本文正在参与 人工智能创作者扶持方案 ”

1.机器学习算法(六)依据气候数据集的XGBoost分类猜测

本项目链接:www.heywhale.com/home/column…

1.1 XGBoost的介绍与运用

XGBoost是2016年由华盛顿大学陈天奇教师带领开发的一个可扩展机器学习体系。严格意义上讲XGBoost并不是一种模型,而是一个可供用户轻松处理分类、回归或排序问题的软件包。它内部完成了梯度提升树(GBDT)模型,并对模型中的算法进行了诸多优化,在获得高精度的一起又坚持了极快的速度,在一段时刻内成为了国内外数据发掘、机器学习范畴中的大规模杀伤性武器。

更重要的是,XGBoost在体系优化和机器学习原理方面都进行了深入的考虑。毫不夸大的讲,XGBoost供给的可扩展性,可移植性与准确性推动了机器学习计算约束的上限,该体系在单台机器上运转速度比当时流行处理方案快十倍以上,甚至在散布式体系中能够处理十亿级的数据。

XGBoost在机器学习与数据发掘范畴有着极为广泛的运用。据计算在2015年Kaggle平台上29个获奖方案中,17只队伍运用了XGBoost;在2015年KDD-Cup中,前十名的队伍均运用了XGBoost,且集成其他模型比不上调理XGBoost的参数所带来的提升。这些实实在在的例子都标明,XGBoost在各种问题上都能够获得非常好的作用。

一起,XGBoost还被成功运用在工业界与学术界的各种问题中。例如商店销售额猜测、高能物理事件分类、web文本分类;用户行为猜测、运动检测、广告点击率猜测、恶意软件分类、灾祸危险猜测、在线课程退学率猜测。虽然范畴相关的数据剖析和特性工程在这些处理方案中也发挥了重要作用,但学习者与实践者对XGBoost的一起挑选标明晰这一软件包的影响力与重要性。

1.2 原理介绍

XGBoost底层完成了GBDT算法,并对GBDT算法做了一系列优化:

  1. 对方针函数进行了泰勒展现的二阶打开,能够愈加高效拟合差错。
  2. 提出了一种估量割裂点的算法加快CART树的构建过程,一起能够处理稀少数据。
  3. 提出了一种树的并行策略加快迭代。
  4. 为模型的散布式算法进行了底层优化。

XGBoost是依据CART树的集成模型,它的思想是串联多个决议计划树模型一起进行决议计划。

那么如何串联呢?XGBoost选用迭代猜测差错的办法串联。举个浅显的例子,咱们现在需求猜测一辆车价值3000元。咱们构建决议计划树1练习后猜测为2600元,咱们发现有400元的差错,那么决议计划树2的练习方针为400元,但决议计划树2的猜测成果为350元,还存在50元的差错就交给第三棵树……以此类推,每一颗树用来估量之前一切树的差错,终究一切树猜测成果的求和便是终究猜测成果!

XGBoost的基模型是CART回归树,它有两个特点:(1)CART树,是一颗二叉树。(2)回归树,终究拟合成果是接连值。

XGBoost模型能够表明为以下方式,咱们约好ft(x)f_t(x)表明前tt颗树的和,ht(x)h_t(x)表明第tt颗决议计划树,模型界说如下:

ft(x)=∑t=1Tht(x)f_{t}(x)=\sum_{t=1}^{T} h_{t}(x)

由于模型递归生成,第tt步的模型由第t−1t-1步的模型形成,能够写成:

ft(x)=ft−1(x)+ht(x)f_{t}(x)=f_{t-1}(x)+h_{t}(x)

每次需求加上的树ht(x)h_t(x)是之前树求和的差错:

rt,i=yi−fm−1(xi)r_{t, i}=y_{i}-f_{m-1}\left(x_{i}\right)

咱们每一步只需拟合一颗输出为rt,ir_{t,i}的CART树加到ft−1(x)f_{t-1}(x)就能够了。

1.3 相关流程

  • 了解 XGBoost 的参数与相关常识
  • 把握 XGBoost 的Python调用并将其运用到气候数据集猜测

Part1 依据气候数据集的XGBoost分类实践

  • Step1: 库函数导入
  • Step2: 数据读取/载入
  • Step3: 数据信息简略检查
  • Step4: 可视化描绘
  • Step5: 对离散变量进行编码
  • Step6: 运用 XGBoost 进行练习与猜测
  • Step7: 运用 XGBoost 进行特征挑选
  • Step8: 经过调整参数获得更好的作用

