简体   繁体   中英

Keras functional API: fitting and testing model that takes multiple inputs

I build a Keras model that has 2 branches, each taking a different feature representation for the same data. The task is classifying sentences into one of 6 classes.

I have tested my code up to model.fit that takes in a list containing the two input feature matrices as X . Everything works OK. But on prediction, when I pass the two input feature matrices for test data, an error is generated.

The code is as follows:

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

The model looks like this: 在此处输入图片说明

And the error is:

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

I would really appreciate some help to understand the error and how to fix it.

The predict method only takes as input the data (ie x ) and the batch_size (it is not necessary to set this). It does not take labels or epochs as inputs.

If you want to predict classes then you should use predict_classes method which gives you the predicted class labels (rather than the probabilities which predict method gives):

preds_prob = model.predict([X_test_feature1, X_test_feature2])
preds = model.predict_classes([X_test_feature1, X_test_feature2])

And if you want to evaluate your model on the test data to find the loss and metric values then you should use evaluate method:

loss_metrics = model.evaluate([X_test_feature1, X_test_feature2], y_test)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM