目前正在研究一个深度学习示例,他们使用了Tokenizer包。我遇到了以下错误:
AttributeError: ‘Tokenizer’ 对象没有属性 ‘word_index’
这是我的代码:
from keras.preprocessing.text import Tokenizersamples = ['The cat say on the mat.', 'The dog ate my homework.']tokenizer = Tokenizer(num_words=1000)tokenizer.fit_on_sequences(samples)sequences = tokenizer.texts_to_sequences(samples)one_hot_results = tokenizer.texts_to_matrix(samples, mode='binary')word_index = tokenizer.word_indexprint('Found %s unique tokens.' % len(word_index))
有谁能帮我找出我的错误吗?
回答:
看起来导入是正确的,但是Tokenizer
对象没有word_index
属性。
根据文档,该属性只有在对Tokenizer
对象调用fit_on_texts
方法后才会设置。
以下代码可以成功运行:
from keras.preprocessing.text import Tokenizer samples = ['The cat say on the mat.', 'The dog ate my homework.'] tokenizer = Tokenizer(num_words=1000) tokenizer.fit_on_texts(samples) one_hot_results = tokenizer.texts_to_matrix(samples, mode='binary') word_index = tokenizer.word_index print('Found %s unique tokens.' % len(word_index))