数据理解
系统核对机器学习建模前的数据理解全流程:数据结构与类型检查、缺失值与分位数质量体检、箱线图 1.5×IQR 异常边界判定、相关性与类别区分度分析,并基于 Iris 数据集完成离线实测。
学完这一章,你能够
- 系统核对机器学习建模前的数据理解全流程:数据结构与类型检查、缺失值与分位数质量体检、箱线图 1.5×IQR 异常边界判定、相关性与类别区分度分析,并基于 Iris 数据集完成离线实测。
数据理解的定位、核心问题与工具链
开展任何机器学习任务(房价预测、图像分类或个性推荐)之前,首要步骤并非挑选算法,而是开展系统性的数据理解(Data Understanding)。数据理解的目标是在动手建模前查明三类基本事实:其一,数据具有怎样的表结构、样本规模与字段类型;其二,数据是否干净完整,是否存在缺失、录入错误或极端离群值;其三,各特征自身服从什么分布,特征之间以及特征与目标标签之间隐含哪些模式与关联。这一阶段以统计核查与可视化探索为主,直接决定后续的数据清洗方案、特征工程策略与模型选型。
Python 数据分析生态通常围绕三大工具协同工作:pandas 提供 DataFrame 表格抽象,负责 CSV/Excel 读写、筛选、缺失核查与描述性统计;matplotlib 作为底层绘图引擎,可精细控制直方图、箱线图、散点图与热力图等全部元素;seaborn 基于 matplotlib 提供更高层的统计绘图封装。由于本验证环境未安装 seaborn,本站离线实验全部基于 pandas + numpy + scipy + scikit-learn 完成精确数值统计与分布核对,并将 seaborn 绘图接口单独记入待补项。
步骤一:加载数据与结构概览
拿到数据集后的第一步是加载并做结构体检:用 df.shape 确认行列维度,用 df.head() 抽查前几条记录直观理解字段语义,用 df.info() 汇总列名(Column)、非空计数(Non-Null Count)与存储类型(Dtype,如 int64、float64 与文本/字符串列),从而第一时间暴露类型错配或缺失列。原教程提供的两处 iris.csv 下载链接已单独捕获并留存于私有证据目录(不对外分发);本站离线实验改用 scikit-learn 内置 load_iris(as_frame=True) 构造对齐的 150 行 × 5 列 DataFrame,实测 4 个花萼/花瓣测量特征均为 float64,首行记录为 sepal_length=5.1、sepal_width=3.5、petal_length=1.4、petal_width=0.2、species='setosa',三类品种各占 50 条样本、类别完全均衡。
步骤二:质量体检与描述性统计
真实业务数据常夹杂缺失值(NaN)与越界录入错误。标准核查组合是先以 df.isnull().sum() 汇总各列缺失数量与占比,再通过 df.describe() 审查数值列的计数(count)、均值(mean)、标准差(std)、最小值(min)、四分位数(25%、50% 中位数、75%)与最大值(max),借助 min/max 与业务常识快速筛查离谱记录(例如年龄出现 200 岁)。本站实测 Iris 全部 5 列缺失数均为 0,sepal_length 均值 5.8433、标准差 0.8281、范围 [4.3, 7.9],petal_length 均值 3.7580、标准差 1.7653、范围 [1.0, 6.9];另构造含缺失与 age=200 的受控脏数据表,实测精确检出 age 缺失 2 处、score 缺失 1 处并标出越界年龄。
步骤三:分布诊断、IQR 边界与特征相关性
除汇总数字外,直方图、箱线图、散点图矩阵与 Pearson 相关矩阵热力图是从单变量走向多变量洞察的核心手段:直方图展示特征在不同区间的聚集形态;箱线图用中位数、Q1/Q3 箱体与 [Q1 - 1.5×IQR, Q3 + 1.5×IQR] 须线标记潜在离群点;散点图矩阵观察两两特征的联合聚集;相关系数矩阵在 [-1, 1] 范围内量化线性关联(接近 +1 为强正相关、接近 -1 为强负相关、接近 0 表示无明显线性相关)。需特别提醒:原始可视化示例代码块中曾误混入中文全角逗号,直接运行会触发 SyntaxError,编写脚本时务必保持英文半角标点。
完成检查后应沉淀结构化数据调查报告。本站基于 Iris 全部 150 条样本实测复核并修正一处常见细节:虽然所有生物测量值均无缺失且处于自然生理范围,但严格按 1.5×IQR 规则检验时,sepal_width(Q1=2.8、中位数 3.0、Q3=3.3、IQR=0.5,上下须 [2.05, 4.05])实际会标出 4 个边界外点 [2.0, 4.1, 4.2, 4.4],而其余三列均为 0 个;这说明统计规则标出的候选离群点仍需结合领域知识决定保留而非盲目删除。同时实测证实:petal_length 与 petal_width 的 Pearson 相关系数高达 0.9629(存在明显信息冗余),sepal_width 与 petal_length 呈中等负相关(-0.4284);setosa 花瓣长度最大仅 1.9(均值 1.462),与 versicolor(均值 4.260)及 virginica(均值 5.552,二者最小为 3.0)完全线性可分;sepal_width 经 Shapiro-Wilk 正态检验得 W=0.9849、p=0.1012(>0.05),未拒绝正态分布假设。
运行 Iris 数据理解、缺失检查、1.5×IQR 边界与相关性实测
"""Independent offline lab for ML Ch 11: Data Understanding (Iris overview, quality, IQR, correlation)."""
import io
import json
import platform
import numpy as np
import pandas as pd
from scipy import stats
from sklearn.datasets import load_iris
def main():
cases = []
# 1. Load Iris via sklearn (offline equivalent of iris.csv) and inspect structure
iris = load_iris(as_frame=True)
df = iris.frame.copy()
df = df.rename(
columns={
"sepal length (cm)": "sepal_length",
"sepal width (cm)": "sepal_width",
"petal length (cm)": "petal_length",
"petal width (cm)": "petal_width",
}
)
df["species"] = df["target"].map(dict(enumerate(iris.target_names)))
df = df[["sepal_length", "sepal_width", "petal_length", "petal_width", "species"]]
buf = io.StringIO()
df.info(buf=buf)
info_text = buf.getvalue()
num_cols = ["sepal_length", "sepal_width", "petal_length", "petal_width"]
dtypes_ok = all(str(df[c].dtype) == "float64" for c in num_cols)
species_counts = df["species"].value_counts().to_dict()
c1_ok = (
df.shape == (150, 5)
and dtypes_ok
and len(df.head()) == 5
and "150 non-null" in info_text
and species_counts == {"setosa": 50, "versicolor": 50, "virginica": 50}
)
cases.append(
dict(
name="iris_load_and_overview",
inputs=dict(source="sklearn.datasets.load_iris(as_frame=True)"),
prerequisites="使用 scikit-learn 内置鸢尾花数据集本地离线还原 150x5 表格结构,不依赖外网下载。",
action="核对 df.shape、df.head()、df.info() 非空计数、数值列 float64 类型及三品种样本均衡性。",
expected=dict(shape=[150, 5], numeric_float64=True, classes_balanced=True),
actual=dict(
shape=list(df.shape),
numeric_float64=dtypes_ok,
classes_balanced=(species_counts == {"setosa": 50, "versicolor": 50, "virginica": 50}),
),
measurements=dict(
head_first_row=df.iloc[0].to_dict(),
species_counts=species_counts,
columns=list(df.columns),
),
passed=c1_ok,
)
)
# 2. Quality inspection: missing counts, missing ratios, describe() summary + synthetic dirty check
missing_counts = df.isnull().sum().to_dict()
missing_ratios = (df.isnull().sum() / len(df) * 100.0).round(2).to_dict()
desc = df[num_cols].describe()
dirty_df = pd.DataFrame({"age": [24.0, np.nan, 31.0, 200.0, np.nan], "score": [88.0, 91.0, np.nan, 79.0, 85.0]})
dirty_missing = dirty_df.isnull().sum().to_dict()
dirty_age_max = float(dirty_df["age"].max())
c2_ok = (
all(v == 0 for v in missing_counts.values())
and int(desc.loc["count", "sepal_length"]) == 150
and dirty_missing == {"age": 2, "score": 1}
and dirty_age_max == 200.0
)
cases.append(
dict(
name="iris_missing_and_describe_quality",
inputs=dict(iris_rows=150, synthetic_dirty_rows=5),
prerequisites="同时核验干净鸢尾花表与含缺失值/200岁极端值对照表的体检指标。",
action="执行 isnull().sum()、缺失比例与 describe() 八项统计,验证空值计数与极值排查逻辑。",
expected=dict(iris_zero_missing=True, dirty_missing_detected=True, extreme_age_flagged=True),
actual=dict(
iris_zero_missing=all(v == 0 for v in missing_counts.values()),
dirty_missing_detected=(dirty_missing == {"age": 2, "score": 1}),
extreme_age_flagged=(dirty_age_max == 200.0),
),
measurements=dict(
iris_missing_ratio_pct=missing_ratios,
sepal_length_stats={k: round(float(desc.loc[k, "sepal_length"]), 4) for k in desc.index},
petal_length_stats={k: round(float(desc.loc[k, "petal_length"]), 4) for k in desc.index},
dirty_missing_counts=dirty_missing,
),
passed=c2_ok,
)
)
# 3. Distribution, 1.5*IQR fence inspection, and Shapiro-Wilk normality check on sepal_width
iqr_report = {}
for col in num_cols:
q1 = float(df[col].quantile(0.25))
q3 = float(df[col].quantile(0.75))
iqr = q3 - q1
lo = q1 - 1.5 * iqr
hi = q3 + 1.5 * iqr
flagged = sorted(float(v) for v in df.loc[(df[col] < lo) | (df[col] > hi), col])
iqr_report[col] = dict(
q1=round(q1, 4),
median=round(float(df[col].median()), 4),
q3=round(q3, 4),
iqr=round(iqr, 4),
lower_fence=round(lo, 4),
upper_fence=round(hi, 4),
iqr_flagged_values=flagged,
)
sw_stat, sw_p = stats.shapiro(df["sepal_width"].to_numpy())
sw_flagged = iqr_report["sepal_width"]["iqr_flagged_values"]
other_flagged = sum(len(iqr_report[c]["iqr_flagged_values"]) for c in ["sepal_length", "petal_length", "petal_width"])
c3_ok = sw_flagged == [2.0, 4.1, 4.2, 4.4] and other_flagged == 0 and float(sw_p) > 0.05
cases.append(
dict(
name="iris_distribution_iqr_and_outliers",
inputs=dict(iqr_multiplier=1.5, normality_test="Shapiro-Wilk"),
prerequisites="按 1.5*IQR 箱线图须边界与正态性检验复核鸢尾花四项数值分布。",
action="核实 sepal_width 按 1.5*IQR 规则会标出 4 个边界外值 [2.0, 4.1, 4.2, 4.4](属合理生物极值),且 Shapiro-Wilk p>0.05 近似正态。",
expected=dict(sepal_width_iqr_count=4, other_features_iqr_count=0, sepal_width_shapiro_p_gt_005=True),
actual=dict(
sepal_width_iqr_count=len(sw_flagged),
other_features_iqr_count=other_flagged,
sepal_width_shapiro_p_gt_005=(float(sw_p) > 0.05),
),
measurements=dict(
iqr_summary=iqr_report,
sepal_width_shapiro_w=round(float(sw_stat), 4),
sepal_width_shapiro_p=round(float(sw_p), 4),
),
passed=c3_ok,
)
)
# 4. Pearson correlation matrix & species-level petal separation
corr = df[num_cols].corr(method="pearson")
r_petal = round(float(corr.loc["petal_length", "petal_width"]), 4)
r_sw_pl = round(float(corr.loc["sepal_width", "petal_length"]), 4)
diag_ones = bool(np.allclose(np.diag(corr.to_numpy()), np.ones(4), atol=1e-12))
sym_ok = bool(np.allclose(corr.to_numpy(), corr.to_numpy().T, atol=1e-12))
setosa_max_pl = float(df.loc[df["species"] == "setosa", "petal_length"].max())
non_setosa_min_pl = float(df.loc[df["species"] != "setosa", "petal_length"].min())
species_petal_means = (
df.groupby("species")[["petal_length", "petal_width"]].mean().round(4).to_dict(orient="index")
)
c4_ok = r_petal > 0.96 and r_sw_pl < -0.4 and diag_ones and sym_ok and setosa_max_pl < non_setosa_min_pl
cases.append(
dict(
name="iris_correlation_and_class_separation",
inputs=dict(features=num_cols, method="pearson"),
prerequisites="计算 4x4 数值特征相关矩阵并按品种分组核对花瓣尺寸可分性。",
action="验证 petal_length 与 petal_width 相关系数 >0.96、相关矩阵对称且对角为 1,并确认 setosa 花瓣长度与另两品种零重叠。",
expected=dict(
petal_corr_gt_096=True,
corr_matrix_valid=True,
setosa_petal_separated=True,
),
actual=dict(
petal_corr_gt_096=(r_petal > 0.96),
corr_matrix_valid=(diag_ones and sym_ok),
setosa_petal_separated=(setosa_max_pl < non_setosa_min_pl),
),
measurements=dict(
petal_length_width_corr=r_petal,
sepal_width_petal_length_corr=r_sw_pl,
setosa_petal_length_max=setosa_max_pl,
other_species_petal_length_min=non_setosa_min_pl,
species_petal_means=species_petal_means,
),
passed=c4_ok,
)
)
payload = dict(
version=platform.python_version(),
system=platform.system(),
pandas=pd.__version__,
cases=cases,
)
print(json.dumps(payload, ensure_ascii=False))
if __name__ == "__main__":
main()
- 核对 Iris (150, 5) 均衡分布、零缺失统计与受控脏数据检出、sepal_width 的 4 个 1.5×IQR 边界外点与 Shapiro-Wilk p=0.1012,以及花瓣长宽相关性 r=0.9629 与 setosa 线性可分界限。
所需环境:Windows x64 CPU、CPython 3.12.14、NumPy 2.5.4、SciPy 1.18.1、scikit-learn 1.9.1、pandas 3.1.0、Matplotlib 3.11.2。
当前源码 SHA256:dbf2fe33c0f7e34308e4e0213a37361016280137c18a3522e6988260103a9ba8
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64 CPU、CPython 3.12.14、NumPy 2.5.4、SciPy 1.18.1、scikit-learn 1.9.1、pandas 3.1.0、Matplotlib 3.11.2。
ZIP SHA256:6b0c70f635e7dac9e702dd33608f54415a9248f7063477c3539595f141554a33
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
对 Iris 数据集执行 1.5×IQR 箱线图检测时,为何 sepal_width 会被标出 4 个边界外点,是否应当直接删除?
展开参考解答
sepal_width 的 Q1=2.8、Q3=3.3、IQR=0.5,上下须为 [2.05, 4.05],因此 [2.0, 4.1, 4.2, 4.4] 落在须线外;但它们均为真实植物测量记录而非录入错误,应结合生物领域背景予以保留而非机械剔除。