開始使用免費開始

對書名進行 one-hot 編碼

PyBooks 想要彙整並分析館藏的書籍類型。請對一份書籍類型清單套用 one-hot 編碼,讓它們能被機器讀取。

已為你匯入 torch

本練習屬於課程

Deep Learning for Text with PyTorch

檢視課程

練習說明

  • 定義詞彙表大小,並存成 vocab_size
  • 使用合適的 torch 技術與 vocab_size 建立 one-hot 向量。
  • 使用字典生成式建立一個從類型到其對應 one-hot 向量的對應表;字典的鍵應該是書籍類型。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

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()}')
編輯並執行程式碼