One-hot encoded book titles
PyBooks wants to catalog and analyze the book genres in its library. Apply one-hot encoding to a list of book genres to make them machine-readable.
torch
has been imported for you.
This exercise is part of the course
Deep Learning for Text with PyTorch
Exercise instructions
- Define the size of the vocabulary and save to
vocab_size
. - Create one-hot vectors using the appropriate
torch
technique andvocab_size
. - Create a dictionary mapping genres to their corresponding one-hot vectors using dictionary comprehension; the dictionary keys should be the genre.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
genres = ['Fiction','Non-fiction','Biography', 'Children','Mystery']
# Define the size of the vocabulary
vocab_size = ____(____)
# Create one-hot vectors
one_hot_vectors = torch.____(____)
# Create a dictionary mapping genres to their one-hot vectors
one_hot_dict = {____: ____[i] for i, genre in enumerate(genres)}
for genre, vector in one_hot_dict.items():
print(f'{genre}: {vector.numpy()}')