Keras实现单词级的one-hot编码

这是对英文文本进行处理

# 导入相关文本处理包
In [1]: from keras.preprocessing.text import Tokenizer

# 两个句子示例
In [2]: samples = ['The cat sat on the mat.', 'The dog ate my homework.']

# 创建一个分词器(tokenizer),设置为只考虑前 1000 个最常见的单词
In [3]: tokenizer = Tokenizer(num_words=1000)

# 传入文本,构建单词索引
In [4]: tokenizer.fit_on_texts(samples)

# 将字符串转换为整数索引组成的列表
In [6]: sequences = tokenizer.texts_to_sequences(samples)

# 打印该索引列表,每个索引代表一个单词
In [7]: sequences
Out[7]: [[1, 2, 3, 4, 1, 5], [1, 6, 7, 8, 9]]

# 得到 one-hot 二进制表示。这个分词器也支持除 one-hot 编码外的其他向量化模式
In [8]: one_hot_results = tokenizer.texts_to_matrix(samples, mode='binary')

# 打印one-hot编码
In [9]: one_hot_results
Out[9]:
array([[0., 1., 1., ..., 0., 0., 0.],
       [0., 1., 0., ..., 0., 0., 0.]])

# 找回单词索引
In [10]: word_index = tokenizer.word_index

In [11]: word_index
Out[11]:
{'the': 1,
 'cat': 2,
 'sat': 3,
 'on': 4,
 'mat': 5,
 'dog': 6,
 'ate': 7,
 'my': 8,
 'homework': 9}

# 单词索引个数
In [12]: print('Found %s unique tokens.' % len(word_index))
Found 9 unique tokens.
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值