3.依据气候数据集的XGBoost分类实战

3.1 EDA探索性剖析

在实践的最开端,咱们首先需求导入一些根底的函数库包含:numpy (Python进行科学计算的根底软件包),pandas(pandas是一种快速,强壮,灵敏且易于运用的开源数据剖析和处理东西),matplotlib和seaborn绘图。

#导入需求用到的数据集
!wget https://tianchi-media.oss-cn-beijing.aliyuncs.com/DSW/7XGBoost/train.csv
--2023-03-22 17:33:53--  https://tianchi-media.oss-cn-beijing.aliyuncs.com/DSW/7XGBoost/train.csv
正在解析主机 tianchi-media.oss-cn-beijing.aliyuncs.com (tianchi-media.oss-cn-beijing.aliyuncs.com)... 49.7.22.39
正在连接 tianchi-media.oss-cn-beijing.aliyuncs.com (tianchi-media.oss-cn-beijing.aliyuncs.com)|49.7.22.39|:443... 已连接。
已发出 HTTP 恳求,正在等待回应... 200 OK
长度: 11476379 (11M) [text/csv]
正在保存至: “train.csv.2”
train.csv.2         100%[===================>]  10.94M  8.82MB/s    in 1.2s    
2023-03-22 17:33:55 (8.82 MB/s) - 已保存 “train.csv.2” [11476379/11476379])

Step1:函数库导入

##  根底函数库
import numpy as np 
import pandas as pd
## 绘图函数库
import matplotlib.pyplot as plt
import seaborn as sns

本次咱们挑选气候数据集进行办法的测验练习,现在有一些由气象站供给的每日降雨数据,咱们需求依据历史降雨数据来猜测明日会下雨的概率。样例涉及到的测验集数据test.csv与train.csv的格局完全相同,但其RainTomorrow未给出,为猜测变量。

数据的各个特征描绘如下:

特征称号 意义 取值规模
Date 日期 字符
Location 气象站的地址 字符串
MinTemp 最低温度 实数
MaxTemp 最高温度 实数
Rainfall 降雨量 实数
Evaporation 蒸发量 实数
Sunshine 光照时刻 实数
WindGustDir 最强的风的方向 字符串
WindGustSpeed 最强的风的速度 实数
WindDir9am 早上9点的风向 字符串
WindDir3pm 下午3点的风向 字符串
WindSpeed9am 早上9点的风速 实数
WindSpeed3pm 下午3点的风速 实数
Humidity9am 早上9点的湿度 实数
Humidity3pm 下午3点的湿度 实数
Pressure9am 早上9点的大气压 实数
Pressure3pm 早上3点的大气压 实数
Cloud9am 早上9点的云指数 实数
Cloud3pm 早上3点的云指数 实数
Temp9am 早上9点的温度 实数
Temp3pm 早上3点的温度 实数
RainToday 今日是否下雨 No,Yes
RainTomorrow 明日是否下雨 No,Yes

Step2:数据读取/载入

## 咱们运用Pandas自带的read_csv函数读取并转化为DataFrame格局
data = pd.read_csv('train.csv')

Step3:数据信息简略检查

## 运用.info()检查数据的全体信息
data.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 106644 entries, 0 to 106643
Data columns (total 23 columns):
 #   Column         Non-Null Count   Dtype  
---  ------         --------------   -----  
 0   Date           106644 non-null  object 
 1   Location       106644 non-null  object 
 2   MinTemp        106183 non-null  float64
 3   MaxTemp        106413 non-null  float64
 4   Rainfall       105610 non-null  float64
 5   Evaporation    60974 non-null   float64
 6   Sunshine       55718 non-null   float64
 7   WindGustDir    99660 non-null   object 
 8   WindGustSpeed  99702 non-null   float64
 9   WindDir9am     99166 non-null   object 
 10  WindDir3pm     103788 non-null  object 
 11  WindSpeed9am   105643 non-null  float64
 12  WindSpeed3pm   104653 non-null  float64
 13  Humidity9am    105327 non-null  float64
 14  Humidity3pm    103932 non-null  float64
 15  Pressure9am    96107 non-null   float64
 16  Pressure3pm    96123 non-null   float64
 17  Cloud9am       66303 non-null   float64
 18  Cloud3pm       63691 non-null   float64
 19  Temp9am        105983 non-null  float64
 20  Temp3pm        104599 non-null  float64
 21  RainToday      105610 non-null  object 
 22  RainTomorrow   106644 non-null  object 
