一.算法简介

Bagging思想:并行,由多个弱学习器预测结果,最红综合所有结果给出最终结果,代表算法为随机森林。

Boosting思想:串行,下一个学习器纠正上一个学习器的错误,从而提高学习器的性能,代表算法为Adaboost(提高错误样本的权重,减小正确样本的权重)、GBDT(借鉴残差的思想,梯度下降提高树的性能)、XGB

XBG(极端梯度提升树)是GBDT的改进版,在除了损失外还增加了正则化项,减小模型复杂度,从而防止过拟合的发生。

二.案例简介

三.代码详解

1.数据读取以及分割

def dm01_data_split():
    #1.加载数据集
    df = pd.read_csv('./data/红酒品质分类.csv')
    #2.查看数据集
    df.info()
    #3.抽取特征数据和标签数据
    x = df.iloc[:, :-1]
    y = df.iloc[:, -1] - 3    #最后一列是标签,默认标签是[3-8],-3后转换为[0,5]

    #4.查看数据
    print(x[:5])
    print(y[:5])
    print(f'查看标签数据是否均衡{Counter(y)}')

    #5.切分训练集和测试集                                                                        参5:参考数据集的标签分布
    x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=23, stratify=y)

    #6.将上述的训练及特征 和 标签数据拼接到一起, 测试集特征和 标签数据拼接到一起, 最后写到文件中
    #print(pd.concat([x_train, y_train], axis=1))   #axis = 1 表示横向拼接
    pd.concat([x_train, y_train], axis=1).to_csv('./data/红酒品质分类.csv_train', index=False)  #忽略索引
    pd.concat([x_test, y_test], axis=1).to_csv('./data/红酒品质分类.csv_test', index=False)     # 忽略索引

由标签可以看出存在数据分布不均的问题,解决方法是权重均衡

2.模型训练、保存

#2.训练模型,并保存
def dm02_train_model():
    #1.读取训练集和测试集
    train_data = pd.read_csv('./data/红酒品质分类.csv_train')
    test_data = pd.read_csv('./data/红酒品质分类.csv_test')

    #2.提取特征数据和标签数据
    x_train = train_data.iloc[:, :-1]  #所有行,除了最后一列
    y_train = train_data.iloc[:, -1]    #所有行,最后一列
    x_test = test_data.iloc[:, :-1]  # 所有行,除了最后一列
    y_test = test_data.iloc[:, -1]  # 所有行,最后一列
    #3.创建模型
    estimator = xgb.XGBClassifier(
        max_depth = 5,
        n_estimators = 100,
        learning_rate = 0.1,
        random_state = 23,       #随机种子
        objective = 'multi:softmax'
    )

    #加入 平衡权重,应为数据是不均衡的      快速导入:ALT+回车
    #                                参1:平衡权重     参2:标签数据(即参考标签数据分布,平衡权重)
    class_weight.compute_sample_weight('balanced', y_train)

    #4.模型训练
    estimator.fit(x_train, y_train)

    #5.模型评估
    print(f'准确率:{estimator.score(x_test, y_test)}')

    #6.保存模型
    joblib.dump(estimator, './model/红酒品质分类.pkl')  #后缀名也可以写.pth,都是pickle文件格式
    print('模型保持成功!')

3.模型预测

#3.测试模型
def dm03_ues_model():
    # 1.读取训练集和测试集
    train_data = pd.read_csv('./data/红酒品质分类.csv_train')
    test_data = pd.read_csv('./data/红酒品质分类.csv_test')

    # 2.提取特征数据和标签数据
    x_train = train_data.iloc[:, :-1]  # 所有行,除了最后一列
    y_train = train_data.iloc[:, -1]  # 所有行,最后一列
    x_test = test_data.iloc[:, :-1]  # 所有行,除了最后一列
    y_test = test_data.iloc[:, -1]  # 所有行,最后一列

    #3.加载模型
    estimator = joblib.load('./model/红酒品质分类.pkl')

    #4.创建网格搜索+交叉验证(结合分层采样数据),训练模型
    #4.1定义变量,记录:参数组合
    param_dict = {
        'max_depth':[2, 3, 5, 6],
        'n_estimators':[50, 100, 150],
        'learning_rate':[0.2, 0.3, 1.0]
    }
    #4.2创建分层采样对象
    #                   参1:折数   参2:是否打乱(数据)   参3:随机种子
    skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=23)
    #4.3创建 网格搜索 + 交叉验证(结合分层采用数据)对象
    gs_estimator = GridSearchCV(estimator, param_grid=param_dict, cv=skf)

    #5.模型训练
    gs_estimator.fit(x_train, y_train)

    #6.模型预测
    y_pred = gs_estimator.predict(x_test)
    print(f'预测值为:{y_pred}')
    #7.打印模型评估系数

    print(f'最优参数组合:{gs_estimator.best_params_}')
    print(f'最优模型对象:{gs_estimator.best_estimator_}')
    print(f'最优评分:{gs_estimator.best_score_}')
    print(f'准确率:{accuracy_score(y_test, y_pred)}')

4.完整代码

"""
新学:数据预处理:
                1.标签重置
                2.不均衡数据提取
                3.特征和标签拼接
                4.处理保存训练集和测试集
                5.权重平衡
"""

