Sou*_*neS 2 python regression predict pandas xgboost
我有一个包含 36540 行的数据框。目标是预测y HITS_DAY。
#数据
https://github.com/soufMiashs/Predict_Hits
我正在尝试训练非线性回归模型,但模型似乎并没有学到太多东西。
X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.20, random_state=42)
data_dmatrix = xgb.DMatrix(data=x,label=y)
xg_reg = xgb.XGBRegressor(learning_rate = 0.1, objectif='reg:linear', max_depth=5,
n_estimators = 1000)
xg_reg.fit(X_train,y_train)
preds = xg_reg.predict(X_test)
df=pd.DataFrame({'ACTUAL':y_test, 'PREDICTED':preds})
Run Code Online (Sandbox Code Playgroud)
我究竟做错了什么?
您没有做任何特别错误的事情(除了可能不存在的objectif参数),但是,您必须考虑如何工作。它将尝试创建“树”。树根据特征值进行分裂。从此处显示的图中可以看出,超过 0 的样本非常少。因此,随机分割测试序列可能会导致测试集几乎没有值高于 0 的样本(因此是一条水平线)。xgboostxgboost
除此之外,您似乎想在非线性数据上拟合线性模型。选择不同的objective功能可能会有所帮助。
最后,你怎么知道你的模型没有学习任何东西?我没有看到任何评估指标来证实这一点。尝试为您的模型考虑有意义的评估指标并展示它们。这将帮助您确定您的模型是否“足够好”。
总结一下:
从这个例子看来,你的模型确实在学习一些东西,即使没有参数调整(你应该这样做!)。
import pandas
import xgboost
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error, r2_score
# Read the data
df = pandas.read_excel("./data.xlsx")
# Split in X and y
X = df.drop(columns=["HITS_DAY"])
y = df["HITS_DAY"]
# Show the values of the full dataset in a plot
y.sort_values().reset_index()["HITS_DAY"].plot()
# Split in test and train, use stratification to make sure the 2 groups look similar
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.20, random_state=42, stratify=[element > 1 for element in y.values]
)
# Show the plots of the test and train set (make sure they look similar!)
y_train.sort_values().reset_index()["HITS_DAY"].plot()
y_test.sort_values().reset_index()["HITS_DAY"].plot()
# Create the regressor
estimator = xgboost.XGBRegressor(objective="reg:squaredlogerror")
# Fit the regressor
estimator.fit(X_train, y_train)
# Predict on the test set
predictions = estimator.predict(X_test)
df = pandas.DataFrame({"ACTUAL": y_test, "PREDICTED": predictions})
# Show the actual vs predicted
df.sort_values("ACTUAL").reset_index()[["ACTUAL", "PREDICTED"]].plot()
# Show some evaluation metrics
print(f"Mean squared error: {mean_squared_error(y_test.values, predictions)}")
print(f"R2 score: {r2_score(y_test.values, predictions)}")
Run Code Online (Sandbox Code Playgroud)
输出:
Mean squared error: 0.01525351142868279
R2 score: 0.07857787102063485
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3335 次 |
| 最近记录: |