第二部分:实战
xgboost既可以通过自己本身的接口进行训练,也可以借助sklearn的接口训练,下面一一进行介绍。
2.1 原生接口的分类实战
代码如下所示
# _*_ coding: UTF-8 _*_
from sklearn.datasets import load_iris
import xgboost as xgb
from xgboost import plot_importance
from matplotlib import pyplot as plt
from sklearn.model_selection import train_test_split
# 加载数据
# data = np.random.rand(5,10)
# label = np.random.randint(2, size=5)
# dtrain = xgb.DMatrix(data, label=label)
iris = load_iris()
X = iris.data
y = iris.target
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.5, random_state=1234565)
# 参数设置
params = {
'booster': 'gbtree',
'objective': 'multi:softmax', # 多分类的问题
'num_class': 3, # 类别数,与 multisoftmax 并用
'gamma': 0.1, # 用于控制是否后剪枝的参数,越大越保守,一般0.1、0.2这样子。
'max_depth': 6, # 构建树的深度,越大越容易过拟合
'lambda': 2, # 控制模型复杂度的权重值的L2正则化项参数,参数越大,模型越不容易过拟合。
'subsample': 0.7, # 随机采样训练样本
'colsample_bytree': 0.7, # 生成树时进行的列采样
'min_child_weight': 3,
'silent': 1, # 设置成1则没有运行信息输出,最好是设置为0.
'eta': 0.1, # 如同学习率
'seed': 1000,
'nthread': 4, # cpu 线程数
}
# xgb矩阵赋值
xgb_train = xgb.DMatrix(X_train, label=y_train)
xgb_test = xgb.DMatrix(X_test, label=y_test)
# 训练模型
plst = list(params.items())
watchlist = [(xgb_train, 'train'), (xgb_test, 'val')]
num_round = 500
model = xgb.train(plst, xgb_train, num_round, watchlist)
# 评价训练模型
y_pred = model.predict(xgb_test, ntree_limit=model.best_ntree_limit)
# 计算准确率
cnt1 = 0
cnt2 = 0
for i in range(len(y_test)):
if y_pred[i] == y_test[i]:
cnt1 += 1
else:
cnt2 += 1
print("Accuracy: %.2f %% " % (100 * cnt1 / (cnt1 + cnt2)))
# 显示重要特征
plot_importance(model)
plt.show()
得到的结果如下:
从上图中可以看到特征的重要性,其中f2特征被分裂了139次。
上图得到了所训练的分类器的精确度。
通过控制台看变量,可以看到训练得到的model的最佳迭代次数是499以及其他信息。
之前由于无法导入graphviz模块,因此只绘制了重要性,而没有绘制树,这里我找到了解决办法,见博文
解决Aanaconda3 安装 graphviz但是在pycharm里面无法调用的问题
在上面的代码后加上两行画决策树的代码,可以得到下面的图。
xgb.plot_tree(model, num_trees=10) # 因为缺少pygraphviz-1.3.1-cp36-none-win32的模块 所以并不能画图,后来解决了
plt.show()
2.2 sklearn接口的分类实战
代码如下所示
# _*_ coding: UTF-8 _*_
from sklearn.datasets import load_iris
import xgboost as xgb
from xgboost.sklearn import XGBClassifier # sklearn接口
from xgboost import plot_importance
from matplotlib import pyplot as plt
import graphviz
from sklearn.model_selection import train_test_split
# 加载数据
iris = load_iris()
X = iris.data
y = iris.target
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)
# 训练模型
model = XGBClassifier(max_depth=5, learning_rate=0.1, n_estimators=160, silent=True, objective='multi:softmax')
model.fit(X_train, y_train)
# 评价训练模型
y_pred = model.predict(X_test)
# 计算准确率
cnt1 = 0
cnt2 = 0
for i in range(len(y_test)):
if y_pred[i] == y_test[i]:
cnt1 += 1
else:
cnt2 += 1
print("Accuracy: %.2f %% " % (100 * cnt1 / (cnt1 + cnt2)))
# 显示重要特征
plot_importance(model)
plt.show()
xgb.plot_tree(model, num_trees=10)
plt.show()
得到的结果如下图所示:
其中精确度达到了。