Keras,训练模型后如何预测?


87

我正在使用路透社示例数据集,它运行良好(我的模型已经过训练)。我阅读了有关如何保存模型的信息,因此以后可以加载它以再次使用。但是,如何使用此保存的模型来预测新文本?我用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'

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

Answers:


61

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

否则,您的代码看起来会很好,除了您对预测不执行任何操作。确保将其存储在变量中,例如:

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

有没有一种方法可以使用keras softmax概率仅打印前k个?
唐纳德

1
@唐纳德是的。只需在中的指标中添加“ top_k_categorical_accuracy”即可fit()
nemo


5

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

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

然后,我正在使用:

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

model.predict(np.array(tokens))

1

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

1

您可以使用正确形状的数组“调用”模型:

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]])>
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.