1

the function failed at prediction with the error:

        f"Feature shape mismatch, expected: {self.num_features()}, "
ValueError: Feature shape mismatch, expected: 395, got 395

testX - 1 X 395 (Dataframe) trainX - n X 395 (Dataframe)

def xgboost_forecast(train, testX):
    # split into input and output columns
    testX = np.asarray(testX)
    testX = testX.reshape(-1, 1)
    trainX, trainy = train.iloc[:, :-1], train.iloc[:, -1]
    trainy = np.asarray(trainy)
    trainy = trainy.reshape(-1, 1)
    # fit model
    model = xgb.XGBClassifier()
    model.fit(trainX.values, trainy.values)
    yhat = model.predict(testX) ##crash
efrat
  • 13
  • 1
  • 4

1 Answers1

0

I hit the same issue today, yet in a small percentage of my fit/predict cycles. This, below, appears to have gotten me around the problem, as I put this snippet after fitting the first time in a try: block and hitting the same error...

try:
    self.y_pred_DEBUG = pModel.predict( dataForPreds )
except ValueError:
    fNames_Error = pModel.get_booster().feature_names;
    alteredDataForPreds = dataForPreds[fNames_Error];
    self.y_pred_DEBUG = pModel.predict( alteredDataForPreds )
  • BTW - I think the XGBoost code that prints out the error message has a bug in it, I saw in my stack trace that I no longer have. The code seemed to be testing on df.shape[1] but the error message in the exception is using df.shape[0] to print. Notice in your error it says "expected: 395, got 395", which seems wrong if we are talking about an exception where the two values are supposedly different. – BigDummy Jun 15 '21 at 04:47