python回归:使用新数据预测模型



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

值错误:feature_name不匹配:['time','x','y']['0','f1',输入数据训练数据中预期的x、时间、y没有以下字段: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)

这是因为您的模型需要一个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)

xgb期望相同的类型数据用于训练和测试。由于您使用pandas数据帧进行训练,但在预测中给出了numpy数组,因此会出现错误。(此外,正如错误所示,它试图用默认列名f*从该数组中生成一个数据帧(。

因此,一个解决方案是将预测中使用的数组转换为具有取自训练X数据帧的列名的帧:

new_data = [[10,10,10]]
new_data_as_frame = pd.DataFrame(new_data, columns=X.columns)
pred = model.predict(new_data_as_frame)

当我以数据帧的形式提供输入并指定列名时,它就可以工作了。

model = xgb_reg.fit(X, y)
prediction = model.predict(X)
new_data = [[10, 10, 10]]
new_data = pd.DataFrame(new_data, columns=['time', 'x', 'y'])
pred = model.predict(new_data)
print(pred)  # [6.3624153]

相关内容

最新更新