Keras Tokenizer num_words似乎不起作用

max*_*mir 11 machine-learning tokenize neural-network deep-learning keras

>>> t = Tokenizer(num_words=3)
>>> l = ["Hello, World! This is so&#$ fantastic!", "There is no other world like this one"]
>>> t.fit_on_texts(l)
>>> t.word_index
{'fantastic': 6, 'like': 10, 'no': 8, 'this': 2, 'is': 3, 'there': 7, 'one': 11, 'other': 9, 'so': 5, 'world': 1, 'hello': 4}
Run Code Online (Sandbox Code Playgroud)

我原本预计t.word_index会有前3个单词.我究竟做错了什么?

Mar*_*jko 11

你在做什么没有错.word_index无论你将在以后使用多少最频繁的单词,就会以相同的方式计算(正如你在这里看到的).因此,当你打电话给任何变形方法时 - Tokenizer将只使用三个最常见的单词,同时,它将保留所有单词的计数器 - 即使它显然不会在以后使用它.


Gad*_*ddy 8

只是对 Marcin 的回答进行补充(“它将保留所有单词的计数器 - 即使很明显它以后不会使用它。”)。

它对所有单词保持反击的原因是您可以fit_on_texts多次调用。每次它都会更新内部计数器,并且在调用转换时,它将使用基于更新的计数器的顶部词。

希望能帮助到你。


far*_*zov 5

将num_words限制为较小的数字(例如 3)对fit_on_texts 输出(例如word_index、word_counts、word_docs )没有影响。它确实对texts_to_matrix产生影响。生成的矩阵将具有num_words (3) 列。

>>> t = Tokenizer(num_words=3)
>>> l = ["Hello, World! This is so&#$ fantastic!", "There is no other world like this one"]
>>> t.fit_on_texts(l)
>>> print(t.word_index)
{'world': 1, 'this': 2, 'is': 3, 'hello': 4, 'so': 5, 'fantastic': 6, 'there': 7, 'no': 8, 'other': 9, 'like': 10, 'one': 11}

>>> t.texts_to_matrix(l, mode='count')
array([[0., 1., 1.],       
       [0., 1., 1.]])
Run Code Online (Sandbox Code Playgroud)