dtypes: float64(16), object(7)
memory usage: 18.7+ MB
## 进行简略的数据检查,咱们能够运用 .head() 头部.tail()尾部
data.head()
.dataframe tbody tr th:only-of-type { vertical-align: middle; } .dataframe tbody tr th { vertical-align: top; } .dataframe thead th { text-align: right; }
Date Location MinTemp MaxTemp Rainfall Evaporation Sunshine WindGustDir WindGustSpeed WindDir9am Humidity9am Humidity3pm Pressure9am Pressure3pm Cloud9am Cloud3pm Temp9am Temp3pm RainToday RainTomorrow
0 2012/1/19 MountGinini 12.1 23.1 0.0 NaN NaN W 30.0 N 60.0 54.0 NaN NaN NaN NaN 17.0 22.0 No No
1 2015/4/13 Nhil 10.2 24.7 0.0 NaN NaN E 39.0 E 63.0 33.0 1021.9 1017.9 NaN NaN 12.5 23.7 No Yes
2 2010/8/5 Nuriootpa -0.4 11.0 3.6 0.4 1.6 W 28.0 N 97.0 78.0 1025.9 1025.3 7.0 8.0 3.9 9.0 Yes No
3 2013/3/18 Adelaide 13.2 22.6 0.0 15.4 11.0 SE 44.0 E 47.0 34.0 1025.0 1022.2 NaN NaN 15.2 21.7 No No
4 2011/2/16 Sale 14.1 28.6 0.0 6.6 6.7 E 28.0 NE 92.0 42.0 1018.0 1014.1 4.0 7.0 19.1 28.2 No No

5 rows 23 columns

这里咱们发现数据会集存在NaN,一般的咱们认为NaN在数据会集代表了缺失值,可能是数据收集或处理时产生的一种过错。这里咱们选用-1将缺失值进行添补,还有其他例如“中位数添补、平均数添补”的缺失值处理办法有兴趣的同学也能够测验。

data = data.fillna(-1)
data.tail()
.dataframe tbody tr th:only-of-type { vertical-align: middle; } .dataframe tbody tr th { vertical-align: top; } .dataframe thead th { text-align: right; }
Date Location MinTemp MaxTemp Rainfall Evaporation Sunshine WindGustDir WindGustSpeed WindDir9am Humidity9am Humidity3pm Pressure9am Pressure3pm Cloud9am Cloud3pm Temp9am Temp3pm RainToday RainTomorrow
106639 2011/5/23 Launceston 10.1 16.1 15.8 -1.0 -1.0 SE 31.0 NNW 99.0 86.0 999.2 995.2 -1.0 -1.0 13.0 15.6 Yes Yes
106640 2014/12/9 GoldCoast 19.3 31.7 36.0 -1.0 -1.0 SE 80.0 NNW 75.0 76.0 1013.8 1010.0 -1.0 -1.0 26.0 25.8 Yes Yes
106641 2014/10/7 Wollongong 17.5 22.2 1.2 -1.0 -1.0 WNW 65.0 WNW 61.0 56.0 1008.2 1008.2 -1.0 -1.0 17.8 21.4 Yes No
106642 2012/1/16 Newcastle 17.6 27.0 3.0 -1.0 -1.0 -1 -1.0 NE 68.0 88.0 -1.0 -1.0 6.0 5.0 22.6 26.4 Yes No
106643 2014/10/21 AliceSprings 16.3 37.9 0.0 14.2 12.2 ESE 41.0 NNE 8.0 6.0 1017.9 1014.0 0.0 1.0 32.2 35.7 No No

5 rows 23 columns

## 运用value_counts函数检查练习集标签的数量
pd.Series(data['RainTomorrow']).value_counts()
No     82786
Yes    23858
Name: RainTomorrow, dtype: int64

咱们发现数据会集的负样本数量远大于正样本数量,这种常见的问题叫做“数据不平衡”问题,在某些状况下需求进行一些特别处理。

