【问题标题】:What is the actual use of num_words parameter in keras Tokenizer? How much overall does it affect the accuracy of my modelkeras Tokenizer中num_words参数的实际用途是什么?它对我的模型的准确性有多大影响
【发布时间】:2021-04-07 22:12:34
【问题描述】:

在给定的代码行tokenizer=Tokenizer(num_words=, oov_token= '<OOV>') 中,num_words 参数实际上做了什么以及在确定分配给它的值之前要考虑什么。给它分配一个非常高的值和一个非常低的值会有什么影响。

【问题讨论】:

标签: tensorflow keras deep-learning nlp nltk


【解决方案1】:

这基本上是您希望根据您拥有的数据在模型中拥有的词汇量大小。下面这个简单的例子会为你详细讲解。

没有 num_words:

import tensorflow as tf
from tensorflow.keras.preprocessing.text import Tokenizer
tokenizer  = Tokenizer(oov_token='<OOV>')
fit_text = ["Example with the first sentence of the tokenizer"]
tokenizer.fit_on_texts(fit_text)
test_text = ["Example with the test sentence of the tokenizer"]
sequences = tokenizer.texts_to_sequences(test_text)

print("sequences : ",sequences,'\n')

print("word_index : ",tokenizer.word_index) 

print("word counts : ",tokenizer.word_counts) 

sequences :  [[3, 4, 2, 1, 6, 7, 2, 8]] 

word_index :  {'<OOV>': 1, 'the': 2, 'example': 3, 'with': 4, 'first': 5, 'sentence': 6, 'of': 7, 'tokenizer': 8}
word counts :  OrderedDict([('example', 1), ('with', 1), ('the', 2), ('first', 1), ('sentence', 1), ('of', 1), ('tokenizer', 1)]) 

这里tokenizer.fit_on_texts(fit_text) 将创建fit_text 中提到的单词的word_index,顺序从oov_token 开始,即1,然后是word_counts 中最常见的单词。
如果您不提及num_words,那么fit_text 的所有唯一词将被视为word_index,并将用于表示sequences

如果存在num_words,那么它将将序列限制为num_words -1 来自word_index 的单词将仅在使用tokenizer.texts_to_sequences() 时被视为形成序列,如果在num_words -1 之外存在任何单词,它将是视为oov_token
下面是它的例子。

使用 num_words:

tokenizer  = Tokenizer(num_words=4,oov_token='<OOV>')
fit_text = ["Example with the first sentence of the tokenizer"]
tokenizer.fit_on_texts(fit_text)
test_text = ["Example with the test sentence of the tokenizer"]
sequences = tokenizer.texts_to_sequences(test_text)

print("sequences : ",sequences,'\n')

print("word_index : ",tokenizer.word_index)

print("word counts : ",tokenizer.word_counts) 

sequences :  [[3, 1, 2, 1, 1, 1, 2, 1]] 

word_index :  {'<OOV>': 1, 'the': 2, 'example': 3, 'with': 4, 'first': 5, 'sentence': 6, 'of': 7, 'tokenizer': 8}
word counts :  OrderedDict([('example', 1), ('with', 1), ('the', 2), ('first', 1), ('sentence', 1), ('of', 1), ('tokenizer', 1)]) 

关于模型的准确性,最好从数据中正确地表示单词序列而不是oov_token
在大数据的情况下,最好提供 num_words 参数而不是给模型加载。
最好先进行stopword removal,lemmatization/stemming 之类的预处理以删除所有不必要的单词,然后再使用Tokenizer 处理预处理数据以更好地选择num_words 参数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-01-17
    • 2020-08-28
    • 2018-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-02
    相关资源
    最近更新 更多