【问题标题】:What is Keras' Tokenizer fit_on_sequences used for?Keras 的 Tokenizer fit_on_sequences 用于什么?
【发布时间】:2020-12-23 15:21:56
【问题描述】:

我熟悉 Keras Tokenizer 中的“fit_on_texts”方法。 'fit_on_sequences' 有什么作用,什么时候有用?根据documentation,它“根据序列列表更新内部词汇表。”,并将其作为输入:'序列列表。 “序列”是整数词索引的列表。'。什么时候有用?

为了适应文本,我知道文本被解析为标记,并且每个标记都分配了一个索引(整数)。因此,tokenizer 对象包括一个与标记(字符串)和索引(整数)相关的字典。但是,如果我只给它一个数字序列并调用 fit_on_sequences,它怎么知道这些东西代表什么标记?

作为实验,请尝试以下操作:

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

然后,属性 word_index 或 index_word,否则将包含值的字典,当然是空的。该文档还说明了 fit_on_sequences:“在使用 sequences_to_matrix 之前需要(如果从未调用 fit_on_texts)。”但是,在仅调用 fit_on_sequences(而不是 fit_on_texts)之后调用 sequence_to_matrix 不起作用。那么,fit_on_sequences 是做什么用的呢?

【问题讨论】:

    标签: python tensorflow keras tokenize text-processing


    【解决方案1】:

    sequences_to_matrix 在调用fit_on_sequences 后确实有效,您只需在Tokenizer() 实例化中指定参数num_words

    from tensorflow.keras.preprocessing.text import Tokenizer
    
    test_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.]])
    

    开头的零是因为你的序列中没有 0,最后的零是因为我指定了 10 num_words 但你的测试序列中的最大值是 6。

    它的目的只是跳过将整数映射到字符串的步骤。它只使用整数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-01-17
      • 2019-01-28
      • 1970-01-01
      • 1970-01-01
      • 2018-02-20
      • 2019-02-12
      • 2018-02-22
      • 1970-01-01
      相关资源
      最近更新 更多