Get startedGet started for free

Creating one-hot encoded labels

One-hot encoding converts a single integer label into a vector with N elements, where N is the number of classes. This vector contains zeros and a one at the correct position.

In this exercise, you'll manually create a one-hot encoded vector for y, and then use PyTorch to simplify the process. Your dataset has three classes (0, 1, 2).

numpy (np), torch.nn.functional (F), and torch are already imported for you.

This exercise is part of the course

Introduction to Deep Learning with PyTorch

View Course

Exercise instructions

  • Manually one-hot encode the ground truth label y using the provided NumPy array and save it as one_hot_numpy.
  • Use PyTorch to one-hot encode y and save it as one_hot_pytorch.

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

y = 1
num_classes = 3

# Create the one-hot encoded vector using NumPy
one_hot_numpy = np.array([____, ____, ____])

# Create the one-hot encoded vector using PyTorch
one_hot_pytorch = F.____(torch.tensor(y), num_classes=____)

print("One-hot vector using NumPy:", one_hot_numpy)
print("One-hot vector using PyTorch:", one_hot_pytorch)
Edit and Run Code