[英]python regression: predicting model with new data
我正在尝试使用新数据来预测新结果,但是,我正在处理以下错误:
ValueError: feature_names mismatch: ['time', 'x', 'y'] ['f0', 'f1', 'f2'] 输入数据训练数据中的预期 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]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.