Keras,我如何在训练模型后进行预测? [英] Keras, how do I predict after I trained a model?

查看:50
本文介绍了Keras,我如何在训练模型后进行预测?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 reuters-example 数据集,它运行良好(我的模型已经过训练).我阅读了有关如何保存模型的信息,以便稍后加载以再次使用.但是我如何使用这个保存的模型来预测新文本?我使用 models.predict() 吗?

I'm playing with the reuters-example dataset and it runs fine (my model is trained). I read about how to save a model, so I could load it later to use again. But how do I use this saved model to predict a new text? Do I use models.predict()?

我必须以特殊的方式准备这篇文章吗?

Do I have to prepare this text in a special way?

我试过了

import keras.preprocessing.text

text = np.array(['this is just some random, stupid text'])
print(text.shape)

tk = keras.preprocessing.text.Tokenizer(
        nb_words=2000,
        filters=keras.preprocessing.text.base_filter(),
        lower=True,
        split=" ")

tk.fit_on_texts(text)
pred = tk.texts_to_sequences(text)
print(pred)

model.predict(pred)

但我总是得到

(1L,)
[[2, 4, 1, 6, 5, 7, 3]]
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-83-42d744d811fb> in <module>()
      7 print(pred)
      8 
----> 9 model.predict(pred)

C:UserskeyAnaconda2libsite-packageskerasmodels.pyc in predict(self, x, batch_size, verbose)
    457         if self.model is None:
    458             self.build()
--> 459         return self.model.predict(x, batch_size=batch_size, verbose=verbose)
    460 
    461     def predict_on_batch(self, x):

C:UserskeyAnaconda2libsite-packageskerasengine	raining.pyc in predict(self, x, batch_size, verbose)
   1132         x = standardize_input_data(x, self.input_names,
   1133                                    self.internal_input_shapes,
-> 1134                                    check_batch_dim=False)
   1135         if self.stateful:
   1136             if x[0].shape[0] > batch_size and x[0].shape[0] % batch_size != 0:

C:UserskeyAnaconda2libsite-packageskerasengine	raining.pyc in standardize_input_data(data, names, shapes, check_batch_dim, exception_prefix)
     79     for i in range(len(names)):
     80         array = arrays[i]
---> 81         if len(array.shape) == 1:
     82             array = np.expand_dims(array, 1)
     83             arrays[i] = array

AttributeError: 'list' object has no attribute 'shape'

对于如何使用经过训练的模型进行预测,您有什么建议吗?

Do you have any recommendations as to how to make predictions with a trained model?

推荐答案

model.predict() 期望第一个参数是一个 numpy 数组.您提供一个列表,该列表不具有 numpy 数组所具有的 shape 属性.

否则你的代码看起来不错,只是你没有对预测做任何事情.确保将其存储在变量中,例如:

Otherwise your code looks fine, except that you are doing nothing with the prediction. Make sure you store it in a variable, for example like this:

prediction = model.predict(np.array(tk.texts_to_sequences(text)))
print(prediction)

这篇关于Keras,我如何在训练模型后进行预测?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