"""Independent offline lab for ML Ch 16: Foundations of Statistics (descriptive, normal, CLT, hypothesis test, confounder)."""
import json
import platform
import numpy as np
import pandas as pd
from scipy import stats
def main():
cases = []
# 1. Central tendency, dispersion & exact variance correction on [30, 35, 40, 45, 200]
salaries = np.array([30.0, 35.0, 40.0, 45.0, 200.0])
s_mean = float(np.mean(salaries))
s_median = float(np.median(salaries))
s_range = float(np.max(salaries) - np.min(salaries))
# True sample variance (ddof=1) MUST center at sample mean (70), NOT median (40)
s_var = float(np.var(salaries, ddof=1))
s_std = float(np.std(salaries, ddof=1))
# Document what median-centered squared deviation actually computes (for correcting source slip)
median_centered_msd = float(np.sum((salaries - s_median) ** 2) / (len(salaries) - 1))
q1, q3 = float(np.percentile(salaries, 25)), float(np.percentile(salaries, 75))
iqr = q3 - q1
upper_fence = q3 + 1.5 * iqr
iqr_outliers = salaries[salaries > upper_fence].tolist()
# Mode verification: unique values have no single mode; repeated shoe sizes have mode=41
shoe_sizes = pd.Series([39, 41, 41, 42, 41, 40])
shoe_mode = int(shoe_sizes.mode().iloc[0])
salary_max_freq = int(pd.Series(salaries).value_counts().max())
c1_ok = bool(
s_mean == 70.0
and s_median == 40.0
and s_range == 170.0
and abs(s_var - 5312.5) < 1e-9
and abs(s_std - float(np.sqrt(5312.5))) < 1e-9
and abs(median_centered_msd - 6437.5) < 1e-9
and iqr_outliers == [200.0]
and salary_max_freq == 1
and shoe_mode == 41
)
cases.append(
dict(
name="central_tendency_dispersion_and_correction",
inputs=dict(salaries=salaries.tolist(), shoe_sizes=shoe_sizes.tolist()),
prerequisites="核对 [30, 35, 40, 45, 200] 的集中趋势、样本方差(ddof=1)、IQR 异常边界与众数。",
action="验证均值=70、中位数=40、极差=170、真实样本方差=5312.5(标准差≈72.8869,纠正来源以中位数40代均值且算错的5875)及200被1.5*IQR标出。",
expected=dict(
mean=70.0,
median=40.0,
sample_var=5312.5,
iqr_outlier=[200.0],
shoe_mode=41,
),
actual=dict(
mean=s_mean,
median=s_median,
sample_var=round(s_var, 4),
iqr_outlier=iqr_outliers,
shoe_mode=shoe_mode,
),
measurements=dict(
sample_std=round(s_std, 4),
population_std=round(float(np.std(salaries, ddof=0)), 4),
median_centered_msd=median_centered_msd,
q1=q1,
q3=q3,
iqr=iqr,
upper_fence=upper_fence,
salary_range=s_range,
),
passed=c1_ok,
)
)
# 2. Basic conditional probability & Normal 68-95-99.7 rule
# Synthetic contingency counts: 100 days, 30 cloudy (B), 24 cloudy & rainy (A and B)
p_b = 30.0 / 100.0
p_a_and_b = 24.0 / 100.0
p_a_given_b = round(p_a_and_b / p_b, 6)
p1 = round(float(stats.norm.cdf(1.0) - stats.norm.cdf(-1.0)), 4)
p2 = round(float(stats.norm.cdf(2.0) - stats.norm.cdf(-2.0)), 4)
p3 = round(float(stats.norm.cdf(3.0) - stats.norm.cdf(-3.0)), 4)
c2_ok = p_a_given_b == 0.8 and p1 == 0.6827 and p2 == 0.9545 and p3 == 0.9973
cases.append(
dict(
name="probability_and_normal_68_95_997",
inputs=dict(p_b=0.3, p_a_and_b=0.24, sigma_bands=[1, 2, 3]),
prerequisites="使用 scipy.stats.norm 精确核对标准正态分布 ±1σ/±2σ/±3σ 区间概率与条件概率定义。",
action="计算 P(A|B)=P(A∩B)/P(B) 与正态分布三档置信覆盖率。",
expected=dict(p_a_given_b=0.8, band_1sigma=0.6827, band_2sigma=0.9545, band_3sigma=0.9973),
actual=dict(p_a_given_b=p_a_given_b, band_1sigma=p1, band_2sigma=p2, band_3sigma=p3),
measurements=dict(
cdf_at_0=float(stats.norm.cdf(0.0)),
symmetric_check=round(float(stats.norm.pdf(1.5) - stats.norm.pdf(-1.5)), 12),
),
passed=c2_ok,
)
)
# 3. Central Limit Theorem on right-skewed Exponential(scale=2.0)
rng = np.random.default_rng(202616)
pop_scale = 2.0
raw_sample = rng.exponential(scale=pop_scale, size=5000)
raw_skew = float(stats.skew(raw_sample))
n_each = 50
sample_means = rng.exponential(scale=pop_scale, size=(2000, n_each)).mean(axis=1)
means_avg = float(sample_means.mean())
means_std = float(sample_means.std(ddof=1))
theoretical_se = float(pop_scale / np.sqrt(n_each))
means_skew = float(stats.skew(sample_means))
c3_ok = bool(
raw_skew > 1.5
and abs(means_avg - pop_scale) < 0.05
and abs(means_std - theoretical_se) < 0.03
and abs(means_skew) < 0.35
)
cases.append(
dict(
name="central_limit_theorem_convergence",
inputs=dict(population="Exponential(scale=2.0)", trials=2000, sample_size=n_each, seed=202616),
prerequisites="从强右偏指数分布(理论均值=2、标准差=2、偏度=2)重复抽取 2000 组样本量 n=50 的均值。",
action="验证样本均值趋近总体均值 2.0、标准误贴近 σ/√n≈0.2828,且分布偏度大幅收敛近对称。",
expected=dict(
raw_highly_skewed=True,
mean_close_to_2=True,
std_close_to_se=True,
skew_near_zero=True,
),
actual=dict(
raw_highly_skewed=bool(raw_skew > 1.5),
mean_close_to_2=bool(abs(means_avg - pop_scale) < 0.05),
std_close_to_se=bool(abs(means_std - theoretical_se) < 0.03),
skew_near_zero=bool(abs(means_skew) < 0.35),
),
measurements=dict(
raw_skew=round(raw_skew, 4),
sample_means_avg=round(means_avg, 4),
sample_means_std=round(means_std, 4),
theoretical_se=round(theoretical_se, 4),
sample_means_skew=round(means_skew, 4),
),
passed=c3_ok,
)
)
# 4. Welch two-sample t-test (reject H0 vs fail to reject H0) & confounder correlation vs causation
grp_ctrl = rng.normal(loc=100.0, scale=12.0, size=60)
grp_eff = rng.normal(loc=110.0, scale=15.0, size=60)
grp_null = rng.normal(loc=100.0, scale=14.0, size=60)
t_eff, p_eff = stats.ttest_ind(grp_eff, grp_ctrl, equal_var=False)
t_null, p_null = stats.ttest_ind(grp_null, grp_ctrl, equal_var=False)
# Confounder simulation: temperature drives both ice cream sales and swimming/drowning count
temp = rng.normal(28.0, 6.0, size=200)
ice_cream = 12.0 * temp + rng.normal(0.0, 20.0, size=200)
drowning = 0.8 * temp + rng.normal(0.0, 2.0, size=200)
raw_r = float(np.corrcoef(ice_cream, drowning)[0, 1])
# Partial correlation removing linear effect of temperature from both variables
res_ice = ice_cream - np.polyval(np.polyfit(temp, ice_cream, 1), temp)
res_drown = drowning - np.polyval(np.polyfit(temp, drowning, 1), temp)
partial_r = float(np.corrcoef(res_ice, res_drown)[0, 1])
c4_ok = float(p_eff) < 0.05 and float(p_null) >= 0.05 and raw_r > 0.80 and abs(partial_r) < 0.15
cases.append(
dict(
name="hypothesis_testing_and_confounder_correlation",
inputs=dict(alpha=0.05, group_n=60, confounder_n=200, equal_var=False),
prerequisites="使用不等方差 Welch t 检验区分拒绝 H0 与未拒绝 H0,并用气温混杂变量模拟伪相关。",
action="验证真实差异组 p<0.05(拒绝 H0)、同均值组 p>=0.05(未拒绝 H0,非证明 H0);控制气温后冰淇淋与溺水偏相关趋近 0。",
expected=dict(
effect_rejects_h0=True,
null_fails_to_reject_h0=True,
raw_confounded_corr_gt_08=True,
partial_corr_near_zero=True,
),
actual=dict(
effect_rejects_h0=(float(p_eff) < 0.05),
null_fails_to_reject_h0=(float(p_null) >= 0.05),
raw_confounded_corr_gt_08=(raw_r > 0.80),
partial_corr_near_zero=(abs(partial_r) < 0.15),
),
measurements=dict(
effect_t=round(float(t_eff), 4),
effect_p=round(float(p_eff), 6),
null_t=round(float(t_null), 4),
null_p=round(float(p_null), 4),
raw_ice_drown_r=round(raw_r, 4),
partial_ice_drown_r=round(partial_r, 4),
),
passed=c4_ok,
)
)
# 5. Owned synthetic restaurant bill/tip cohort (offline substitute for seaborn tips)
n_tips = 244
sex_t = rng.choice(["Male", "Female"], size=n_tips, p=[0.64, 0.36])
smoker_t = rng.choice(["No", "Yes"], size=n_tips, p=[0.62, 0.38])
time_t = rng.choice(["Dinner", "Lunch"], size=n_tips, p=[0.72, 0.28])
total_bill = np.clip(
rng.gamma(shape=4.5, scale=4.2, size=n_tips) + np.where(smoker_t == "Yes", 2.0, 0.0),
4.0,
52.0,
).round(2)
tip = np.clip(0.11 * total_bill + rng.normal(0.85, 0.85, size=n_tips), 1.0, 10.0).round(2)
tips_df = pd.DataFrame(
{"total_bill": total_bill, "tip": tip, "sex": sex_t, "smoker": smoker_t, "time": time_t}
)
r_bill_tip = round(float(tips_df["tip"].corr(tips_df["total_bill"])), 4)
med_by_sex = {str(k): round(float(v), 2) for k, v in tips_df.groupby("sex")["tip"].median().items()}
mean_by_smoker = {str(k): round(float(v), 2) for k, v in tips_df.groupby("smoker")["total_bill"].mean().items()}
_, p_smoker = stats.ttest_ind(
tips_df.loc[tips_df["smoker"] == "Yes", "total_bill"],
tips_df.loc[tips_df["smoker"] == "No", "total_bill"],
equal_var=False,
)
c5_ok = tips_df.shape == (244, 5) and r_bill_tip > 0.50 and float(tips_df["total_bill"].mean()) > 10.0
cases.append(
dict(
name="tips_cohort_exploratory_statistics",
inputs=dict(rows=244, cols=5, seed=202616),
prerequisites="使用固定种子 244 行自有合成餐饮账单队列完成离线描述统计、相关性与组间检验。",
action="核对账单均值/中位数/标准差、小费与账单正相关及按性别/吸烟分组统计量。",
expected=dict(shape=[244, 5], positive_bill_tip_corr=True, realistic_bill_mean=True),
actual=dict(
shape=list(tips_df.shape),
positive_bill_tip_corr=(r_bill_tip > 0.50),
realistic_bill_mean=(float(tips_df["total_bill"].mean()) > 10.0),
),
measurements=dict(
total_bill_mean=round(float(tips_df["total_bill"].mean()), 2),
total_bill_median=round(float(tips_df["total_bill"].median()), 2),
total_bill_std=round(float(tips_df["total_bill"].std(ddof=1)), 2),
corr_bill_tip=r_bill_tip,
median_tip_by_sex=med_by_sex,
mean_bill_by_smoker=mean_by_smoker,
smoker_bill_welch_p=round(float(p_smoker), 4),
),
passed=c5_ok,
)
)
payload = dict(
version=platform.python_version(),
system=platform.system(),
scipy=stats.__name__,
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-foundations-of-statistics-lab/explore-foundations-of-statistics.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-foundations-of-statistics.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章) · 含当前章节或实例 · mbskycom202612a471.zip
课程关联工程包(登记关联58章) · 含当前章节或实例 · mbskycom202612a449.zip