MulaiMulai sekarang secara gratis

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.

Latihan ini adalah bagian dari kursus

Deep Learning for Text with PyTorch

Lihat Kursus

Petunjuk latihan

  • Define the size of the vocabulary and save to vocab_size.
  • Create one-hot vectors using the appropriate torch technique and vocab_size.
  • Create a dictionary mapping genres to their corresponding one-hot vectors using dictionary comprehension; the dictionary keys should be the genre.

Latihan interaktif praktis

Cobalah latihan ini dengan menyelesaikan kode contoh berikut.

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()}')
Edit dan Jalankan Kode