在 PyTorch 中使用 Embedding
PyBooks 透過書籍推薦系統獲得成功。然而,該系統尚未納入文字中部分語意。PyTorch 內建的 embedding 層可以直接從資料中學習並表示詞與詞之間的關係。你的團隊想探索這個能力,以改進書籍推薦系統。你能協助實作嗎?
torch 與 torch.nn(簡寫為 nn)已為你匯入。
本練習屬於課程
Deep Learning for Text with PyTorch
練習說明
- 將
words中的每個單字對應到唯一的索引,存成word_to_idx。 - 將
word_to_idx轉換為 PyTorch 張量,並存為inputs。 - 使用
torch模組初始化一個 10 維的 embedding 層。 - 將
inputs張量傳入 embedding 層,並檢視輸出。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Map a unique index to each word
words = ["This", "book", "was", "fantastic", "I", "really", "love", "science", "fiction", "but", "the", "protagonist", "was", "rude", "sometimes"]
word_to_idx = {word: ____ for i, word in enumerate(____)}
# Convert word_to_idx to a tensor
inputs = ____.____([word_to_idx[w] for w in words])
# Initialize embedding layer with ten dimensions
embedding = nn.____(num_embeddings=len(words), embedding_dim=____)
# Pass the tensor to the embedding layer
output = embedding(____)
print(output)