XGBOOST代码实现-葡萄酒品质分类案例

本章会介绍如何调用XGBOOST模型API

导入相关的库

import joblib #用于保存模型
import  pandas as pd
import numpy as np
import xgboost as xgb # XGBOOST的库
from collections import Counter # 统计数据,专门用来可迭代对象元素频次统计的字典子类,自动统计每个元素出现多少次。
from sklearn.model_selection import train_test_split, GridSearchCV
from sklearn.metrics import classification_report
from sklearn.model_selection import StratifiedKFold # 分成K折交叉验证,类似于网格搜索时cv=折数
from sklearn.utils import class_weight # 计算样本权重

一、定义函数,对红酒品质分类源数据-->拆分乘训练集和测试集,并存储到csv中

def dm01_data_split():
    # 1.加载数据集
    df = pd.read_csv('红酒品质分类.csv')
    # 2.查看数据集
    print(df.info())

    #3.抽取特征数据和标签数据
    x = df.iloc[:,:-1]
    y = df.iloc[:,-1] -3 # []最后一列是标签,默认范围是[3,8]-->[0,5]
    #4.查看数据
    print(f'查看标签结果的分布情况,是否均衡?:{Counter(y)}')
    #5. 切分训练集和测试集
    x_train, x_test, y_train, y_test = train_test_split(x, y, test_size = 0.2, random_state = 23,stratify=y)
    # 6.把上述的训练集特征和标签数据拼接到一起,测试集特征和标签数据拼接到一起,最后写到文件中
    pd.concat([x_train,y_train],axis=1).to_csv('红酒品质分类_train.csv',index=False)     # 拼接特征和标签,axis=1左右拼接
    pd.concat([x_test,y_test],axis=1).to_csv('红酒品质分类_test.csv',index=False)
dm01_data_split()

二、定义函数,训练模型,并保存模型

XGBClassifier参数介绍:n_estimators:决策树的个数;max_depth:单棵决策树的最大深度;learning_rate:学习率,每棵树的权重缩放系数;
objective:损失函数(任务类型)二分类默认:binary:logistic;多分类:multi:softprob;回归任务:reg:squarederror

def dm02_train_model():
    # 1.读取训练集和测试集
    train_data = pd.read_csv('红酒品质分类_train.csv')
    test_data = pd.read_csv('红酒品质分类_test.csv')
    # 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'
    )
    # 加入权重,因为数据集是样本不均衡的
    # 参1:平衡权重 参2:标签数据(参考标签数据分布,平衡权重,)
    classes = np.unique(y_train)
    weights = class_weight.compute_class_weight(
    'balanced',
    classes=classes,
    y=y_train
)
    # 4.模型训练
    estimator.fit(x_train, y_train)
    # 5.模型评估
    print(f'准确率{estimator.score(x_test, y_test)}')
    # 6.保存模型
    joblib.dump(estimator,'红酒品质分类.pkl')
dm02_train_model()

三、定义函数,测试模型(网格搜索)

def dm03_use_model():
    # 1.读取训练集和测试集
    train_data = pd.read_csv('红酒品质分类_train.csv')
    test_data = pd.read_csv('红酒品质分类_test.csv')
    # 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('红酒品质分类.pkl')
    # 4. 创建网格搜索 + 交叉验证(结合分层采样数据)
    # 4.1 定义变量,记录参数组合
    param_dict = {
        'max_depth':[2,3,4,5,6,7],
        'n_estimators':[30,50,100,150],
        'learning_rate':[0.2,0.3,1,1.3]
    }
    # 4.2 创建分层采样数据对象
    # 参1:折数,参2:是否打乱数据,参3:随机种子
    skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=23)
    # 4.3 创建 网格搜索+交叉验证(结合分层采样数据)对象
    gs_estimator = GridSearchCV(estimator,param_dict,n_jobs=-1,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_score_}')
dm03_use_model()
posted @ 2026-06-26 10:32  王新文  阅读(8)  评论(0)    收藏  举报