开始使用免费开始使用

图书标题的独热编码

PyBooks 想要编目并分析其馆藏中的图书体裁。请对体裁列表进行独热编码,使其可被机器读取。

已为您导入 torch

本练习是课程的一部分

使用 PyTorch 的文本深度学习

查看课程

练习说明

  • 定义词汇表大小,并保存到 vocab_size
  • 使用合适的 torch 技术结合 vocab_size 创建独热向量。
  • 使用字典推导式创建从体裁到对应独热向量的映射;字典键应为体裁。

交互式实操练习

通过完成这段示例代码来试试这个练习。

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()}')
编辑并运行代码