## 关于特征进行一些计算描绘
data.describe()
.dataframe tbody tr th:only-of-type { vertical-align: middle; } .dataframe tbody tr th { vertical-align: top; } .dataframe thead th { text-align: right; }
MinTemp MaxTemp Rainfall Evaporation Sunshine WindGustSpeed WindSpeed9am WindSpeed3pm Humidity9am Humidity3pm Pressure9am Pressure3pm Cloud9am Cloud3pm Temp9am Temp3pm
count 106644.000000 106644.000000 106644.000000 106644.000000 106644.000000 106644.000000 106644.000000 106644.000000 106644.000000 106644.000000 106644.000000 106644.000000 106644.000000 106644.000000 106644.000000 106644.000000
mean 12.129147 23.183398 2.313912 2.704798 3.509008 37.305137 13.852200 18.265378 67.940353 50.104657 917.003689 914.995385 2.381231 2.285670 16.877842 21.257600
std 6.444358 7.208596 8.379145 4.519172 5.105696 16.585310 8.949659 9.118835 20.481579 22.136917 304.042528 303.120731 3.483751 3.419658 6.629811 7.549532
min -8.500000 -4.800000 -1.000000 -1.000000 -1.000000 -1.000000 -1.000000 -1.000000 -1.000000 -1.000000 -1.000000 -1.000000 -1.000000 -1.000000 -7.200000 -5.400000
25% 7.500000 17.900000 0.000000 -1.000000 -1.000000 30.000000 7.000000 11.000000 56.000000 35.000000 1011.000000 1008.500000 -1.000000 -1.000000 12.200000 16.300000
50% 12.000000 22.600000 0.000000 1.600000 0.200000 37.000000 13.000000 17.000000 70.000000 51.000000 1016.700000 1014.200000 1.000000 1.000000 16.700000 20.900000
75% 16.800000 28.300000 0.600000 5.400000 8.700000 46.000000 19.000000 24.000000 83.000000 65.000000 1021.800000 1019.400000 6.000000 6.000000 21.500000 26.300000
max 31.900000 48.100000 268.600000 145.000000 14.500000 135.000000 130.000000 87.000000 100.000000 100.000000 1041.000000 1039.600000 9.000000 9.000000 39.400000 46.200000

Step4:可视化描绘

为了方便,咱们先纪录数字特征与非数字特征:

numerical_features = [x for x in data.columns if data[x].dtype == np.float]
category_features = [x for x in data.columns if data[x].dtype != np.float and x != 'RainTomorrow']
## 选取三个特征与标签组合的散点可视化
sns.pairplot(data=data[['Rainfall',
'Evaporation',
'Sunshine'] + ['RainTomorrow']], diag_kind='hist', hue= 'RainTomorrow')
plt.show()

机器学习算法(六)基于天气数据集的XGBoost分类预测

从上图能够发现,在2D状况下不同的特征组合关于第二天下雨与不下雨的散点散布,以及大约的区别才能。相对的Sunshine与其他特征的组合更具有区别才能

for col in data[numerical_features].columns:
    if col != 'RainTomorrow':
        sns.boxplot(x='RainTomorrow', y=col, saturation=0.5, palette='pastel', data=data)
        plt.title(col)
        plt.show()

机器学习算法(六)基于天气数据集的XGBoost分类预测
机器学习算法(六)基于天气数据集的XGBoost分类预测
机器学习算法(六)基于天气数据集的XGBoost分类预测
机器学习算法(六)基于天气数据集的XGBoost分类预测

运用箱型图咱们也能够得到不同类别在不同特征上的散布差异状况。咱们能够发现Sunshine,Humidity3pm,Cloud9am,Cloud3pm的区别才能较强

tlog = {}
for i in category_features:
    tlog[i] = data[data['RainTomorrow'] == 'Yes'][i].value_counts()
flog = {}
for i in category_features:
    flog[i] = data[data['RainTomorrow'] == 'No'][i].value_counts()
plt.figure(figsize=(10,10))
plt.subplot(1,2,1)
plt.title('RainTomorrow')
sns.barplot(x = pd.DataFrame(tlog['Location']).sort_index()['Location'], y = pd.DataFrame(tlog['Location']).sort_index().index, color = "red")
plt.subplot(1,2,2)
plt.title('Not RainTomorrow')
sns.barplot(x = pd.DataFrame(flog['Location']).sort_index()['Location'], y = pd.DataFrame(flog['Location']).sort_index().index, color = "blue")
plt.show()

机器学习算法(六)基于天气数据集的XGBoost分类预测

从上图能够发现不同区域降雨状况差别很大,有些当地明显更容易降雨

