XGBoost
XGBoost is the leading model for working with standard tabular data (the type of data you store in Pandas DataFrames, as opposed to more exotic types of data like images and videos). XGBoost models dominate many Kaggle competitions.
XGBoost is an implementation of the Gradient Boosted Decision Trees algorithm.
我们通过循环构建新模型,并将它们组合成一个整体模型。开始通过计算数据集中每个观察记录的误差来启动循环, 然后我们构建一个新模型来预测这些,我们将此错误预测模型的预测添加到“模型集合”中。
为了进行预测,我们添加了以前所有模型的预测。 我们可以使用这些预测来计算新错误,构建下一个模型,并将其添加到整体中。
在这个循环之外有一点, 我们需要一些基础预测来开始循环。 在实践中,最初的预测可能非常幼稚。 即使它的预测非常不准确,随后对整体的添加也将解决这些错误。
- 基础使用
from xgboost import XGBRegressor
my_model = XGBRegressor()
# Add silent=True to avoid printing out updates with each cycle
my_model.fit(train_X, train_y, verbose=False)
# make predictions
predictions = my_model.predict(test_X)
print("Mean Absolute Error : " + str(mean_absolute_error(predictions, test_y)))
my_model.fit封装了xgboost训练过程,可以通过设置XGBRegressor(silent=False)观察的训练过程输出
- 性能调优
my_model = XGBRegressor(n_estimators=1000)
my_model.fit(train_X, train_y, early_stopping_rounds=5,
eval_set=[(test_X, test_y)], verbose=False)
# make predictions
predictions = my_model.predict(test_X)
print("Mean Absolute Error : " + str(mean_absolute_error(predictions, test_y)))
my_model = XGBRegressor(n_estimators=1000, learning_rate=0.05)
my_model.fit(train_X, train_y, early_stopping_rounds=5,
eval_set=[(test_X, test_y)], verbose=False)
# make predictions
predictions = my_model.predict(test_X)
print("Mean Absolute Error : " + str(mean_absolute_error(predictions, test_y)))
完整代码:https://github.com/firdameng/kaggle_ml/blob/master/xgboost_demo.py
参考:
https://www.kaggle.com/dansbecker/xgboost
部分依赖图
部分依赖图显示每个变量或预测变量如何影响模型的预测.比如:
- 男女之间的工资差异有多少仅仅取决于性别,而不是教育背景或工作经历的差异?
- 控制房屋特征,经度和纬度对房价有何影响? 为了重申这一点,我们想要了解在不同区域如何定价同样大小的房屋,即使这些房屋的房屋大小不同。
- 由于饮食差异或其他因素,两组之间是否存在健康差异?
如果您熟悉线性或逻辑回归模型,则可以与这些模型中的系数类似地对部分依赖图进行解释。 但是,部分依赖图可以从数据中捕获更复杂的模式,并且可以与任何模型一起使用。
仅在模型拟合后才计算部分依赖图
my_model = GradientBoostingRegressor()
# fit the model as usual
my_model.fit(X, y)
# Here we make the plot
# artial dependence plots show how each variable or predictor affects the model's predictions
# If you are familiar with linear or logistic regression models, partial dependence plots can be interepreted similarly to the coefficients in those models.
# feature_names 都要给出来
my_plots = plot_partial_dependence(my_model,
features=[0,1, 2], # column numbers of plots we want to show
X=X, # raw predictors data.
feature_names=['Distance', 'Landsize', 'BuildingArea'], # labels on graphs
grid_resolution=10) # number of values to plot on x axis
可以看出,plot_partial_dependence函数需要传入fit后的模型,features=[0,1, 2]是我们想要观察的特征,grid_resolution可以选择确定水平轴上的哪些点。
完整示例代码:https://github.com/firdameng/kaggle_ml/blob/master/partial-dependence-plots.py
参考:https://www.kaggle.com/dansbecker/partial-dependence-plots