机器学习算法(二): 基于XGBoost的分类预测

阿里云机器学习案例(二)

1.实验室介绍

1.1 XGBoost介绍

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

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

XGBoost的主要优点:

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

XGBoost的主要缺点:

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

1.2 XGBoost的应用

XGBoost在机器学习与数据挖掘领域有着极为广泛的应用。据统计在2015年Kaggle平台上29个获奖方案中,17只队伍使用了XGBoost;在2015年KDD-Cup中,前十名的队伍均使用了XGBoost,且集成其他模型比不上调节XGBoost的参数所带来的提升。这些实实在在的例子都表明,XGBoost在各种问题上都可以取得非常好的效果。

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

2.实验室手册

2.1 学习目标

2.1.1 了解 XGBoost 的参数与相关知识
2.1.2 掌握 XGBoost 的Python调用并将其运用到天气数据集预测

2.2 代码流程

Part1 基于天气数据集的XGBoost分类实践

Step1: 库函数导入
Step2: 数据读取/载入
Step3: 数据信息简单查看
Step4: 可视化描述
Step5: 对离散变量进行编码
Step6: 利用 XGBoost 进行训练与预测
Step7: 利用 XGBoost 进行特征选择
Step8: 通过调整参数获得更好的效果

2.3 算法实战

2.3.1 基于天气数据集的XGBoost分类实战

%%%数据集地址如下%%% :
https://tianchi-media.oss-cn-beijing.aliyuncs.com/DSW/7XGBoost/train.csv

step1:库函数导入

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import warnings
import xgboost

step2:数据载入

plt.rcParams['axes.unicode_minus'] = False

warnings.filterwarnings('ignore')
data = pd.read_csv(r"E:\train.csv")

step3:数据信息简单查看

data.info
data.head()
data = data.fillna(-1)
data.tail()
pd.Series(data['RainTomorrow']).value_counts()
data.describe()

step4:可视化描述

numerical_features = [x for x in data.columns if data[x].dtype == np.float64]
category_features = [x for x in data.columns if data[x].dtype != np.float64 and x != 'RainTomorrow']

sns.pairplot(data = data[['Rainfall',
                          'Evaporation',
                          'Sunshine'] + ['RainTomorrow']], diag_kind = 'hist', hue = 'RainTomorrow')
plt.show()
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()

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()
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()

step5:对离散变量进行编码


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['RainTomorrow'] = data['RainTomorrow'].apply(get_mapfunction(data['RainTomorrow']))

step6:接下来利用XGBoost进行训练与预测


from sklearn.model_selection import train_test_split

data_features_part = data[[x for x in data.columns if x != 'RainTomorrow']]
data_target_part = data['RainTomorrow']

x_train, x_test, y_train, y_test = train_test_split(data_features_part, data_target_part, test_size=0.2, random_state= 2020)

from xgboost.sklearn import XGBClassifier

clf = XGBClassifier()

clf.fit(x_train, y_train)

train_predict = clf.predict(x_train)
test_predict = clf.predict(x_test)
from sklearn import metrics

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()

step7:利用XGBoost进行特征选择

?sns.barplot

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

from sklearn.metrics import accuracy_score
from xgboost import plot_importance

def estimate(model, data):

    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=', pre)

step8:通过调整参数获得更好的效果


from sklearn.model_selection import GridSearchCV

learning_rate = [0.1, 0.3, 0.6]
subsample = [0.8, 0.9]
colsample_bytree = [0.6, 0.8]
max_depth = [3, 6, 8]

parameters = {
    'learning_rate': learning_rate,
    'subsample': subsample,
    'colsample_bytree': colsample_bytree,
    'max_depth': max_depth
}
model = XGBClassifier(n_estimators = 50)

clf = GridSearchCV(model, parameters, cv=3, scoring='accuracy', verbose=1, n_jobs=-1)
clf = clf.fit(x_train, y_train)
clf.best_params_

clf = XGBClassifier(colsample_bytree = 0.8, learning_rate = 0.3, max_depth = 6, subsample = 0.8)

clf.fit(x_train, y_train)

train_predict = clf.predict(x_train)
test_predict = clf.predict(x_test)

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()

3.知识点

3.1 XGBoost的重要参数

3.2 XGBoost原理粗略讲解

机器学习算法(二): 基于XGBoost的分类预测

Original: https://blog.csdn.net/lele_god/article/details/124481995
Author: lele_god
Title: 机器学习算法(二): 基于XGBoost的分类预测

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/661568/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球