这基本上是您希望根据您拥有的数据在模型中拥有的词汇量大小。下面这个简单的例子会为你详细讲解。
没有 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 参数。