我构建了一个Keras模型,该模型具有2个分支,每个分支对同一数据采用不同的特征表示。任务是将句子分为6类。
我已经测试了直到model.fit
的代码,该代码接受一个包含两个输入要素矩阵的列表,分别为X
。一切正常。但是在预测时,当我将两个输入特征矩阵传递给测试数据时,会生成错误。
代码如下:
X_train_feature1 = ... # shape: (2200, 100) each row a sentence and each column a feature
X_train_feature2 = ... # shape: (2200, 13) each row a sentence and each column a feature
y_train= ... # shape: (2200,6)
X_test_feature1 = ... # shape: (587, 100) each row a sentence and each column a feature
X_test_feature2 = ... # shape: (587, 13) each row a sentence and each column a feature
y_test= ... # shape: (587,6)
model= ... #creating a model with 2 branches, see the image below
model.fit([X_train_feature1, X_train_feature2],y_train,epochs=100, batch_size=10, verbose=2) #Model trains ok
model.predict([X_test_feature1, X_test_feature2],y_test,epochs=100, batch_size=10, verbose=2) #error here
错误是:
predictions = model.predict([X_test_feature1,X_test_feature2], y_test, verbose=2)
File "/home/zz/Programs/anaconda3/lib/python3.6/site-packages/keras/engine/training.py", line 1748, in predict
verbose=verbose, steps=steps)
File "/home/zz/Programs/anaconda3/lib/python3.6/site-packages/keras/engine/training.py", line 1290, in _predict_loop
batches = _make_batches(num_samples, batch_size)
File "/home/zz/Programs/anaconda3/lib/python3.6/site-packages/keras/engine/training.py", line 384, in _make_batches
num_batches = int(np.ceil(size / float(batch_size)))
TypeError: only length-1 arrays can be converted to Python scalars
我非常感谢您提供一些帮助,以了解该错误以及如何解决该错误。
答案 0 :(得分:1)
predict
method仅将数据(即x
)和batch_size
(无需设置)作为输入。它不使用标签或纪元作为输入。
如果要预测类别,则应使用predict_classes
方法,该方法为您提供预测的类别标签(而不是predict
方法提供的概率):
preds_prob = model.predict([X_test_feature1, X_test_feature2])
preds = model.predict_classes([X_test_feature1, X_test_feature2])
如果您要根据测试数据评估模型以找到损耗和度量值,则应使用evaluate
方法:
loss_metrics = model.evaluate([X_test_feature1, X_test_feature2], y_test)