Keras tokenizer.fit_on_texts 做了什么?

如何使用 Keras Tokenizer 方法 fit_on_texts

它与 fit_on_sequences 有何不同?


回答:

fit_on_textstexts_to_matrix 结合使用时,会为文本生成独热编码,详见 https://www.tensorflow.org/text/guide/word_embeddings

enter image description here

fit_on_texts

使用 fit_on_texts 的示例

from keras.preprocessing.text import Tokenizertext='check check fail'tokenizer = Tokenizer()tokenizer.fit_on_texts([text])tokenizer.word_index

将生成 {'check': 1, 'fail': 2}

注意,我们使用 [text] 作为参数,因为输入必须是一个列表,列表的每个元素被视为一个标记。输入也可以是文本生成器或字符串列表的列表。

将文本生成器作为输入传递是内存高效的,这里是一个例子:(1)定义一个返回可迭代文本集合的文本生成器

def text_generator(texts_generator):    for texts in texts_generator:        for text in texts:            yield text

(2)将其作为输入传递给 fit_on_texts

tokenizer.fit_on_text(text_generator)

fit_on_texts 在调用 texts_to_matrix 之前使用,后者为原始文本集生成独热编码。

num_words 参数

num_words 参数传递给分词器将指定我们考虑在表示中的(最频繁的)单词数量。一个示例,首先 num_words = 1,我们只对最频繁的单词 love 进行编码

sentences = [    'i love my dog',    'I, love my cat',    'You love my dog!']tokenizer = Tokenizer(num_words = 1+1)tokenizer.fit_on_texts(sentences)tokenizer.texts_to_sequences(sentences) # [[1], [1], [1]]

其次,num_words = 100,我们对100个最频繁的单词进行编码

tokenizer = Tokenizer(num_words = 100+1)tokenizer.fit_on_texts(sentences)tokenizer.texts_to_sequences(sentences) # [[3, 1, 2, 4], [3, 1, 2, 5], [6, 1, 2, 4]]

fit_on_sequences

Fit_on_sequences 适用于“序列”,即整数单词索引的列表。它在调用 sequence_to_matrix 之前使用

from tensorflow.keras.preprocessing.text import Tokenizertest_seq = [[1,2,3,4,5,6]]tok = Tokenizer(num_words=10)tok.fit_on_sequences(test_seq)tok.sequences_to_matrix(test_seq)

生成

array([[0., 1., 1., 1., 1., 1., 1., 0., 0., 0.]])

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注