首页 > 解决方案 > keras 和 nlp - 何时使用 .texts_to_matrix 而不是 .texts_to_sequences?

问题描述

Keras 提供了几个辅助函数来处理文本:

texts_to_sequencestexts_to_matrix

似乎大多数人都使用 texts_to_sequences,但我不清楚为什么选择一个而不是另一个,以及在什么条件下您可能想要使用texts_to_matrix.

标签: kerasnlp

解决方案


texts_to_matrix 很容易理解。它将文本转换为矩阵,其中的列表示单词和带有出现次数或存在次数的单元格。这样的设计对于直接应用 ML 算法(逻辑回归、决策树等)很有用。

texts_to_sequence 将创建表示单词的整数集合的列表。某些函数(如 Keras 嵌入)需要这种格式进行预处理。

考虑下面的例子。

txt = ['Python is great and useful', 'Python is easy to learn', 'Python is easy to implement']
txt = pd.Series(txt)

tok = Tokenizer(num_words=10)
tok.fit_on_texts(txt)
mat_texts = tok.texts_to_matrix(txt, mode='count')
mat_texts

输出:array([[0., 1., 1., 0., 0., 1., 1., 1., 0., 0.], [0., 1., 1., 1., 1., 0., 0., 0., 1., 0.], [0., 1., 1., 1., 1., 0., 0., 0., 0., 1.] ])

tok.get_config()['word_index']

输出:'{“python”:1,“is”:2,“easy”:3,“to”:4,“great”:5,“and”:6,“useful”:7,“learn”: 8、“实现”:9}'

mat_texts_seq = tok.texts_to_sequences(txt)
mat_texts_seq

输出:- [[1, 2, 5, 6, 7], [1, 2, 3, 4, 8], [1, 2, 3, 4, 9]]


推荐阅读