在 PyTorch 中使用 Embedding
PyBooks 通过图书推荐系统取得了成功。不过,该系统尚未考虑文本中的部分语义信息。PyTorch 内置的嵌入层可以直接从数据中学习并表示词与词之间的关系。您的团队希望探索这一能力,以改进图书推荐系统。您能帮忙实现吗?
torch 和 torch.nn(简称 nn)已为您导入。
本练习是课程的一部分
使用 PyTorch 的文本深度学习
练习说明
- 为
words中的每个词映射一个唯一索引,并保存为word_to_idx。 - 将
word_to_idx转换为 PyTorch 张量,并保存为inputs。 - 使用
torch模块初始化一个具有 10 个维度的嵌入层。 - 将
inputs张量传入嵌入层,并查看输出。
交互式实操练习
通过完成这段示例代码来试试这个练习。
# 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)