You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用PyTorch实现分词句子结合词索引字典转one hot编码张量

正确实现方案

原代码核心问题

  • 语法错误:onehot_vectors 行缩进错误,不属于函数内部代码
  • torch.zeros 参数不符合API要求:第一个参数应为张量形状元组,直接传入分词列表和索引列表无法正常生成张量
  • 缺少词到数值索引的映射步骤:one hot编码的输入是词对应的索引值,不是全零张量
  • 未指定one hot编码的类别数:默认以输入最大索引+1作为类别数,无法匹配实际词表大小

依赖导入

首先确保你已经导入需要的PyTorch模块:

import torch
import torch.nn.functional as F

函数实现

def make_onehot_vectors(sentence, word_to_ix):
    # 分词转对应索引
    word_indices = [word_to_ix[word] for word in sentence]
    # 转换为PyTorch要求的长整型张量
    indices_tensor = torch.tensor(word_indices, dtype=torch.long)
    # 计算词表总大小,适配索引不从0开始的场景
    vocab_size = max(word_to_ix.values()) + 1
    # 生成one hot编码
    onehot_vectors = F.one_hot(indices_tensor, num_classes=vocab_size)
    # 如果需要浮点类型输出可取消下行注释
    # onehot_vectors = onehot_vectors.float()
    return onehot_vectors

测试验证

你给出的测试用例需要配套对应包含this的词表,测试代码如下:

# 测试用词表,this对应索引0
word_dictionary = {'this': 0}
onehot_sentence = make_onehot_vectors(["this"], word_dictionary)
onehot_correct = torch.tensor([[1]])
assert torch.equal(onehot_sentence, onehot_correct)

如果使用你给出的示例词表 word_dictonary={'worddd':1,'wooord':2,'woooord':3},测试输入["worddd"]时,输出结果为 tensor([[0, 1, 0, 0]]),符合one hot编码规则。

内容的提问来源于stack exchange,提问作者Xillobln

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 08:15:05