语法:
class xgboost.XGBClassifier(max_depth=3, learning_rate=0.1, n_estimators=100, silent=True, objective='binary:logistic', booster='gbtree', n_jobs=1, nthread=None, gamma=0, min_child_weight=1, max_delta_step=0, subsample=1, colsample_bytree=1, colsample_bylevel=1, reg_alpha=0, reg_lambda=1, scale_pos_weight=1, base_score=0.5, random_state=0, seed=None, missing=None, **kwargs)
booster
n_jobs
并行线程数scale_pos_weight
正样本的权重,在二分类任务中,当正负样本比例失衡时,设置正样本的权重,模型效果更好。例如,当正负样本比例为1:10时,scale_pos_weight=10。
n_estimatores
含义:总共迭代的次数,即决策树的个数
调参:
max_depth
含义:树的深度,默认值为6,典型值3-10。
调参:值越大,越容易过拟合;值越小,越容易欠拟合。
min_child_weight
含义:默认值为1,。
调参:值越大,越容易欠拟合;值越小,越容易过拟合(值较大时,避免模型学习到局部的特殊样本)。
subsample
含义:训练每棵树时,使用的数据占全部训练集的比例。默认值为1,典型值为0.5-1。
调参:防止overfitting。
colsample_bytree
含义:训练每棵树时,使用的特征占全部特征的比例。默认值为1,典型值为0.5-1。
调参:防止overfitting。
learning_rate
含义:学习率,控制每次迭代更新权重时的步长,默认0.3。
调参:值越小,训练越慢。
典型值为0.01-0.2。
gamma
惩罚项系数,指定节点分裂所需的最小损失函数下降值。
调参:
alpha
L1正则化系数,默认为1
lambda
L2正则化系数,默认为1
pima-indians-diabetes.csv
印度的一个数据集,前面是各个类别的值,最后一列是标签值,1代表糖尿病,0代表正常。
代码:
from numpy import loadtxt
from xgboost import XGBClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
# 加载数据集
dataset = loadtxt('E:/file/pima-indians-diabetes.csv', delimiter=",")
# 将数据分为 数据和标签
X = dataset[:,0:8]
Y = dataset[:,8]
# 划分测试集和训练集
seed = 7 # 随机因子,能保证多次的随机数据一致
test_size = 0.33
X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=test_size, random_state=seed)
# 训练模型
model = XGBClassifier()
model.fit(X_train, y_train)
# 对模型做预测
y_pred = model.predict(X_test)
predictions = [round(value) for value in y_pred]
# 评估预测
accuracy = accuracy_score(y_test, predictions)
print("Accuracy: %.2f%%" % (accuracy * 100.0))
测试记录:
Accuracy: 74.02%
代码:
from numpy import loadtxt
from xgboost import XGBClassifier
from xgboost import plot_importance
from matplotlib import pyplot as plt
# 加载数据集
dataset = loadtxt('E:/file/pima-indians-diabetes.csv', delimiter=",")
# 将数据分为 数据和标签
X = dataset[:,0:8]
Y = dataset[:,8]
# 训练模型
model = XGBClassifier()
model.fit(X, Y)
# 画图,画出特征的重要性
plot_importance(model)
plt.show()
代码:
from numpy import loadtxt
from xgboost import XGBClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
# 加载数据集
dataset = loadtxt('E:/file/pima-indians-diabetes.csv', delimiter=",")
# 将数据分为 数据和标签
X = dataset[:,0:8]
Y = dataset[:,8]
# 划分测试集和训练集
seed = 7 # 随机因子,能保证多次的随机数据一致
test_size = 0.33
X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=test_size, random_state=seed)
# 训练模型
model = XGBClassifier()
eval_set = [(X_test, y_test)]
model.fit(X_train, y_train, early_stopping_rounds=10, eval_metric="logloss", eval_set=eval_set, verbose=True)
# 对模型做预测
y_pred = model.predict(X_test)
predictions = [round(value) for value in y_pred]
# 评估预测
accuracy = accuracy_score(y_test, predictions)
print("Accuracy: %.2f%%" % (accuracy * 100.0))
测试记录:
[0] validation_0-logloss:0.60491
[1] validation_0-logloss:0.55934
[2] validation_0-logloss:0.53068
[3] validation_0-logloss:0.51795
[4] validation_0-logloss:0.51153
[5] validation_0-logloss:0.50934
[6] validation_0-logloss:0.50818
[7] validation_0-logloss:0.51097
[8] validation_0-logloss:0.51760
[9] validation_0-logloss:0.51912
[10] validation_0-logloss:0.52503
[11] validation_0-logloss:0.52697
[12] validation_0-logloss:0.53335
[13] validation_0-logloss:0.53905
[14] validation_0-logloss:0.54545
[15] validation_0-logloss:0.54613
Accuracy: 74.41%
代码:
from numpy import loadtxt
from xgboost import XGBClassifier
from sklearn.model_selection import GridSearchCV
from sklearn.model_selection import StratifiedKFold
# 加载数据集
dataset = loadtxt('E:/file/pima-indians-diabetes.csv', delimiter=",")
# 将数据分为 数据和标签
X = dataset[:,0:8]
Y = dataset[:,8]
# grid search 做交叉验证
model = XGBClassifier()
learning_rate = [0.0001, 0.001, 0.01, 0.1, 0.2, 0.3]
param_grid = dict(learning_rate=learning_rate)
kfold = StratifiedKFold(n_splits=10, shuffle=True, random_state=7)
grid_search = GridSearchCV(model, param_grid, scoring="neg_log_loss", n_jobs=-1, cv=kfold)
grid_result = grid_search.fit(X, Y)
# 汇总结果
print("Best: %f using %s" % (grid_result.best_score_, grid_result.best_params_))
means = grid_result.cv_results_['mean_test_score']
params = grid_result.cv_results_['params']
for mean, param in zip(means, params):
print("%f with: %r" % (mean, param))
测试记录:
Best: -0.530152 using {'learning_rate': 0.01}
-0.689563 with: {'learning_rate': 0.0001}
-0.660868 with: {'learning_rate': 0.001}
-0.530152 with: {'learning_rate': 0.01}
-0.552723 with: {'learning_rate': 0.1}
-0.653341 with: {'learning_rate': 0.2}
-0.718789 with: {'learning_rate': 0.3}