Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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: enter image description here

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.

like image 625
Ziqi Avatar asked Nov 30 '25 01:11

Ziqi


1 Answers

The predict method only takes as input the data (i.e. 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)
like image 170
today Avatar answered Dec 02 '25 15:12

today



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!