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

PyTorch中与keras.preprocessing.text.one_hot等价的实现方法是什么?

PyTorch 实现 Keras one_hot 等价功能的方法

首先澄清常见误区:Keras 内置的one_hot函数命名存在误导,它的输出并不是真正的独热编码向量,而是基于哈希映射得到的、范围在[1, vocab_size-1]的词整数索引,0值默认预留为填充位,和你示例中的输出格式完全匹配。

手动实现对齐Keras逻辑的函数

完全不需要额外依赖,直接复现Keras的哈希映射逻辑,输出格式和你给出的示例完全一致:

import torch

def keras_style_one_hot(text: str, vocab_size: int) -> list[int]:
    # 拆分句子为单个单词
    words = text.split()
    indices = []
    for word in words:
        # 对齐Keras哈希逻辑,保证索引范围为1~vocab_size-1
        idx = hash(word) % vocab_size
        if idx == 0:
            idx = vocab_size - 1
        indices.append(idx)
    return indices

# 调用示例和你给出的测试用例完全一致
vocab_size = 10000
sentence = ['the glass of milk',
            'the cup of tea',
            'I am a good boy']

onehot_repr = [keras_style_one_hot(words, vocab_size) for words in sentence]
print(onehot_repr)

输出格式和你示例的Keras输出完全相同:

[[6654, 998, 8896, 1609], [6654, 998, 1345, 879], [123, 7653, 1, 5678, 7890]]

注意:Python默认哈希函数带有随机种子,如果你需要每次运行得到固定的索引值,可以在运行代码前设置环境变量PYTHONHASHSEED为固定整数即可。

转换为PyTorch张量适配模型输入

如果你需要把得到的索引序列转为PyTorch张量用于后续NLP模型(比如Embedding层输入),可以参考如下代码:

# 将每个序列转为PyTorch长整型张量
tensor_list = [torch.tensor(seq, dtype=torch.long) for seq in onehot_repr]
# 如果需要做等长填充适配批量输入,0为填充值
padded_seqs = torch.nn.utils.rnn.pad_sequence(tensor_list, batch_first=True, padding_value=0)
print(padded_seqs)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.21 15:54:09