UCI葡萄酒数据集完整加载流程教程

UCI葡萄酒数据集完整加载流程教程

数据集介绍

UCI葡萄酒数据集是机器学习中常用的经典数据集,包含178个葡萄酒样本,每个样本有13个化学特征属性,分为3个不同的类别(1, 2, 3),对应意大利同一区域三种不同酒庄的葡萄酒。

环境准备

首先需要导入必要的Python库:

1
2
3
4
5
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['SimHei']

数据加载与CSV文件解析

方法一:从UCI在线加载(推荐)

1
2
3
4
5
6
7
8
9
# 定义列名
column_names = ['Class label', 'Alcohol', 'Malic acid', 'Ash',
'Alcalinity of ash', 'Magnesium', 'Total phenols',
'Flavanoids', 'Nonflavanoid phenols', 'Proanthocyanins',
'Color intensity', 'Hue', 'OD280/OD315 of diluted wines', 'Proline']

# 从UCI服务器直接读取数据
df = pd.read_csv('https://archive.ics.uci.edu/ml/machine-learning-databases/wine/wine.data',
header=None, names=column_names)

方法二:使用sklearn内置数据集

1
2
3
4
5
6
from sklearn.datasets import load_wine

# 使用sklearn内置的葡萄酒数据集
wine_data = load_wine()
df = pd.DataFrame(data=wine_data.data, columns=wine_data.feature_names)
df['Class label'] = wine_data.target

数据预览

查看数据集前5行

1
2
print("数据集前5行:")
print(df.head())

输出示例:

1
2
3
4
   Class label  Alcohol  Malic acid  Ash  ...  Color intensity  Hue  OD280/OD315 of diluted wines  Proline
0 1 14.23 1.71 2.43 ... 7.00 0.70 1.56 1270
1 1 13.20 1.78 2.14 ... 6.10 0.65 1.60 1190
2 1 13.16 2.36 2.67 ... 6.60 0.68 1.58 1235

查看数据集后5行

1
2
print("\n数据集后5行:")
print(df.tail())

查看数据集基本信息

1
2
3
4
print("\n数据集形状:", df.shape)
print("\n数据集基本信息:")
print(df.info())
print("\n类别标签:", np.unique(df['Class label']))

统计分析

使用describe()函数分析数据统计特征

1
2
3
4
5
6
7
# 整体统计描述
print("整体统计描述:")
print(df.describe())

# 按类别分组统计
print("\n按类别分组的统计描述:")
print(df.groupby('Class label').describe())

describe()函数输出包含以下统计指标: - count: 非空值数量 - mean: 平均值 - std: 标准差 - min: 最小值 - 25%: 第一四分位数 - 50%: 中位数 - 75%: 第三四分位数 - max: 最大值

特定特征的详细分析

1
2
3
4
5
6
7
8
# 对酒精含量进行详细分析
alcohol_stats = df['Alcohol'].describe()
print("\n酒精含量的详细统计:")
print(alcohol_stats)

# 添加自定义统计量
print(f"\n酒精含量范围:{df['Alcohol'].max() - df['Alcohol'].min():.2f}")
print(f"酒精含量变异系数:{df['Alcohol'].std() / df['Alcohol'].mean():.4f}")

数据集划分(训练集/测试集)

基本划分方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# 准备特征矩阵X和标签向量y
X = df.iloc[:, 1:].values # 所有行,第1列到最后列(特征)
y = df.iloc[:, 0].values # 所有行,第0列(类别标签)

# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y,
test_size=0.3,
random_state=0,
stratify=y)

print(f"训练集大小:{X_train.shape}")
print(f"测试集大小:{X_test.shape}")
print(f"训练集类别比例:{np.unique(y_train, return_counts=True)}")
print(f"测试集类别比例:{np.unique(y_test, return_counts=True)}")

参数说明

  • test_size=0.3: 测试集占总数据的30%(常见比例为60:40, 70:30或80:20)
  • random_state=0: 设置随机种子确保结果可重现
  • stratify=y: 保持训练集和测试集中各类别比例与原始数据集一致

进阶划分技巧

1
2
3
4
5
# 对于小数据集的更精细划分(训练集/验证集/测试集)
X_temp, X_test, y_temp, y_test = train_test_split(X, y, test_size=0.2, random_state=0, stratify=y)
X_train, X_val, y_train, y_val = train_test_split(X_temp, y_temp, test_size=0.25, random_state=0, stratify=y_temp)

print(f"进阶划分 - 训练集:{X_train.shape}, 验证集:{X_val.shape}, 测试集:{X_test.shape}")

完整示例代码

以下是整合所有步骤的完整代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# 导入所需库
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.datasets import load_wine

# 1. 数据加载
column_names = ['Class label', 'Alcohol', 'Malic acid', 'Ash',
'Alcalinity of ash', 'Magnesium', 'Total phenols',
'Flavanoids', 'Nonflavanoid phenols', 'Proanthocyanins',
'Color intensity', 'Hue', 'OD280/OD315 of diluted wines', 'Proline']

df = pd.read_csv('https://archive.ics.uci.edu/ml/machine-learning-databases/wine/wine.data',
header=None, names=column_names)

# 2. 数据预览
print("=== 数据预览 ===")
print("前5行数据:")
print(df.head())
print("\n后5行数据:")
print(df.tail())
print(f"\n数据集形状:{df.shape}")
print(f"类别标签:{np.unique(df['Class label'])}")

# 3. 统计分析
print("\n=== 统计分析 ===")
print("整体统计描述:")
print(df.describe())

print("\n按类别统计描述:")
print(df.groupby('Class label').describe())

# 4. 数据集划分
X = df.iloc[:, 1:].values
y = df.iloc[:, 0].values

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=0, stratify=y)

print("\n=== 数据集划分结果 ===")
print(f"训练集大小:{X_train.shape}")
print(f"测试集大小:{X_test.shape}")

# 验证类别比例保持一致性
train_counts = np.unique(y_train, return_counts=True)
test_counts = np.unique(y_test, return_counts=True)
print(f"训练集类别分布:{dict(zip(train_counts[0], train_counts[1]))}")
print(f"测试集类别分布:{dict(zip(test_counts[0], test_counts[1]))}")

注意事项

  1. 数据规模考量:对于只有178个样本的小数据集,测试集比例不宜过大(通常20-30%)
  2. 随机种子设置:设置random_state参数可确保每次划分结果一致,便于结果复现
  3. 分层抽样:使用stratify=y参数确保类别比例一致,尤其对于不平衡数据集很重要
  4. 数据完整性:在划分前确保数据已经过清洗,处理缺失值和异常值

通过本教程,您已经掌握了UCI葡萄酒数据集的完整加载流程,包括数据获取、解析、预览、统计分析和划分,为后续的机器学习模型训练奠定了基础。