Python Keras,我如何在训练模型后进行预测?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37891954/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 20:04:38  来源:igfitidea点击:

Keras, how do I predict after I trained a model?

pythontheanodeep-learningkeras

提问by ben

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()?

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

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

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

I tried it with

我试过了

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)

But I always get

但我总是得到

(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:\Users\bkey\Anaconda2\lib\site-packages\keras\models.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:\Users\bkey\Anaconda2\lib\site-packages\keras\engine\training.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:\Users\bkey\Anaconda2\lib\site-packages\keras\engine\training.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?

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

回答by nemo

model.predict()expects the first parameter to be a numpy array. You supply a list, which does not have the shapeattribute a numpy array has.

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

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)

回答by Thomas Decaux

You must use the same Tokenizer you used to build your model!

您必须使用用于构建模型的相同 Tokenizer!

Else this will give different vector to each word.

否则,这将为每个单词提供不同的向量。

Then, I am using:

然后,我正在使用:

phrase = "not good"
tokens = myTokenizer.texts_to_matrix([phrase])

model.predict(np.array(tokens))

回答by tauseef_CuriousGuy

I trained a neural network in Keras to perform non linear regression on some data. This is some part of my code for testing on new data using previously saved model configuration and weights.

我在 Keras 中训练了一个神经网络来对一些数据执行非线性回归。这是我使用以前保存的模型配置和权重测试新数据的代码的一部分。

fname = r"C:\Users\tauseef\Desktop\keras\tutorials\BestWeights.hdf5"
modelConfig = joblib.load('modelConfig.pkl')
recreatedModel = Sequential.from_config(modelConfig)
recreatedModel.load_weights(fname)
unseenTestData = np.genfromtxt(r"C:\Users\tauseef\Desktop\keras\arrayOf100Rows257Columns.txt",delimiter=" ")
X_test = unseenTestData
standard_scalerX = StandardScaler()
standard_scalerX.fit(X_test)
X_test_std = standard_scalerX.transform(X_test)
X_test_std = X_test_std.astype('float32')
unseenData_predictions = recreatedModel.predict(X_test_std)