plt.figure(figsize=(10,2))
plt.subplot(1,2,1)
plt.title('RainTomorrow')
sns.barplot(x = pd.DataFrame(tlog['RainToday'][:2]).sort_index()['RainToday'], y = pd.DataFrame(tlog['RainToday'][:2]).sort_index().index, color = "red")
plt.subplot(1,2,2)
plt.title('Not RainTomorrow')
sns.barplot(x = pd.DataFrame(flog['RainToday'][:2]).sort_index()['RainToday'], y = pd.DataFrame(flog['RainToday'][:2]).sort_index().index, color = "blue")
plt.show()

机器学习算法(六)基于天气数据集的XGBoost分类预测

上图咱们能够发现,今日下雨明日不一定下雨,但今日不下雨,第二天大约率也不下雨。

3.2 特征向量编码

Step5:对离散变量进行编码

由于XGBoost无法处理字符串类型的数据,咱们需求一些办法讲字符串数据转化为数据。一种最简略的办法是把一切的相同类其他特征编码成同一个值,例如女=0,男=1,狗狗=2,所以终究编码的特征值是在[0,特征数量−1][0, 特征数量-1]之间的整数。除此之外,还有独热编码、求和编码、留一法编码等等办法能够获得更好的作用。

## 把一切的相同类其他特征编码为同一个值
def get_mapfunction(x):
    mapp = dict(zip(x.unique().tolist(),
         range(len(x.unique().tolist()))))
    def mapfunction(y):
        if y in mapp:
            return mapp[y]
        else:
            return -1
    return mapfunction
for i in category_features:
    data[i] = data[i].apply(get_mapfunction(data[i]))
## 编码后的字符串特征变成了数字
data['Location'].unique()
array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16,
       17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33,
       34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48])

3.3 模型练习猜测

Step6:运用 XGBoost 进行练习与猜测

## 为了正确评价模型功能,将数据区分为练习集和测验集,并在练习集上练习模型,在测验集上验证模型功能。
from sklearn.model_selection import train_test_split
## 挑选其类别为0和1的样本 (不包含类别为2的样本)
data_target_part = data['RainTomorrow']
data_features_part = data[[x for x in data.columns if x != 'RainTomorrow']]
## 测验集巨细为20%, 80%/20%分
x_train, x_test, y_train, y_test = train_test_split(data_features_part, data_target_part, test_size = 0.2, random_state = 2020)
#检查标签数据
print(y_train[0:2],y_test[0:2])
# 替换Yes为1,No为0
y_train = y_train.replace({'Yes': 1, 'No': 0})
y_test  = y_test.replace({'Yes': 1, 'No': 0})
# 打印修改后的成果
print(y_train[0:2],y_test[0:2])
98173    No
33154    No
Name: RainTomorrow, dtype: object 10273    Yes
90769     No
Name: RainTomorrow, dtype: object
98173    0
33154    0
Name: RainTomorrow, dtype: int64 10273    1
90769    0
Name: RainTomorrow, dtype: int64
The label for xgboost must consist of integer labels of the form 0, 1, 2, ..., [num_class - 1]. This means that the labels must be sequential integers starting from 0 up to the total number of classes minus 1. For example, if there are 3 classes, the labels should be 0, 1, and 2. If the labels are not in this format, xgboost may not be able to train the model properly.
## 导入XGBoost模型
from xgboost.sklearn import XGBClassifier
## 界说 XGBoost模型 
clf = XGBClassifier(use_label_encoder=False)
# 在练习集上练习XGBoost模型
clf.fit(x_train, y_train)
#https://cloud.tencent.com/developer/ask/sof/913362/answer/1303557
[17:34:10] WARNING: ../src/learner.cc:1061: Starting in XGBoost 1.3.0, the default evaluation metric used with the objective 'binary:logistic' was changed from 'error' to 'logloss'. Explicitly set eval_metric if you'd like to restore the old behavior.
XGBClassifier(base_score=0.5, booster='gbtree', colsample_bylevel=1,
              colsample_bynode=1, colsample_bytree=1, gamma=0, gpu_id=-1,
              importance_type='gain', interaction_constraints='',
              learning_rate=0.300000012, max_delta_step=0, max_depth=6,
              min_child_weight=1, missing=nan, monotone_constraints='()',
              n_estimators=100, n_jobs=24, num_parallel_tree=1, random_state=0,
              reg_alpha=0, reg_lambda=1, scale_pos_weight=1, subsample=1,
              tree_method='exact', use_label_encoder=False,
              validate_parameters=1, verbosity=None)
