【问题标题】:Keras Tokenizer num_words doesn't seem to workKeras Tokenizer num_words 似乎不起作用
【发布时间】:2018-02-22 11:00:55
【问题描述】:
>>> 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}

我原以为 t.word_index 只包含前 3 个单词。我做错了什么?

【问题讨论】:

标签: machine-learning neural-network keras deep-learning tokenize


【解决方案1】:

只是在 farid khafizov 的回答中添加一点, 从 texts_to_sequences 的结果中删除 num_words 及以上序列的单词(第 1 句中的 4 个、第 2 句中的 5 个和第 3 句中的 6 个分别消失)

import tensorflow as tf
from tensorflow.keras.preprocessing.text import Tokenizer

print(tf.__version__) # 2.4.1, in my case
sentences = [
    'I love my dog',
    'I, love my cat',
    'You love my dog!'
]

tokenizer = Tokenizer(num_words=4)
tokenizer.fit_on_texts(sentences)
word_index = tokenizer.word_index
seq = tokenizer.texts_to_sequences(sentences)
print(word_index)  # {'love': 1, 'my': 2, 'i': 3, 'dog': 4, 'cat': 5, 'you': 6}
print(seq)         # [[3, 1, 2], [3, 1, 2], [1, 2]]

【讨论】:

    【解决方案2】:

    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.]])
    

    【讨论】:

      【解决方案3】:

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

      它对所有单词保持计数器的原因是您可以多次调用fit_on_texts。每次它会更新内部计数器,当调用转换时,它会根据更新的计数器使用最上面的词。

      希望对你有帮助。

      【讨论】:

        【解决方案4】:

        你所做的并没有错。 word_index 的计算方式相同,无论您稍后将使用多少最常用的词(如您所见 here)。因此,当您调用任何转换方法时 - Tokenizer 将只使用三个最常用的词,同时,它会保留所有词的计数器 - 即使它很明显以后不会使用它。

        【讨论】:

        • 所以num_wordsfit_on_texts() 也没有关系?
        猜你喜欢
        • 2021-01-17
        • 1970-01-01
        • 2020-08-28
        • 2018-11-27
        • 2019-01-12
        • 1970-01-01
        • 2018-05-20
        • 2016-11-29
        • 2016-02-01
        相关资源
        最近更新 更多