Keras 功能 API:采用多个输入的拟合和测试模型
Posted
技术标签:
【中文标题】Keras 功能 API:采用多个输入的拟合和测试模型【英文标题】:Keras functional API: fitting and testing model that takes multiple inputs 【发布时间】:2018-12-23 02:54:50 【问题描述】:我构建了一个具有 2 个分支的 Keras 模型,每个分支对相同的数据采用不同的特征表示。任务是将句子分为 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
如果能帮助我理解错误以及如何修复它,我将不胜感激。
【问题讨论】:
【参考方案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)
【讨论】:
以上是关于Keras 功能 API:采用多个输入的拟合和测试模型的主要内容,如果未能解决你的问题,请参考以下文章