## 在练习集和测验集上散布运用练习好的模型进行猜测
train_predict = clf.predict(x_train)
test_predict = clf.predict(x_test)
from sklearn import metrics
## 运用accuracy(准确度)【猜测正确的样本数目占总猜测样本数目的份额】评价模型作用
print('The accuracy of the Logistic Regression is:',metrics.accuracy_score(y_train,train_predict))
print('The accuracy of the Logistic Regression is:',metrics.accuracy_score(y_test,test_predict))
## 检查混淆矩阵 (猜测值和实在值的各类状况计算矩阵)
confusion_matrix_result = metrics.confusion_matrix(test_predict,y_test)
print('The confusion matrix result:\n',confusion_matrix_result)
# 运用热力求关于成果进行可视化
plt.figure(figsize=(8, 6))
sns.heatmap(confusion_matrix_result, annot=True, cmap='Blues')
plt.xlabel('Predicted labels')
plt.ylabel('True labels')
plt.show()
The accuracy of the Logistic Regression is: 0.8982476703979371
The accuracy of the Logistic Regression is: 0.8575179333302076
The confusion matrix result:
 [[15656  2142]
 [  897  2634]]

机器学习算法(六)基于天气数据集的XGBoost分类预测

咱们能够发现共有15759 + 2306个样本猜测正确,2470 + 794个样本猜测过错。

3.3.1 特征挑选

Step7: 运用 XGBoost 进行特征挑选

XGBoost的特征挑选属于特征挑选中的嵌入式办法,在XGboost中能够用特点feature_importances_去检查特征的重要度。

? sns.barplot
sns.barplot(y=data_features_part.columns, x=clf.feature_importances_)

机器学习算法(六)基于天气数据集的XGBoost分类预测

从图中咱们能够发现下午3点的湿度与今日是否下雨是决议第二天是否下雨最重要的要素

初次之外,咱们还能够运用XGBoost中的下列重要特点来评价特征的重要性。

  • weight:是以特征用到的次数来评价
  • gain:当运用特征做区分的时候的评价基尼指数
  • cover:运用一个掩盖样本的指标二阶导数(具体原理不清楚有待探究)平均值来区分。
  • total_gain:总基尼指数
  • total_cover:总掩盖
from sklearn.metrics import accuracy_score
from xgboost import plot_importance
def estimate(model,data):
    #sns.barplot(data.columns,model.feature_importances_)
    ax1=plot_importance(model,importance_type="gain")
    ax1.set_title('gain')
    ax2=plot_importance(model, importance_type="weight")
    ax2.set_title('weight')
    ax3 = plot_importance(model, importance_type="cover")
    ax3.set_title('cover')
    plt.show()
def classes(data,label,test):
    model=XGBClassifier()
    model.fit(data,label)
    ans=model.predict(test)
    estimate(model, data)
    return ans
ans=classes(x_train,y_train,x_test)
pre=accuracy_score(y_test, ans)
print('acc=',accuracy_score(y_test,ans))
/opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages/xgboost/sklearn.py:888: UserWarning: The use of label encoder in XGBClassifier is deprecated and will be removed in a future release. To remove this warning, do the following: 1) Pass option use_label_encoder=False when constructing XGBClassifier object; and 2) Encode your labels (y) as integers starting with 0, i.e. 0, 1, 2, ..., [num_class - 1].
  warnings.warn(label_encoder_deprecation_msg, UserWarning)
[17:34:28] WARNING: ../src/learner.cc:1061: Starting in XGBoost 1.3.0, the default evaluation metric used with the objective 'binary:logistic' was changed from 'error' to 'logloss'. Explicitly set eval_metric if you'd like to restore the old behavior.

机器学习算法(六)基于天气数据集的XGBoost分类预测
机器学习算法(六)基于天气数据集的XGBoost分类预测
机器学习算法(六)基于天气数据集的XGBoost分类预测

acc= 0.8575179333302076

这些图相同能够帮助咱们更好的了解其他重要特征。

Step8: 经过调整参数获得更好的作用

XGBoost中包含但不限于下列对模型影响较大的参数:

