Iris数据集全解析:从数据读取到可视化展示的完整流程(Python版)
在数据科学领域,Iris数据集就像"Hello World"对于编程初学者一样经典。这个包含150朵鸢尾花测量数据的小型数据集,自1936年由统计学家Ronald Fisher首次引入以来,已经成为机器学习入门和数据分析教学的标准教材。本文将带你用Python完整走一遍数据处理的闭环流程,从数据加载到最终的可视化呈现,每个环节都会分享实际项目中积累的技巧和容易踩的坑。
1. 环境准备与数据加载
工欲善其事,必先利其器。我们先配置好分析环境:
# 基础数据分析三件套
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline # Jupyter Notebook魔法命令
# 美化图形显示
plt.style.use('seaborn')
plt.rcParams['font.family'] = ['SimHei'] # 中文显示
plt.rcParams['axes.unicode_minus'] = False # 负号显示
Iris数据集可以通过多种方式获取,每种方式各有优劣:
| 加载方式 | 优点 | 缺点 | 适用场景 |
|---|---|---|---|
| sklearn内置 | 无需额外文件 | 缺少原始列名 | 快速原型开发 |
| CSV文件 | 保留完整元数据 | 需要文件路径管理 | 生产环境 |
| 网络URL | 无需本地存储 | 依赖网络连接 | 教学演示 |
推荐使用sklearn的标准化加载方式:
from sklearn.datasets import load_iris
# 加载数据集
iris = load_iris()
# 转换为DataFrame
df = pd.DataFrame(iris.data, columns=iris.feature_names)
df['species'] = pd.Categorical.from_codes(iris.target, iris.target_names)
注意:直接从sklearn加载时,特征名称可能被简写为"sepal length (cm)"等形式,建议统一重命名为更简洁的格式:
df.columns = ['sepal_length', 'sepal_width', 'petal_length', 'petal_width', 'species']
2. 数据探索与描述性统计
拿到数据后的第一步不是急着建模,而是要充分了解数据的"脾气秉性"。以下是几个必看的数据快照:
# 查看数据样本
display(df.sample(5, random_state=42))
# 数据结构概览
print(f"数据集形状:{df.shape}")
df.info()
描述性统计能揭示数据的分布特征:
stats = df.describe().T
stats['skew'] = df.skew(numeric_only=True) # 添加偏度指标
stats['kurtosis'] = df.kurtosis(numeric_only=True) # 添加峰度指标
display(stats)
关键发现:
- 花瓣宽度(petal_width)的极差最大(0.1-2.5cm)
- 花萼长度(sepal_length)的标准差最小,数据相对集中
- 花瓣长度(petal_length)呈现左偏分布(偏度-0.27)
类别分布分析同样重要:
species_dist = df['species'].value_counts()
print("各类别样本数量:")
display(species_dist)
# 各类别特征均值对比
species_means = df.groupby('species').mean()
display(species_means.style.background_gradient(cmap='Blues'))
3. 单变量可视化分析
单变量分析是理解每个特征独立分布的基础。我们使用三种互补的可视化方式:
3.1 直方图与密度图组合
fig, axes = plt.subplots(2, 2, figsize=(12, 8))
features = df.columns[:-1] # 排除类别列
for ax, feature in zip(axes.flat, features):
# 直方图
df[feature].plot.hist(ax=ax, bins=15, alpha=0.6, color='skyblue', edgecolor='black')
# 密度图
df[feature].plot.kde(ax=ax, secondary_y=True, color='red', linewidth=2)
ax.set_title(f'{feature}分布', pad=10)
ax.set_ylabel('频数')
ax.right_ax.set_ylabel('密度')
plt.tight_layout()
plt.show()
3.2 箱线图分析
箱线图能直观显示离群点和数据分布范围:
plt.figure(figsize=(10, 6))
df.boxplot(column=features.tolist(), grid=False)
plt.title('特征值箱线图对比', pad=15)
plt.xticks(rotation=45)
plt.ylabel('厘米(cm)')
plt.show()
提示:当发现离群点时,不要急于删除,先确认是否为测量误差。在Iris数据中,看似离群的值可能是不同物种的自然变异。
3.3 小提琴图进阶分析
结合箱线图和密度图的小提琴图能提供更丰富的信息:
import seaborn as sns
plt.figure(figsize=(12, 6))
sns.violinplot(data=df.melt(id_vars='species'),
x='variable', y='value',
hue='species', split=True,
inner='quartile', palette='Set2')
plt.title('各类别特征分布对比', pad=15)
plt.xlabel('特征')
plt.ylabel('测量值(cm)')
plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left')
plt.show()
4. 多变量关系可视化
变量间的交互关系往往能揭示更深层的模式。以下是三种经典的多变量分析方法:
4.1 散点图矩阵
sns.pairplot(df, hue='species', palette='Set2',
diag_kind='kde', markers=['o', 's', 'D'],
plot_kws={'alpha':0.7, 'edgecolor':'black'},
height=2.5)
plt.suptitle('特征间关系矩阵', y=1.02)
plt.show()
从矩阵图中可以明显看出:
- 花瓣长度与宽度呈现清晰的线性关系
- setosa物种在所有特征上都与其他两类明显分离
- versicolor和virginica在花萼特征上有部分重叠
4.2 热力图分析
量化特征间的相关程度:
plt.figure(figsize=(8, 6))
corr = df.corr(numeric_only=True)
mask = np.triu(np.ones_like(corr, dtype=bool)) # 隐藏上半三角
sns.heatmap(corr, mask=mask, annot=True, cmap='coolwarm',
center=0, linewidths=.5, fmt='.2f')
plt.title('特征相关系数矩阵', pad=15)
plt.xticks(rotation=45)
plt.show()
相关系数揭示:
- 花瓣长度与宽度高度相关(0.96)
- 花萼长度与宽度基本无关(-0.11)
- 花萼长度与花瓣长度中度相关(0.87)
4.3 平行坐标图
对于分类问题,平行坐标图能直观展示特征与类别的关系:
from pandas.plotting import parallel_coordinates
plt.figure(figsize=(10, 6))
parallel_coordinates(df, 'species', colormap='Set2', alpha=0.7)
plt.title('各类别特征平行坐标对比', pad=15)
plt.xlabel('特征')
plt.ylabel('测量值(cm)')
plt.grid(alpha=0.3)
plt.show()
5. 高级可视化技巧
在基础图表之上,我们可以通过组合和增强来提取更多洞见:
5.1 分面网格图
g = sns.FacetGrid(df.melt(id_vars='species'),
col='variable', hue='species',
col_wrap=2, palette='Set2',
sharey=False, height=4, aspect=1.5)
g.map(sns.kdeplot, 'value', fill=True, alpha=0.5)
g.add_legend(title='物种')
g.fig.suptitle('各类别特征分布对比', y=1.03)
plt.show()
5.2 3D散点图
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure(figsize=(10, 8))
ax = fig.add_subplot(111, projection='3d')
for species, group in df.groupby('species'):
ax.scatter(group['sepal_length'],
group['sepal_width'],
group['petal_length'],
label=species, s=50, alpha=0.7)
ax.set_xlabel('Sepal Length')
ax.set_ylabel('Sepal Width')
ax.set_zlabel('Petal Length')
ax.set_title('三维特征空间分布', pad=15)
ax.legend()
plt.show()
5.3 交互式可视化
在Jupyter中实现交互探索(需要安装plotly):
import plotly.express as px
fig = px.scatter_3d(df, x='sepal_length', y='sepal_width',
z='petal_length', color='species',
symbol='species', opacity=0.7,
title='鸢尾花三维特征空间')
fig.update_layout(margin=dict(l=0, r=0, b=0, t=30))
fig.show()
850



被折叠的 条评论
为什么被折叠?



