1. 需求分析
用XGBoost算法对葡萄酒品质进行多分类预测
2. 数据说明
葡萄牙北部绿酒(Vinho Verde)理化检测 + 人工感官评分数据集,2009 年 Cortez 发布于 UCI 机器学习库,同时支持回归(预测分数)、分类(划分品质等级)两大任务。
- 红葡萄酒:
,1599 行,11 特征 + 1 标签winequality-red.csv - 白葡萄酒:
,4898 行,11 特征 + 1 标签winequality-white.csv
特征列:
| 英文名称 | 中文释义 | 业务意义 |
|---|---|---|
| fixed acidity | 固定酸度 | 酒石酸、苹果酸等不易挥发有机酸,决定基础酸度 |
| volatile acidity | 挥发性酸度 | 乙酸,过高会出现醋味,大幅降低品质 |
| citric acid | 柠檬酸 | 提升果香,少量可柔化口感 |
| residual sugar | 残糖 | 甜味来源,干型 / 甜型酒区分核心指标 |
| chlorides | 氯化物 | 含盐量,过高带来咸味、劣质口感 |
| free sulfur dioxide | 游离二氧化硫 | 抑菌抗氧化,过量产生刺鼻硫磺味 |
| total sulfur dioxide | 总二氧化硫 | 游离 + 结合 SO₂,食品安全限制指标 |
| density | 密度 | 与酒精度、含糖量强相关 |
| pH | 酸碱度 | 酸度平衡,影响稳定性与风味 |
| sulphates | 硫酸盐 | 提升葡萄酒香气 |
| alcohol | 酒精度 | 高度数通常对应更高品质评分 |
标签列:quality
人工感官打分,区间 3~8 分(无 1/2/9/10),类别极度不均衡:
- 红酒主流:5、6 分;少量 3、4、7、8
- 白酒主流:5、6 分;极少 3、4、8
分类任务常用标签转换方案
原始 quality 是有序多分类,工程上三种主流处理:
方案 1:二分类
- 好酒:quality ≥ 6 → label=1
- 差酒:quality ≤ 5 → label=0 适用:逻辑回归、SVM、二分类树、AUC/KS 评估
方案 2:三分类
- 低档:3,4
- 中档:5,6
- 高档:7,8 适用:有序分类模型(Ordinal Logistic、XGBoost 序分类)
方案 3:原始多分类(6 类:3,4,5,6,7,8)
直接以分数为 6 分类标签,样本分布极不均衡,适合类别不平衡建模(加权损失、过采样)
3. 建模
import pandas as pd from sklearn.metrics import classification_report from sklearn.model_selection import train_test_split, GridSearchCV import xgboost as xgb # xgboost包 import joblib3.1 加载数据
# 1. 获取数据 train = pd.read_csv('./data/winequality-red.csv', sep=';') train.head()3.2 数据预处理
提取特征和标签;缺失值处理;标签处理;划分数据集
# 2. 数据预处理 # 2.1 提取特征和标签 x = train.iloc[:, :-1] y = train['quality'] y.value_counts() # 2.4 标签处理(xgboost可预测多分类,标签要从0开始) y = y - 3 # 2.5 划分数据集 x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=14, stratify=y)3.3 特征工程(无)
3.4 模型训练
# 4 模型训练 # 4.1 场景2:XGBoost(默认参数) # 参数解释:objective:目标函数,多分类问题使用multi:softmax;num_class:标签数量 estimator1 = xgb.XGBClassifier(objective='multi:softmax', num_class=len(y.unique()), random_state=666) estimator1.fit(x_train, y_train) y_pre1 = estimator1.predict(x_test) print('XGBoost(默认参数)分类报告:\n', classification_report(y_test, y_pre1, zero_division=0))3.5 模型评估
# 5. 模型评估 estimator = xgb.XGBClassifier(learning_rate=0.05, max_depth=10, n_estimators=120, objective='multi:softmax', num_class=len(y.unique()), random_state=666) estimator.fit(x_train, y_train) y_pre = estimator.predict(x_test) print('分类报告:\n', classification_report(y_test, y_pre, zero_division=0))3.6 模型保存
# 6. 模型保存 joblib.dump(estimator, './model/xgb_wine_red_model.pkl')3.7 模型应用(预测)
# 7. 加载模型 estimator = joblib.load('./model/xgb_wine_red_model.pkl') # 8.模型预测 y_pre = estimator.predict(x_test) y_pre