我正在使用 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'
对于如何使用经过训练的模型进行预测,您有什么建议吗?
model.predict()
期望第一个参数是一个 numpy 数组。您提供一个列表,该列表没有 numpy 数组所具有的 shape
属性。
否则你的代码看起来很好,除了你对预测什么都不做。确保将其存储在变量中,例如:
prediction = model.predict(np.array(tk.texts_to_sequences(text)))
print(prediction)
model.predict_classes(<numpy_array>)
示例 https://gist.github.com/alexcpn/0683bb940cae510cf84d5976c1652abd
您可以使用正确形状的数组“调用”您的模型:
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]])>
您必须使用与构建模型相同的 Tokenizer!
否则,这将为每个单词提供不同的向量。
然后,我正在使用:
phrase = "not good"
tokens = myTokenizer.texts_to_matrix([phrase])
model.predict(np.array(tokens))
您可以使用标记器和填充序列来获取新文本。接下来是模型预测。这会将预测返回为一个 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)])
我在 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)
不定期副业成功案例分享
fit()
中的指标即可。[[0.49334425], [0.4927475 ]]
这样的数组。你能告诉我我应该如何解释这个!(2, 1)
形状,这向我表明您的模型输出一个值,并且您传入了两个输入向量。这就是我能说的。对于未来的问题,请打开一个包含更多详细信息和特定问题的新问题!