import joblib                                                   #保存模型
import numpy as np                                              #数据运算
import pandas as pd                                             #读数据
import xgboost as xgb                                           #极限提升树
from collections import Counter                                 #统计数据
from sklearn.model_selection import train_test_split,GridSearchCV
from sklearn.metrics import classification_report, accuracy_score  # 模型评估报告
from sklearn.model_selection import StratifiedKFold             #分层K折叠交叉验证,类似于网格搜索时,cv = 折数


from sklearn.utils import class_weight                          #平衡权重
#1.对红酒品质分类源数据-》拆分成,训练集和测试集,并保存导csv文件中



def dm01_data_split():
    #1.加载数据集
    df = pd.read_csv('./data/红酒品质分类.csv')
    #2.查看数据集
    df.info()
    #3.抽取特征数据和标签数据
    x = df.iloc[:, :-1]
    y = df.iloc[:, -1] - 3    #最后一列是标签,默认标签是[3-8],-3后转换为[0,5]

    #4.查看数据
    print(x[:5])
    print(y[:5])
    print(f'查看标签数据是否均衡{Counter(y)}')

    #5.切分训练集和测试集                                                                        参5:参考数据集的标签分布
    x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=23, stratify=y)

    #6.将上述的训练及特征 和 标签数据拼接到一起, 测试集特征和 标签数据拼接到一起, 最后写到文件中
    #print(pd.concat([x_train, y_train], axis=1))   #axis = 1 表示横向拼接
    pd.concat([x_train, y_train], axis=1).to_csv('./data/红酒品质分类.csv_train', index=False)  #忽略索引
    pd.concat([x_test, y_test], axis=1).to_csv('./data/红酒品质分类.csv_test', index=False)     # 忽略索引


#2.训练模型,并保存
def dm02_train_model():
    #1.读取训练集和测试集
    train_data = pd.read_csv('./data/红酒品质分类.csv_train')
    test_data = pd.read_csv('./data/红酒品质分类.csv_test')

    #2.提取特征数据和标签数据
    x_train = train_data.iloc[:, :-1]  #所有行,除了最后一列
    y_train = train_data.iloc[:, -1]    #所有行,最后一列
    x_test = test_data.iloc[:, :-1]  # 所有行,除了最后一列
    y_test = test_data.iloc[:, -1]  # 所有行,最后一列
    #3.创建模型
    estimator = xgb.XGBClassifier(
        max_depth = 5,
        n_estimators = 100,
        learning_rate = 0.1,
        random_state = 23,       #随机种子
        objective = 'multi:softmax'
    )

    #加入 平衡权重,应为数据是不均衡的      快速导入:ALT+回车
    #                                参1:平衡权重     参2:标签数据(即参考标签数据分布,平衡权重)
    class_weight.compute_sample_weight('balanced', y_train)

    #4.模型训练
    estimator.fit(x_train, y_train)

    #5.模型评估
    print(f'准确率:{estimator.score(x_test, y_test)}')

    #6.保存模型
    joblib.dump(estimator, './model/红酒品质分类.pkl')  #后缀名也可以写.pth,都是pickle文件格式
    print('模型保持成功!')


#3.测试模型
def dm03_ues_model():
    # 1.读取训练集和测试集
    train_data = pd.read_csv('./data/红酒品质分类.csv_train')
    test_data = pd.read_csv('./data/红酒品质分类.csv_test')

    # 2.提取特征数据和标签数据
    x_train = train_data.iloc[:, :-1]  # 所有行,除了最后一列
    y_train = train_data.iloc[:, -1]  # 所有行,最后一列
    x_test = test_data.iloc[:, :-1]  # 所有行,除了最后一列
    y_test = test_data.iloc[:, -1]  # 所有行,最后一列

    #3.加载模型
    estimator = joblib.load('./model/红酒品质分类.pkl')

    #4.创建网格搜索+交叉验证(结合分层采样数据),训练模型
    #4.1定义变量,记录:参数组合
    param_dict = {
        'max_depth':[2, 3, 5, 6],
        'n_estimators':[50, 100, 150],
        'learning_rate':[0.2, 0.3, 1.0]
    }
    #4.2创建分层采样对象
    #                   参1:折数   参2:是否打乱(数据)   参3:随机种子
    skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=23)
    #4.3创建 网格搜索 + 交叉验证(结合分层采用数据)对象
    gs_estimator = GridSearchCV(estimator, param_grid=param_dict, cv=skf)

    #5.模型训练
    gs_estimator.fit(x_train, y_train)

    #6.模型预测
    y_pred = gs_estimator.predict(x_test)
    print(f'预测值为:{y_pred}')
    #7.打印模型评估系数

    print(f'最优参数组合:{gs_estimator.best_params_}')
    print(f'最优模型对象:{gs_estimator.best_estimator_}')
    print(f'最优评分:{gs_estimator.best_score_}')
    print(f'准确率:{accuracy_score(y_test, y_pred)}')


#4.测试
if __name__ =='__main__':
    #dm01_data_split()
    #dm02_train_model()
    dm03_ues_model()

四.总结

通过此案例,主要学习了数据的处理方法,例如标签重置、处理数据部分不均问题,并且加强了对XGB的认识

Logo

汇聚全球AI编程工具,助力开发者即刻编程。

更多推荐