"""Offline verification lab for ML Data Bias: selection/temporal/survivorship/labeling bias, fairness audit, resampling & SMOTE."""
import json
import platform
import numpy as np
import pandas as pd
from scipy.stats import chisquare
from sklearn.datasets import make_classification
from sklearn.ensemble import RandomForestClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score, confusion_matrix, f1_score, precision_score, recall_score
from sklearn.model_selection import train_test_split
from sklearn.neighbors import NearestNeighbors
from sklearn.utils import resample
def smote_oversample(X_train: np.ndarray, y_train: np.ndarray, k_neighbors: int = 5, seed: int = 42):
"""Self-contained deterministic k-NN SMOTE minority oversampling (training split only)."""
rng = np.random.default_rng(seed)
X_maj = X_train[y_train == 0]
X_min = X_train[y_train == 1]
n_needed = len(X_maj) - len(X_min)
if n_needed <= 0:
return X_train.copy(), y_train.copy()
nn = NearestNeighbors(n_neighbors=min(k_neighbors + 1, len(X_min))).fit(X_min)
_, indices = nn.kneighbors(X_min)
neighbors = indices[:, 1:] # exclude self
base_idx = rng.integers(0, len(X_min), size=n_needed)
nbr_pick = rng.integers(0, neighbors.shape[1], size=n_needed)
lam = rng.uniform(0.0, 1.0, size=(n_needed, 1))
synth = X_min[base_idx] + lam * (X_min[neighbors[base_idx, nbr_pick]] - X_min[base_idx])
X_bal = np.vstack([X_train, synth])
y_bal = np.hstack([y_train, np.ones(n_needed, dtype=y_train.dtype)])
return X_bal, y_bal
def run_cases():
cases = []
# 1. Selection bias (1D 90/10), temporal bias & survivorship bias
np.random.seed(42)
n_samples = 1000
X_real = np.random.uniform(-5, 5, n_samples).reshape(-1, 1)
y_real = (X_real.flatten() > 0).astype(int)
mask_pos = X_real.flatten() > 0
mask_neg = X_real.flatten() <= 0
X_pos, y_pos = X_real[mask_pos], y_real[mask_pos]
X_neg, y_neg = X_real[mask_neg], y_real[mask_neg]
neg_idx = np.random.choice(len(X_neg), int(0.1 * len(X_pos)), replace=False)
X_biased = np.vstack([X_pos, X_neg[neg_idx]])
y_biased = np.hstack([y_pos, y_neg[neg_idx]])
X_tr, _, y_tr, _ = train_test_split(X_biased, y_biased, test_size=0.2, random_state=42)
lr = LogisticRegression().fit(X_tr, y_tr)
train_acc = round(float(accuracy_score(y_tr, lr.predict(X_tr))), 4)
real_acc = round(float(accuracy_score(y_real, lr.predict(X_real))), 4)
neg_recall = round(float(recall_score(y_real, lr.predict(X_real), pos_label=0)), 4)
boundary = round(float(-lr.intercept_[0] / lr.coef_[0, 0]), 4)
# Temporal bias: 2010 baseline threshold vs shifted 2023 behavior
rng = np.random.default_rng(101)
X_2010 = rng.normal(0.0, 1.0, (500, 2))
y_2010 = (X_2010[:, 0] - 0.5 * X_2010[:, 1] > 0.0).astype(int)
X_2023 = rng.normal(0.0, 1.0, (500, 2))
y_2023 = (0.2 * X_2023[:, 0] + 1.2 * X_2023[:, 1] > 0.0).astype(int)
lr_time = LogisticRegression().fit(X_2010, y_2010)
acc_2010 = round(float(accuracy_score(y_2010, lr_time.predict(X_2010))), 4)
acc_2023 = round(float(accuracy_score(y_2023, lr_time.predict(X_2023))), 4)
# Survivorship bias: analyzing only surviving companies (revenue > 80) overestimates true mean return
all_returns = rng.normal(12.0, 25.0, 1000)
survivors = all_returns[all_returns > 20.0]
true_mean_ret = round(float(np.mean(all_returns)), 2)
surv_mean_ret = round(float(np.mean(survivors)), 2)
c1_ok = (
train_acc > real_acc
and boundary < -0.2
and acc_2010 > acc_2023 + 0.25
and surv_mean_ret > true_mean_ret + 20.0
)
cases.append(dict(
name="selection_temporal_survivorship_bias",
inputs=dict(n_real=1000, biased_samples=len(X_biased)),
prerequisites="复现 90%正/10%负一维采样偏差、2010→2023 时间偏差与仅观测盈利企业的幸存者偏差。",
action="验证采样偏差使逻辑回归决策边界左移且真实世界精度低于训练集、时间偏差导致跨期精度大跌、幸存者筛选高估平均回报。",
expected=dict(selection_shifted_boundary=True, temporal_drop=True, survivorship_overestimated=True),
actual=dict(
selection_shifted_boundary=(train_acc > real_acc and boundary < -0.2),
temporal_drop=(acc_2010 > acc_2023 + 0.25),
survivorship_overestimated=(surv_mean_ret > true_mean_ret + 20.0),
),
measurements=dict(
train_acc=train_acc, real_acc=real_acc, neg_class_recall=neg_recall,
decision_boundary=boundary, acc_2010=acc_2010, acc_2023=acc_2023,
true_mean_return=true_mean_ret, survivor_mean_return=surv_mean_ret,
),
passed=c1_ok,
))
# 2. Annotation / confirmation bias on sentiment texts
df_ann = pd.DataFrame({
"text": [
"这个产品真的很棒,我非常喜欢!",
"不太确定这个好不好用",
"绝对不要买这个垃圾产品",
"还行吧,一般般",
"超级推荐,物超所值",
],
"biased_label": [1, 0, 0, 0, 1],
"true_label": [1.0, 0.5, 0.0, 0.5, 1.0],
})
neutral_mask = df_ann["true_label"] == 0.5
neutral_forced_neg = int((df_ann.loc[neutral_mask, "biased_label"] == 0).sum())
biased_mean = round(float(df_ann["biased_label"].mean()), 4)
true_mean = round(float(df_ann["true_label"].mean()), 4)
c2_ok = len(df_ann) == 5 and neutral_forced_neg == 2 and biased_mean == 0.4 and true_mean == 0.6
cases.append(dict(
name="annotation_confirmation_bias",
inputs=dict(rows=5, neutral_rows=2),
prerequisites="对比包含正面、中性与负面评论的 5 条文本在二元偏见标注与连续真实情感分下的差异。",
action="验证全部 2 条中性评论被强行压成负面 0,导致整体情感均值由 0.6 失真降至 0.4。",
expected=dict(neutral_forced_negative=2, biased_mean=0.4, true_mean=0.6),
actual=dict(neutral_forced_negative=neutral_forced_neg, biased_mean=biased_mean, true_mean=true_mean),
passed=c2_ok,
))
# 3. Subgroup distribution audit & fairness metrics (Demographic Parity + Equal Opportunity post-processing)
pop_pct = np.array([40, 30, 20, 10], dtype=float)
data_pct = np.array([70, 20, 8, 2], dtype=float)
n_audit = 1000
chi2_stat, chi2_p = chisquare(f_obs=data_pct * (n_audit / 100.0), f_exp=pop_pct * (n_audit / 100.0))
rep_ratios = [round(float(d / p), 4) for d, p in zip(data_pct, pop_pct)]
# Fairness gap on biased hiring model vs group-specific threshold post-processing
rng_f = np.random.default_rng(77)
n_g = 600
# Group 0 (majority in historical data) and Group 1 (underrepresented & score-shifted measurement bias)
s0 = rng_f.normal(0.0, 1.0, n_g)
y0 = (s0 > 0.0).astype(int)
s1 = rng_f.normal(0.0, 1.0, n_g)
y1 = (s1 > 0.0).astype(int)
# Observed score for group 1 has systematic -0.7 measurement penalty
obs0 = s0 + rng_f.normal(0.0, 0.3, n_g)
obs1 = s1 - 0.7 + rng_f.normal(0.0, 0.3, n_g)
clf_hire = LogisticRegression().fit(
np.concatenate([obs0[:450], obs1[:50]]).reshape(-1, 1),
np.concatenate([y0[:450], y1[:50]]),
)
p0 = clf_hire.predict_proba(obs0[450:].reshape(-1, 1))[:, 1]
p1 = clf_hire.predict_proba(obs1[450:].reshape(-1, 1))[:, 1]
tpr0_before = round(float(recall_score(y0[450:], (p0 >= 0.5).astype(int))), 4)
tpr1_before = round(float(recall_score(y1[450:], (p1 >= 0.5).astype(int))), 4)
dp_gap_before = round(abs(float(np.mean(p0 >= 0.5) - np.mean(p1 >= 0.5))), 4)
eo_gap_before = round(abs(tpr0_before - tpr1_before), 4)
# Post-processing: calibrate threshold on group 1 to equalize positive selection rate / opportunity
thr1 = float(np.quantile(p1, 1.0 - float(np.mean(p0 >= 0.5))))
tpr1_after = round(float(recall_score(y1[450:], (p1 >= thr1).astype(int))), 4)
dp_gap_after = round(abs(float(np.mean(p0 >= 0.5) - np.mean(p1 >= thr1))), 4)
eo_gap_after = round(abs(tpr0_before - tpr1_after), 4)
c3_ok = (
rep_ratios == [1.75, 0.6667, 0.4, 0.2]
and float(chi2_p) < 1e-6
and eo_gap_before >= 0.15
and eo_gap_after < 0.08
)
cases.append(dict(
name="subgroup_audit_and_fairness_metrics",
inputs=dict(pop_pct=[40, 30, 20, 10], data_pct=[70, 20, 8, 2]),
prerequisites="对四群体占比执行卡方拟合优度检验,并在含测量偏差的招聘评分模型上计算人口统计学均等差与机会均等(TPR)差。",
action="验证群体 A 被 1.75 倍过度代表、群体 D 仅 0.20 倍代表(p<1e-6),且分组阈值后处理将机会均等差距显著压低。",
expected=dict(rep_ratios=[1.75, 0.6667, 0.4, 0.2], chi2_significant=True, postproc_reduced_eo_gap=True),
actual=dict(
rep_ratios=rep_ratios,
chi2_significant=(float(chi2_p) < 1e-6),
postproc_reduced_eo_gap=(eo_gap_before >= 0.15 and eo_gap_after < 0.08),
),
measurements=dict(
chi2_stat=round(float(chi2_stat), 2),
tpr0_before=tpr0_before, tpr1_before=tpr1_before,
dp_gap_before=dp_gap_before, eo_gap_before=eo_gap_before,
tpr1_after=tpr1_after, dp_gap_after=dp_gap_after, eo_gap_after=eo_gap_after,
),
passed=c3_ok,
))
# 4. Random oversampling via sklearn.utils.resample (900/100 -> 900/900)
np.random.seed(42)
X_maj = np.random.normal(0, 1, 900).reshape(-1, 1)
y_maj = np.zeros(900, dtype=int)
X_min = np.random.normal(2, 1, 100).reshape(-1, 1)
y_min = np.ones(100, dtype=int)
X_min_up, y_min_up = resample(X_min, y_min, replace=True, n_samples=len(X_maj), random_state=42)
y_bal = np.hstack([y_maj, y_min_up])
before_counts = [int(len(y_maj)), int(len(y_min))]
after_counts = [int(np.sum(y_bal == 0)), int(np.sum(y_bal == 1))]
c4_ok = before_counts == [900, 100] and after_counts == [900, 900]
cases.append(dict(
name="random_oversampling_balance",
inputs=dict(majority=900, minority=100, replace=True),
prerequisites="使用 sklearn.utils.resample 对 900:100 不平衡样本做有放回少数类上采样。",
action="验证重采样后多数类与少数类样本数精确平衡为 [900, 900]。",
expected=dict(before=[900, 100], after=[900, 900]),
actual=dict(before=before_counts, after=after_counts),
passed=c4_ok,
))
# 5. Full imbalanced workflow with stratified split + training-only SMOTE + RandomForest
X_clf, y_clf = make_classification(
n_samples=2000, n_features=10, n_informative=8, n_redundant=2,
n_clusters_per_class=1, weights=[0.9, 0.1], flip_y=0, random_state=42,
)
X_tr5, X_te5, y_tr5, y_te5 = train_test_split(
X_clf, y_clf, test_size=0.3, random_state=42, stratify=y_clf,
)
tr_before = np.bincount(y_tr5).tolist()
te_counts = np.bincount(y_te5).tolist()
X_tr_sm, y_tr_sm = smote_oversample(X_tr5, y_tr5, k_neighbors=5, seed=42)
tr_after = np.bincount(y_tr_sm).tolist()
rf_imb = RandomForestClassifier(n_estimators=200, random_state=42).fit(X_tr5, y_tr5)
rf_bal = RandomForestClassifier(n_estimators=200, random_state=42).fit(X_tr_sm, y_tr_sm)
pred_imb = rf_imb.predict(X_te5)
pred_bal = rf_bal.predict(X_te5)
imb_acc = round(float(accuracy_score(y_te5, pred_imb)), 4)
imb_rec = round(float(recall_score(y_te5, pred_imb)), 4)
imb_prec = round(float(precision_score(y_te5, pred_imb)), 4)
imb_f1 = round(float(f1_score(y_te5, pred_imb)), 4)
bal_acc = round(float(accuracy_score(y_te5, pred_bal)), 4)
bal_rec = round(float(recall_score(y_te5, pred_bal)), 4)
bal_prec = round(float(precision_score(y_te5, pred_bal)), 4)
bal_f1 = round(float(f1_score(y_te5, pred_bal)), 4)
cm_imb = confusion_matrix(y_te5, pred_imb).tolist()
cm_bal = confusion_matrix(y_te5, pred_bal).tolist()
c5_ok = (
tr_before == [1260, 140]
and te_counts == [540, 60]
and tr_after == [1260, 1260]
and bal_rec > imb_rec
and bal_f1 >= imb_f1
)
cases.append(dict(
name="smote_imbalanced_pipeline",
inputs=dict(n_samples=2000, weights=[0.9, 0.1], test_size=0.3, n_estimators=200),
prerequisites="在 90:10 不平衡分类数据上分层切分,仅对训练集做 k-NN SMOTE 插值平衡后训练 200 棵树随机森林。",
action="验证分层划分精确保持 [1260,140]/[540,60]、SMOTE 仅扩增训练集至 [1260,1260] 且显著提高测试集少数类召回率与 F1。",
expected=dict(train_before=[1260, 140], test_counts=[540, 60], train_after=[1260, 1260], minority_recall_improved=True),
actual=dict(
train_before=tr_before, test_counts=te_counts, train_after=tr_after,
minority_recall_improved=(bal_rec > imb_rec and bal_f1 >= imb_f1),
),
measurements=dict(
imb_acc=imb_acc, imb_min_prec=imb_prec, imb_min_rec=imb_rec, imb_min_f1=imb_f1, cm_imb=cm_imb,
smote_acc=bal_acc, smote_min_prec=bal_prec, smote_min_rec=bal_rec, smote_min_f1=bal_f1, cm_smote=cm_bal,
),
passed=c5_ok,
))
payload = dict(version=platform.python_version(), system=platform.system(), cases=cases)
print(json.dumps(payload, ensure_ascii=False))
if __name__ == "__main__":
run_cases()
本例需在 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-bias-lab/explore-data-bias.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-data-bias.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章) · 含当前章节或实例 · mbskycom202612a458.zip
课程关联工程包(登记关联58章) · 含当前章节或实例 · mbskycom202612a449.zip