【发布时间】:2020-05-17 18:04:49
【问题描述】:
我目前正在学习 TensorFlow 系列的机器学习。在这种情况下是关于文本分类的。正如您在代码中看到的,我已经训练了模型并将其保存为文件进行测试。
加载保存的文件
modelFile = keras.models.load_model('model_text_classification.h5')
编码函数:
def review_encode(string):
'''look up the mapping of all the words and return to us an encoded list'''
encoded = [1] # start with 1 as a starting tag as the system with word_index['<START>'] = 1
for word in string:
if word in word_index:
encoded.append(word_index[word.lower()])
else:
encoded.append(2) # as the END tag
return encoded
预处理:
- 文件是一个大字符串,但我需要将其转换为数字的编码列表
- 文本的大小最多只有 256 个字,因为这是我在训练数据时使用的方式
with open('lion_king.txt', encoding = 'utf-8') as f:
for line in f.readlines():
nline = line.replace(',', '').replace('.', '').replace('(', '').replace(')', '').replace('\"', '').replace(':', '')
nline = nline.split(' ')
# encode and trim the data down to 256 words
encode = review_encode(nline)
encode = keras.preprocessing.sequence.pad_sequences([encode], value = word_index['<PAD>'], padding = 'post', maxlen = 256) # [encode], because is expecting a list of lists
# using the model to make a prediction
predict = model.predict_classes(encode)
print(line)
print(encode)
print(predict(encode[0])) #HERE IS ERROR
预期输出:
将预测打印为 96% 肯定。
示例: [0.9655667]
完整的追溯:
TypeError Traceback (most recent call last)
<ipython-input-58-790c338a89ce> in <module>()
13 print(line)
14 print(encode)
---> 15 print(predict(encode[0]))
TypeError: 'numpy.ndarray' object is not callable
【问题讨论】:
-
您希望
predict(encode[0])做什么?您是否希望调用一些predict函数? (如果是这样,您不应该为predict(encode[0])重复使用predict名称。)或者您不确定如何访问您计算的预测结果中的数据? -
@user2357112supportsMonica predict 是 keras 中的一个函数,它返回回归的分数。在这种情况下,电影评论的预测(大约 96% 是肯定的)。例如:[0.9655667]
-
那么您不应该重复使用
predict = model.predict_classes(encode)的名称。 -
@user2357112supportsMonica 我认为它不会那样工作。 numpy 数组中称为 encode 的数据实例可以传递给模型上的 predict_classes() 函数,以预测数组中每个实例的类值。我可以将其更改为任何名称,但仍然会给我同样的错误。
标签: python numpy tensorflow numpy-ndarray