蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

运行 Iris 数据理解、缺失检查、1.5×IQR 边界与相关性实测

PYTHONWindows 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。explore-data-understanding.py
explore-data-understanding.py192 行
"""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()
本例需在 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。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境: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。

入口文件:projects/ml-data-understanding-lab/explore-data-understanding.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-data-understanding.py,或下载右侧课程工程包。
  2. 确认本地已准备 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。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:机器学习

课程关联工程包(登记关联58章) · 含当前章节或实例 · mbskycom202612a449.zip

下载课程关联工程包:机器学习

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a460.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习