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.

你可能感兴趣的:(NLP)