1. learning_rate: 有时也叫作eta,体系默许值为0.3。每一步迭代的步长,很重要。太大了运转准确率不高,太小了运转速度慢。
2. subsample:体系默许为1。这个参数操控关于每棵树,随机采样的份额。减小这个参数的值,算法会愈加保存,防止过拟合, 取值规模零到一。
3. colsample_bytree:体系默许值为1。咱们一般设置成0.8左右。用来操控每棵随机采样的列数的占比(每一列是一个特征)。
4. max_depth: 体系默许值为6,咱们常用3-10之间的数字。这个值为树的最大深度。这个值是用来操控过拟合的。max_depth越大,模型学习的愈加具体。

3.3.2 中心参数调优

1.eta[默许0.3]
经过为每一颗树增加权重,提高模型的鲁棒性。
典型值为0.01-0.2。

2.min_child_weight[默许1]
决议最小叶子节点样本权重和。
这个参数能够防止过拟合。当它的值较大时,能够防止模型学习到部分的特别样本。
可是假如这个值过高,则会导致模型拟合不充分。

3.max_depth[默许6]
这个值也是用来防止过拟合的。max_depth越大,模型会学到更具体更部分的样本。
典型值:3-10

4.max_leaf_nodes
树上最大的节点或叶子的数量。
能够替代max_depth的作用。
这个参数的界说会导致忽略max_depth参数。

5.gamma[默许0]
在节点割裂时,只有割裂后丢失函数的值下降了,才会割裂这个节点。Gamma指定了节点割裂所需的最小丢失函数下降值。 这个参数的值越大,算法越保存。这个参数的值和丢失函数息息相关。

6.max_delta_step[默许0]
这参数约束每棵树权重改动的最大步长。假如这个参数的值为0,那就意味着没有约束。假如它被赋予了某个正值,那么它会让这个算法愈加保存。
可是当各类其他样本非常不平衡时,它对分类问题是很有帮助的。

7.subsample[默许1]
这个参数操控关于每棵树,随机采样的份额。
减小这个参数的值,算法会愈加保存,防止过拟合。可是,假如这个值设置得过小,它可能会导致欠拟合。
典型值:0.5-1

8.colsample_bytree[默许1]
用来操控每棵随机采样的列数的占比(每一列是一个特征)。
典型值:0.5-1

9.colsample_bylevel[默许1]
用来操控树的每一级的每一次割裂,对列数的采样的占比。
subsample参数和colsample_bytree参数能够起到相同的作用,一般用不到。

10.lambda[默许1]
权重的L2正则化项。(和Ridge regression相似)。
这个参数是用来操控XGBoost的正则化部分的。虽然大部分数据科学家很少用到这个参数,可是这个参数在削减过拟合上仍是能够发掘出更多用处的。

11.alpha[默许1]
权重的L1正则化项。(和Lasso regression相似)。
能够运用在很高维度的状况下,使得算法的速度更快。

12.scale_pos_weight[默许1]
在各类别样本非常不平衡时,把这个参数设定为一个正值,能够使算法更快收敛。

3.3.3 网格调参法

调理模型参数的办法有贪心算法、网格调参、贝叶斯调参等。这里咱们选用网格调参,它的基本思想是穷举查找:在一切候选的参数挑选中,经过循环遍历,测验每一种可能性,体现最好的参数便是终究的成果

## 从sklearn库中导入网格调参函数
from sklearn.model_selection import GridSearchCV
## 界说参数取值规模
learning_rate = [0.1, 0.3,]
subsample = [0.8]
colsample_bytree = [0.6, 0.8]
max_depth = [3,5]
parameters = { 'learning_rate': learning_rate,
              'subsample': subsample,
              'colsample_bytree':colsample_bytree,
              'max_depth': max_depth}
