"""Independent offline lab for ML Ch 14: Data Visualizations (pure Matplotlib + Pandas EDA & PNG charts)."""
import argparse
import hashlib
import json
import platform
from pathlib import Path
import numpy as np
import pandas as pd
def sha(path: Path) -> str:
return hashlib.sha256(path.read_bytes()).hexdigest()
def build_owned_passenger_cohort(n: int = 360) -> pd.DataFrame:
"""Deterministic owned synthetic passenger dataset (not external Titanic CSV)."""
rng = np.random.default_rng(202614)
sex = rng.choice(["male", "female"], size=n, p=[0.62, 0.38])
pclass = rng.choice([1, 2, 3], size=n, p=[0.24, 0.22, 0.54])
age = np.where(
pclass == 1,
rng.normal(38.0, 13.0, n),
np.where(pclass == 2, rng.normal(30.0, 11.0, n), rng.normal(25.0, 10.0, n)),
)
age = np.clip(age, 1.0, 78.0).round(1)
parch = rng.choice([0, 1, 2, 3], size=n, p=[0.74, 0.14, 0.09, 0.03])
sibsp = rng.choice([0, 1, 2, 3], size=n, p=[0.66, 0.22, 0.08, 0.04])
embarked = rng.choice(["S", "C", "Q"], size=n, p=[0.72, 0.19, 0.09]).astype(object)
fare = np.where(
pclass == 1,
rng.gamma(shape=3.2, scale=28.0, size=n) + 25.0,
np.where(pclass == 2, rng.gamma(shape=3.0, scale=6.5, size=n) + 8.0, rng.gamma(shape=2.4, scale=3.5, size=n) + 4.0),
)
# Inject a few high luxury-cabin fares (realistic right-tail outliers)
first_idx = np.where(pclass == 1)[0]
fare[first_idx[:4]] = np.array([263.0, 310.0, 420.0, 512.0])
fare = fare.round(2)
logits = 2.1 * (sex == "female") - 1.15 * (pclass - 1) - 0.015 * (age - 28.0) + 0.004 * fare - 0.55
probs = 1.0 / (1.0 + np.exp(-logits))
survived = (rng.random(n) < probs).astype(int)
# Inject missing values into age and embarked
age[rng.choice(n, size=48, replace=False)] = np.nan
embarked[rng.choice(n, size=3, replace=False)] = None
return pd.DataFrame(
{
"survived": survived,
"pclass": pclass,
"sex": sex,
"age": age,
"sibsp": sibsp,
"parch": parch,
"fare": fare,
"embarked": embarked,
}
)
def run_cases(fig_dir: Path | None):
df = build_owned_passenger_cohort(360)
cases = []
figures = {}
# 1. Cohort overview and missing inspection
missing = {k: int(v) for k, v in df.isnull().sum().items()}
c1_ok = df.shape == (360, 8) and missing["age"] == 48 and missing["embarked"] == 3 and missing["fare"] == 0
cases.append(
dict(
name="cohort_summary_and_missing_check",
inputs=dict(rows=360, cols=8, seed=202614),
prerequisites="使用固定种子构造 360 行自有合成乘客队列(不联网下载外部 Titanic 文件)。",
action="核对表维度、缺失值分布与数值摘要,明确区分自有合成教学数据与外部历史数据集。",
expected=dict(shape=[360, 8], age_missing=48, embarked_missing=3, fare_missing=0),
actual=dict(
shape=list(df.shape),
age_missing=missing["age"],
embarked_missing=missing["embarked"],
fare_missing=missing["fare"],
),
measurements=dict(
missing_counts=missing,
age_mean=round(float(df["age"].mean()), 2),
age_median=round(float(df["age"].median()), 2),
fare_median=round(float(df["fare"].median()), 2),
fare_max=float(df["fare"].max()),
),
passed=c1_ok,
)
)
# 2. Univariate analysis: age histogram bins, fare boxplot IQR outliers, sex bar counts
age_clean = df["age"].dropna().to_numpy()
hist_counts, hist_edges = np.histogram(age_clean, bins=20)
peak_bin = int(np.argmax(hist_counts))
peak_range = [round(float(hist_edges[peak_bin]), 1), round(float(hist_edges[peak_bin + 1]), 1)]
q1_f, q3_f = float(df["fare"].quantile(0.25)), float(df["fare"].quantile(0.75))
iqr_f = q3_f - q1_f
fare_outliers = int((df["fare"] > q3_f + 1.5 * iqr_f).sum())
sex_counts = {str(k): int(v) for k, v in df["sex"].value_counts().items()}
c2_ok = int(hist_counts.sum()) == len(age_clean) and fare_outliers > 10 and sum(sex_counts.values()) == 360
cases.append(
dict(
name="univariate_hist_box_and_bar_stats",
inputs=dict(age_bins=20, iqr_k=1.5),
prerequisites="单变量数值分布(直方图/箱线图)与类别频数(柱状图)基础度量。",
action="验证年龄直方图频数总和等于非空样本数 312、票价存在明显右尾异常值且性别计数和为 360。",
expected=dict(hist_sum_matches_nonnull=True, fare_has_outliers=True, sex_total=360),
actual=dict(
hist_sum_matches_nonnull=(int(hist_counts.sum()) == len(age_clean)),
fare_has_outliers=(fare_outliers > 10),
sex_total=sum(sex_counts.values()),
),
measurements=dict(
age_nonnull=len(age_clean),
age_peak_bin_range=peak_range,
fare_iqr_upper_fence=round(q3_f + 1.5 * iqr_f, 2),
fare_outlier_count=fare_outliers,
sex_counts=sex_counts,
),
passed=c2_ok,
)
)
# 3. Bivariate analysis: pclass vs fare medians, sex vs age medians, sex x survived crosstab, pclass x survived counts
fare_by_pclass = {int(k): round(float(v), 2) for k, v in df.groupby("pclass")["fare"].median().items()}
ct_sex_surv = pd.crosstab(df["sex"], df["survived"], normalize="index")
row_sums_one = bool(np.allclose(ct_sex_surv.sum(axis=1).to_numpy(), 1.0))
female_surv_rate = round(float(ct_sex_surv.loc["female", 1]), 4)
male_surv_rate = round(float(ct_sex_surv.loc["male", 1]), 4)
ct_pclass_surv = pd.crosstab(df["pclass"], df["survived"])
pclass1_rate = round(float(ct_pclass_surv.loc[1, 1] / ct_pclass_surv.loc[1].sum()), 4)
pclass3_rate = round(float(ct_pclass_surv.loc[3, 1] / ct_pclass_surv.loc[3].sum()), 4)
c3_ok = (
fare_by_pclass[1] > fare_by_pclass[2] > fare_by_pclass[3]
and row_sums_one
and female_surv_rate > male_surv_rate + 0.2
and pclass1_rate > pclass3_rate + 0.2
)
cases.append(
dict(
name="bivariate_grouped_violin_and_crosstab",
inputs=dict(groups=["pclass", "sex"], normalize="index"),
prerequisites="双变量分析:类别-数值分组箱线/小提琴统计与类别-类别归一化交叉表。",
action="核验一等舱票价中位数 > 二等 > 三等,交叉表各行概率和为 1,女性与高等舱生存比例显著更高。",
expected=dict(
fare_monotone_by_pclass=True,
crosstab_rows_sum_to_1=True,
female_higher_survival=True,
class1_higher_survival=True,
),
actual=dict(
fare_monotone_by_pclass=(fare_by_pclass[1] > fare_by_pclass[2] > fare_by_pclass[3]),
crosstab_rows_sum_to_1=row_sums_one,
female_higher_survival=(female_surv_rate > male_surv_rate + 0.2),
class1_higher_survival=(pclass1_rate > pclass3_rate + 0.2),
),
measurements=dict(
median_fare_by_pclass=fare_by_pclass,
female_survival_rate=female_surv_rate,
male_survival_rate=male_surv_rate,
pclass1_survival_rate=pclass1_rate,
pclass3_survival_rate=pclass3_rate,
),
passed=c3_ok,
)
)
# 4. Multivariate correlation matrix & age-fare-parch pairwise statistics
num_cols = ["survived", "pclass", "age", "sibsp", "parch", "fare"]
corr = df[num_cols].corr()
r_pclass_fare = round(float(corr.loc["pclass", "fare"]), 4)
r_age_fare = round(float(corr.loc["age", "fare"]), 4)
r_pclass_surv = round(float(corr.loc["pclass", "survived"]), 4)
corr_valid = bool(np.allclose(np.diag(corr.to_numpy()), 1.0) and np.allclose(corr.to_numpy(), corr.to_numpy().T))
c4_ok = corr_valid and r_pclass_fare < -0.50 and r_pclass_surv < -0.25
cases.append(
dict(
name="multivariate_correlation_and_pairwise_stats",
inputs=dict(numeric_columns=num_cols),
prerequisites="多变量相关性矩阵与散点分组统计分析。",
action="计算 6x6 数值相关矩阵,验证 pclass 与 fare 呈强负相关(r<-0.50),且矩阵对称对角为 1。",
expected=dict(matrix_valid=True, pclass_fare_strong_negative=True, pclass_survived_negative=True),
actual=dict(
matrix_valid=corr_valid,
pclass_fare_strong_negative=(r_pclass_fare < -0.50),
pclass_survived_negative=(r_pclass_surv < -0.25),
),
measurements=dict(
corr_pclass_fare=r_pclass_fare,
corr_age_fare=r_age_fare,
corr_pclass_survived=r_pclass_surv,
survived_fare_mean=round(float(df.loc[df["survived"] == 1, "fare"].mean()), 2),
not_survived_fare_mean=round(float(df.loc[df["survived"] == 0, "fare"].mean()), 2),
),
passed=c4_ok,
)
)
# 5. Pure Matplotlib publication-grade PNG charts (no seaborn dependency)
mpl_ver = None
if fig_dir is not None:
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
plt.rcParams["font.sans-serif"] = ["Microsoft YaHei", "SimHei", "DejaVu Sans"]
plt.rcParams["axes.unicode_minus"] = False
fig_dir.mkdir(parents=True, exist_ok=True)
mpl_ver = matplotlib.__version__
# Chart 1: 2x2 Univariate & Bivariate EDA dashboard
fig1, axes = plt.subplots(2, 2, figsize=(10.2, 7.2), dpi=140)
# (a) Age histogram
axes[0, 0].hist(age_clean, bins=20, color="#2b6cb0", edgecolor="white", alpha=0.85)
axes[0, 0].axvline(float(df["age"].median()), color="#c53030", linestyle="--", linewidth=1.6,
label=f"中位数 {df['age'].median():.1f}")
axes[0, 0].set_title("单变量:年龄分布直方图(n=312 非空)", fontsize=10.5)
axes[0, 0].set_xlabel("年龄")
axes[0, 0].set_ylabel("频数")
axes[0, 0].grid(True, axis="y", alpha=0.3)
axes[0, 0].legend(fontsize=8.5)
# (b) Grouped boxplot: fare by pclass
fare_groups = [df.loc[df["pclass"] == c, "fare"].to_numpy() for c in [1, 2, 3]]
bp = axes[0, 1].boxplot(fare_groups, tick_labels=["1 等舱", "2 等舱", "3 等舱"], patch_artist=True)
for patch, color in zip(bp["boxes"], ["#63b3ed", "#9ae6b4", "#fbd38d"]):
patch.set_facecolor(color)
axes[0, 1].set_title("双变量:不同舱位票价分组箱线图", fontsize=10.5)
axes[0, 1].set_ylabel("票价")
axes[0, 1].grid(True, axis="y", alpha=0.3)
# (c) Violin plot: age by sex (pure matplotlib)
age_f = df.loc[df["sex"] == "female", "age"].dropna().to_numpy()
age_m = df.loc[df["sex"] == "male", "age"].dropna().to_numpy()
vp = axes[1, 0].violinplot([age_f, age_m], positions=[1, 2], showmedians=True, showextrema=True)
for body, color in zip(vp["bodies"], ["#f687b3", "#63b3ed"]):
body.set_facecolor(color)
body.set_alpha(0.7)
axes[1, 0].set_xticks([1, 2], ["女性", "男性"])
axes[1, 0].set_title("双变量:不同性别年龄小提琴图", fontsize=10.5)
axes[1, 0].set_ylabel("年龄")
axes[1, 0].grid(True, axis="y", alpha=0.3)
# (d) Stacked bar: survival proportion by sex
sex_order = ["female", "male"]
sex_labels = ["女性", "男性"]
p0 = [float(ct_sex_surv.loc[s, 0]) for s in sex_order]
p1 = [float(ct_sex_surv.loc[s, 1]) for s in sex_order]
x_pos = np.arange(2)
axes[1, 1].bar(x_pos, p0, width=0.5, color="#e57373", label="未幸存")
axes[1, 1].bar(x_pos, p1, width=0.5, bottom=p0, color="#68d391", label="幸存")
for i in range(2):
axes[1, 1].text(x_pos[i], p0[i] + p1[i] / 2, f"{p1[i]:.1%}", ha="center", va="center", fontsize=9, fontweight="bold")
axes[1, 1].set_xticks(x_pos, sex_labels)
axes[1, 1].set_ylim(0, 1.24)
axes[1, 1].set_title("双变量:性别与幸存比例堆叠柱状图", fontsize=10.5)
axes[1, 1].set_ylabel("比例")
axes[1, 1].legend(fontsize=8.5, loc="upper center", ncol=2, frameon=True)
axes[1, 1].grid(True, axis="y", alpha=0.3)
fig1.suptitle("蓝色天空网 · 自有合成乘客队列单/双变量探索图(n=360)", fontsize=12, y=0.99)
fig1.tight_layout(rect=(0, 0, 1, 0.96))
p_out1 = fig_dir / "eda-univariate-bivariate.png"
fig1.savefig(p_out1)
plt.close(fig1)
figures["eda-univariate-bivariate.png"] = sha(p_out1)
# Chart 2: 1x2 Multivariate scatter (hue+marker) + annotated correlation heatmap
fig2, ax2 = plt.subplots(1, 2, figsize=(10.4, 4.4), dpi=140)
valid_af = df.dropna(subset=["age", "fare"])
for label, marker, color, name in [(0, "o", "#3182ce", "未幸存"), (1, "^", "#dd6b20", "幸存")]:
sub = valid_af[valid_af["survived"] == label]
ax2[0].scatter(sub["age"], sub["fare"], c=color, marker=marker, alpha=0.65, s=28, label=name)
ax2[0].set_title("多变量:年龄 vs 票价(按幸存状态着色/标记)", fontsize=10)
ax2[0].set_xlabel("年龄")
ax2[0].set_ylabel("票价")
ax2[0].grid(True, alpha=0.3)
ax2[0].legend(fontsize=8.5)
mat = corr.to_numpy()
im = ax2[1].imshow(mat, cmap="coolwarm", vmin=-1.0, vmax=1.0, aspect="equal")
ax2[1].set_xticks(range(len(num_cols)), num_cols, rotation=35, ha="right", fontsize=8.5)
ax2[1].set_yticks(range(len(num_cols)), num_cols, fontsize=8.5)
for i in range(len(num_cols)):
for j in range(len(num_cols)):
val = mat[i, j]
txt_col = "white" if abs(val) > 0.55 else "#1a202c"
ax2[1].text(j, i, f"{val:.2f}", ha="center", va="center", color=txt_col, fontsize=8)
fig2.colorbar(im, ax=ax2[1], fraction=0.046, pad=0.04)
ax2[1].set_title("多变量:数值特征 Pearson 相关矩阵热力图", fontsize=10)
fig2.suptitle("蓝色天空网 · 自有合成乘客队列多变量关系与相关性热力图(n=360)", fontsize=11.5, y=0.99)
fig2.tight_layout(rect=(0, 0, 1, 0.94))
p_out2 = fig_dir / "eda-multivariate-heatmap.png"
fig2.savefig(p_out2)
plt.close(fig2)
figures["eda-multivariate-heatmap.png"] = sha(p_out2)
cases.append(
dict(
name="observed_visualization_panels_plot",
inputs=dict(charts=["eda-univariate-bivariate.png", "eda-multivariate-heatmap.png"], n=360),
prerequisites="纯 Matplotlib(Agg 后端 + Microsoft YaHei 字体)离线绘制 6 张核心探索统计图。",
action="输出单/双变量 4 合 1 图与多变量散点+热力图,验证所有图表文件按预期产出。",
expected=dict(chart_count=2),
actual=dict(chart_count=2 if fig_dir is None else len(figures)),
measurements=dict(
figures_generated=sorted(figures.keys()),
matplotlib_version=mpl_ver,
),
passed=(True if fig_dir is None else len(figures) == 2),
)
)
payload = dict(
version=platform.python_version(),
system=platform.system(),
pandas=pd.__version__,
cases=cases,
)
if mpl_ver:
payload["matplotlib"] = mpl_ver
payload["figures"] = figures
print(json.dumps(payload, ensure_ascii=False))
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--figures", type=Path, default=None)
args = parser.parse_args()
run_cases(args.figures)
本例需在 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-visualizations-lab/explore-data-visualizations.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-data-visualizations.py,或下载右侧课程工程包。 - 确认本地已准备 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。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a461.zip
课程关联工程包(登记关联58章) · 含当前章节或实例 · mbskycom202612a449.zip