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

107

我正在使用 reuters-example 数据集进行实验,并且表现良好(我的模型已经训练完毕)。我了解了如何保存模型,以便稍后加载并再次使用。但是,如何使用保存的模型来预测新文本呢?我需要使用 models.predict() 吗?

我是否需要以特殊的方式准备这个文本?

我尝试了一下:

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:\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'

您有没有任何建议,关于如何使用已训练好的模型进行预测?

6个回答

69

model.predict()函数期望第一个参数是一个NumPy数组。你提供了一个列表,它没有像NumPy数组那样具有shape属性。

除此之外,你的代码看起来没问题,只是你对预测结果没有任何操作。请确保把它存储在一个变量中,例如这样:

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

有没有一种方法可以使用Keras softmax概率仅打印前k个? - donald
2
@donald 是的。只需在 fit() 中的指标中添加 'top_k_categorical_accuracy' 即可。 - nemo
这给我一个像 [[0.49334425], [0.4927475]] 这样的数组。请问我应该如何解释它? - Sourav Kannantha B
@SouravKannanthaB 一般来说不行,这取决于你的模型、任务和手头的问题。你手头的输出形状为(2,1),这表明你的模型输出一个值,而你传入了两个输入向量。这就是我能说的全部。对于未来的问题,请提出一个新问题,并提供更多细节和具体问题! - nemo

10

7
您只需使用正确形状的数组“调用”模型:
model(np.array([[6.7, 3.3, 5.7, 2.5]]))

完整示例:

from sklearn.datasets import load_iris
from tensorflow.keras.layers import Dense
from tensorflow.keras.models import Sequential
import numpy as np

X, y = load_iris(return_X_y=True)

model = Sequential([
    Dense(16, activation='relu'),
    Dense(32, activation='relu'),
    Dense(1)])

model.compile(loss='mean_absolute_error', optimizer='adam')

history = model.fit(X, y, epochs=10, verbose=0)

print(model(np.array([[6.7, 3.3, 5.7, 2.5]])))

<tf.Tensor: shape=(1, 1), dtype=float64, numpy=array([[1.92517677]])>

5

你必须使用与构建模型时相同的分词器(Tokenzier)!

否则,每个单词将会被赋予不同的向量。

接着,我正在使用:

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

model.predict(np.array(tokens))

2
你可以使用分词器和填充序列来处理新的文本。接下来是模型预测,它将返回一个numpy数组以及标签本身。
例如:
new_complaint = ['Your service is not good']
seq = tokenizer.texts_to_sequences(new_complaint)
padded = pad_sequences(seq, maxlen=maxlen)
pred = model.predict(padded)
print(pred, labels[np.argmax(pred)])

0

我在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)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接