model = XGBClassifier(n_estimators = 20)
## 进行网格查找
clf = GridSearchCV(model, parameters, cv=3, scoring='accuracy',verbose=1,n_jobs=-1)
clf = clf.fit(x_train, y_train)
## 网格查找后的最好参数为
clf.best_params_
## 在练习集和测验集上散布运用最好的模型参数进行猜测
## 界说带参数的 XGBoost模型 
clf = XGBClassifier(colsample_bytree = 0.6, learning_rate = 0.3, max_depth= 8, subsample = 0.9)
# 在练习集上练习XGBoost模型
clf.fit(x_train, y_train)
train_predict = clf.predict(x_train)
test_predict = clf.predict(x_test)
## 运用accuracy(准确度)【猜测正确的样本数目占总猜测样本数目的份额】评价模型作用
print('The accuracy of the Logistic Regression is:',metrics.accuracy_score(y_train,train_predict))
print('The accuracy of the Logistic Regression is:',metrics.accuracy_score(y_test,test_predict))
## 检查混淆矩阵 (猜测值和实在值的各类状况计算矩阵)
confusion_matrix_result = metrics.confusion_matrix(test_predict,y_test)
print('The confusion matrix result:\n',confusion_matrix_result)
# 运用热力求关于成果进行可视化
plt.figure(figsize=(8, 6))
sns.heatmap(confusion_matrix_result, annot=True, cmap='Blues')
plt.xlabel('Predicted labels')
plt.ylabel('True labels')
plt.show()
/opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages/xgboost/sklearn.py:888: UserWarning: The use of label encoder in XGBClassifier is deprecated and will be removed in a future release. To remove this warning, do the following: 1) Pass option use_label_encoder=False when constructing XGBClassifier object; and 2) Encode your labels (y) as integers starting with 0, i.e. 0, 1, 2, ..., [num_class - 1].
  warnings.warn(label_encoder_deprecation_msg, UserWarning)
[17:55:25] WARNING: ../src/learner.cc:1061: Starting in XGBoost 1.3.0, the default evaluation metric used with the objective 'binary:logistic' was changed from 'error' to 'logloss'. Explicitly set eval_metric if you'd like to restore the old behavior.
The accuracy of the Logistic Regression is: 0.9382992439781984
The accuracy of the Logistic Regression is: 0.856674011908669
The confusion matrix result:
 [[15611  2115]
 [  942  2661]]

机器学习算法(六)基于天气数据集的XGBoost分类预测

本来有2470 + 790个过错,现在有 2112 + 939个过错,带来了明显的正确率提升。

更多调参技巧请参阅:blog.csdn.net/weixin_6268…

4. 总结

XGBoost的首要长处:

  1. 简略易用。相对其他机器学习库,用户能够轻松运用XGBoost并获得相当不错的作用。
  2. 高效可扩展。在处理大规模数据集时速度快作用好,对内存等硬件资源要求不高。
  3. 鲁棒性强。相关于深度学习模型不需求精密调参便能获得挨近的作用。
  4. XGBoost内部完成提升树模型,能够主动处理缺失值。

XGBoost的首要缺陷:

  1. 相关于深度学习模型无法对时空方位建模,不能很好地捕获图画、语音、文本等高维数据。
  2. 在拥有海量练习数据,并能找到适宜的深度学习模型时,深度学习的精度能够遥遥领先XGBoost。

本项目链接:www.heywhale.com/home/column…

参阅链接:tianchi.aliyun.com/course/278/…


本人最近计划整合ML、DRL、NLP等相关范畴的体系化项目课程,方便入门同学快速把握相关常识。声明:部分项目为网络经典项目方便大家快速学习,后续会不断增加实战环节(竞赛、论文、实践运用等)。

  • 关于机器学习这块规划为:根底入门机器学习算法—>简略项目实战—>数据建模竞赛—–>相关实践中运用场景问题处理。一条道路帮助大家学习,快速实战。
  • 关于深度强化学习这块规划为:根底单智能算法教学(gym环境为主)—->主流多智能算法教学(gym环境为主)—->单智能多智能题实战(论文复现偏事务如:无人机优化调度、电力资源调度等项目运用)
  • 自然语言处理相关规划:除了单点算法技能外,首要环绕常识图谱构建进行:信息抽取相关技能(含智能标示)—>常识交融—->常识推理—->图谱运用

上述关于你把握后的期许:

  1. 关于ML,希望你后续能够乱杀数学建模相关竞赛(参与就获奖保底,top仍是难的需求研究)
  2. 能够实践处理实践中一些优化调度问题,而非停留在gym环境下的一些游戏demo玩玩。(更深层次可能需求自己研究了,难度仍是很大的)
  3. 把握可常识图谱全流程构建其间各个重要环节算法,包含图数据库相关常识。

这三块范畴耦合状况比较大,后续会经过比方:查找引荐体系整个项目进行耦合,各项算法都会耦合在其间。举例:常识图谱就会用到(图算法、NLP、ML相关算法),查找引荐体系(除了该范畴召回粗排精排重排混排等算法外,还有强化学习、常识图谱等耦合在其间)。饼画的有点大,后边渐渐完成。

本文正在参与 人工智能创作者扶持方案 ”