Home > Software engineering >  ValueError: operands could not be broadcast together with shapes (7,) (624,3) while doing weighted p
ValueError: operands could not be broadcast together with shapes (7,) (624,3) while doing weighted p

Time:09-17

I am doing an ensemble of predicted probabilities from seven models. Each model outputs three classes. I calculated the weights in prior to be given for the predictions from each of the seven models.These predicted weights are stored in the variable "prediction_weights". The weighted averaging code is given below:

prediction_weights = np.array([[3.66963025e-01, 1.08053256e-01,1.14617370e-01, 4.10366349e-01,
 6.16391075e-14, 4.37376684e-14, 9.26785075e-18]]) 
weighted_predictions7 = np.zeros((nb_test_samples, num_classes), 
                                dtype='float32')
for weight, prediction in zip(prediction_weights, preds):
    weighted_predictions7  = weight * prediction    
yPred7 = np.argmax(weighted_predictions7, axis=1)
yTrue = Y_test.argmax(axis=-1)
accuracy = metrics.accuracy_score(yTrue, yPred7) * 100

np.savetxt('weighted_averaging_7_y_pred.csv',
            weighted_predictions7,fmt='%f',
            delimiter = ",")

I get the following error:

  File "<ipython-input-16-8f3a15c0fec1>", line 2, in <module>
    weighted_predictions7  = weight * prediction

ValueError: operands could not be broadcast together with shapes (7,) (624,3) 

The following are the shapes of the variables:

    prediction_weights: (1,7) - Array of Float 64
    nb_test_samples: 1 - int
    num_classes: 1 - int
    weighted_predictions7: (624,3) - Array of float32
    Y_test: (624,3) - Array of float32
    yTrue: (624,) - Array of Int64

CodePudding user response:

Simply replacing

prediction_weights = np.array([[3.66963025e-01, 1.08053256e-01,1.14617370e-01, 4.10366349e-01,
 6.16391075e-14, 4.37376684e-14, 9.26785075e-18]]) 

by

prediction_weights = [3.66963025e-01, 1.08053256e-01,1.14617370e-01, 4.10366349e-01,
 6.16391075e-14, 4.37376684e-14, 9.26785075e-18] 

resolved the error.

  • Related