首页 > 解决方案 > python回归:用新数据预测模型

问题描述

我正在尝试使用新数据来预测新结果,但是,我正在处理以下错误:

ValueError: feature_names mismatch: ['time', 'x', 'y'] ['f0', 'f1', 'f2'] expected x, time, y in input data training data没有以下字段:f0 , f1, f2

我不明白为什么,因为我有 3 个预测变量,并且我在数组中使用了 3 个值。

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
import xgboost as xgb
import datetime
import seaborn as sns
from numpy import asarray

data=[[1, 1,2 ,5],
        [2, 5,5,6],
        [3, 4,6,6]
        ,[5, 6,5,6],
        [7,9,9,7],
        [8, 7,9,4]
        ,[9, 2,3,8],
        [2, 5,1,9],
        [2,2,10,9]
        ,[3, 8,2,8],
        [6, 5,4,10],
        [6, 8,5 ,10]]
df = pd.DataFrame(data, columns=['time','x','y','target'])
xgb_reg=xgb.XGBRegressor( n_estimators= 30, max_depth=8, eta= 0.1, colsample_bytree= 0.4, subsample= 0.4) #(n_estimators=250, max_depth=15, eta=0.1, subsample=0.4, colsample_bytree=0.4)
y = (df.target)
X=df.drop(['target'], axis = 1)
print('========1=============')
model=xgb_reg.fit(X,y)
prediction=model.predict(X)
new_data=[[10,10,10]]
new_data_asarray=asarray(new_data)
pred=model.predict(new_data_asarray)
print(pred)

标签: pythonpandasmachine-learningprediction

解决方案


这是因为您的模型需要一个 pandas 数据框作为输入。

只需在训练之前将您的 X 数据框转换为 numpy 数组,如下所示。

import numpy as np
import pandas as pd
import xgboost as xgb


data = [
    [1, 1, 2, 5],
    [2, 5, 5, 6],
    [3, 4, 6, 6],
    [5, 6, 5, 6],
    [7, 9, 9, 7],
    [8, 7, 9, 4],
    [9, 2, 3, 8],
    [2, 5, 1, 9],
    [2, 2, 10, 9],
    [3, 8, 2, 8],
    [6, 5, 4, 10],
    [6, 8, 5, 10],
]
df = pd.DataFrame(data, columns=["time", "x", "y", "target"])
xgb_reg = xgb.XGBRegressor(
    n_estimators=30, max_depth=8, eta=0.1, colsample_bytree=0.4, subsample=0.4
)  # (n_estimators=250, max_depth=15, eta=0.1, subsample=0.4, colsample_bytree=0.4)
y = df.target
X = df.drop(["target"], axis=1)

X = X.to_numpy()

print("========1=============")
model = xgb_reg.fit(X, y)
prediction = model.predict(X)
new_data = [[10, 10, 10]]
new_data_asarray = np.asarray(new_data)
pred = model.predict(new_data_asarray)
print(pred)

推荐阅读