红葡萄酒质量预测实战:基于AI Studio数据集的决策树与随机森林模型评估

1次阅读
没有评论

共计 2103 个字符,预计需要花费 6 分钟才能阅读完成。

image.webp

背景与痛点

红葡萄酒质量预测在酿酒工业中具有重要意义。传统上,葡萄酒质量的评估依赖于专业品酒师的主观判断,这种方法存在几个明显问题:

红葡萄酒质量预测实战:基于 AI Studio 数据集的决策树与随机森林模型评估

  • 人力成本高,无法实现大规模快速评估
  • 主观性强,不同品酒师可能给出差异较大的评价
  • 难以追溯和量化评估标准

机器学习方法可以有效解决这些问题,通过量化理化指标与质量评分的关联性,建立客观、可复现的预测模型。

数据准备

AI Studio 提供的红葡萄酒数据集包含 11 个理化特征和 1 个质量评分(3- 8 分)。关键预处理步骤包括:

  1. 数据探索

    import pandas as pd
    
    data = pd.read_csv('winequality-red.csv')
    print(data.describe())
    print(data.isnull().sum())

  2. 特征工程

  3. 将质量评分转换为二分类问题(≥6 分为优质,否则为普通)

  4. 标准化数值型特征
  5. 检查并处理特征间相关性

  6. 数据分割

from sklearn.model_selection import train_test_split

X = data.drop('quality', axis=1)
y = data['quality'].apply(lambda x: 1 if x >=6 else 0)

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

模型实现

决策树模型

from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import classification_report

# 初始化模型
dt = DecisionTreeClassifier(max_depth=5, random_state=42)

# 训练模型
dt.fit(X_train, y_train)

# 预测与评估
y_pred = dt.predict(X_test)
print(classification_report(y_test, y_pred))

随机森林模型

from sklearn.ensemble import RandomForestClassifier

# 初始化模型
rf = RandomForestClassifier(n_estimators=100, max_depth=10, random_state=42)

# 训练模型
rf.fit(X_train, y_train)

# 预测与评估
y_pred = rf.predict(X_test)
print(classification_report(y_test, y_pred))

评估对比

我们使用以下关键指标评估模型性能:

  1. 准确率(Accuracy):正确预测的比例
  2. 精确率(Precision):预测为正样本中实际为正的比例
  3. 召回率(Recall):实际正样本中被正确预测的比例
  4. F1 分数:精确率和召回率的调和平均

在测试集上的对比结果如下:

指标 决策树 随机森林
准确率 0.81 0.85
精确率 0.83 0.86
召回率 0.87 0.90
F1 分数 0.85 0.88

随机森林在所有指标上均优于单棵决策树,这得益于其集成学习的优势。

生产建议

  1. 模型调参

  2. 使用网格搜索优化超参数

    from sklearn.model_selection import GridSearchCV
    
    param_grid = {'n_estimators': [50, 100, 200],
        'max_depth': [5, 10, 15]
    }
    
    grid_search = GridSearchCV(RandomForestClassifier(random_state=42), param_grid, cv=5)
    grid_search.fit(X_train, y_train)
    print(grid_search.best_params_)

  3. 过拟合预防

  4. 增加 max_depth 限制

  5. 使用 min_samples_split 参数
  6. 添加交叉验证

  7. 特征重要性分析

importances = rf.feature_importances_
feat_importances = pd.Series(importances, index=X.columns)
feat_importances.nlargest(5).plot(kind='barh')

避坑指南

  1. 数据不平衡问题

  2. 原始数据中优质酒占比约 60%,若不平衡更严重需使用过采样 / 欠采样

  3. 特征相关性

  4. 高相关特征可能导致模型不稳定,需检查并移除

  5. 模型解释性

  6. 决策树可视化帮助理解模型决策过程

    from sklearn.tree import plot_tree
    import matplotlib.pyplot as plt
    
    plt.figure(figsize=(15,10))
    plot_tree(dt, feature_names=X.columns, filled=True)
    plt.show()

总结

通过本次实践,我们验证了随机森林在红葡萄酒质量预测上的优势。建议在实际应用中:

  1. 优先尝试随机森林等集成方法
  2. 重视特征工程和参数调优
  3. 关注模型解释性以增强业务可信度

读者可以在 AI Studio 上复现这个实验,尝试调整参数或使用其他算法比较效果。

正文完
 0
评论(没有评论)