"""Independent offline ML project lifecycle lab: 6 stages + verified fixes for leakage & deploy pitfalls."""
import json
import pickle
import platform
import tempfile
from datetime import datetime, timedelta
from pathlib import Path
import numpy as np
import pandas as pd
from sklearn.calibration import CalibratedClassifierCV
from sklearn.compose import ColumnTransformer
from sklearn.ensemble import RandomForestClassifier
from sklearn.impute import SimpleImputer
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import (
accuracy_score, confusion_matrix, f1_score, mean_absolute_error,
mean_squared_error, precision_score, r2_score, recall_score, roc_auc_score,
)
from sklearn.model_selection import train_test_split
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
from sklearn.svm import SVC
def run_cases():
cases = []
# 1. Stage 1: Problem definition contract
problem_spec = dict(
business_problem="提升商品推荐点击与购买转化率",
technical_problem="依据用户画像、商品与行为特征预测点击/购买概率",
problem_type="推荐系统(分类+排序)",
success_criteria=dict(ctr_lift="15%", cvr_lift="10%", accuracy="80%"),
constraints=dict(latency="<100ms", privacy="合规脱敏", compute="现有 CPU 服务"),
features=dict(
user=["年龄", "性别", "购买历史", "浏览行为"],
item=["类别", "价格", "评分", "库存"],
context=["时间", "设备", "地理位置"],
),
labels=dict(primary="是否点击", secondary="是否购买", auxiliary="停留时间"),
)
c1_ok = (
len(problem_spec["success_criteria"]) == 3
and len(problem_spec["constraints"]) == 3
and sum(len(v) for v in problem_spec["features"].values()) == 11
)
cases.append(dict(
name="problem_definition_schema",
inputs=dict(feature_groups=3, label_levels=3),
prerequisites="电商推荐项目问题定义结构体",
action="核对业务目标、3 项成功指标、3 项工程约束与 11 项特征字段定义完整性。",
expected=dict(criteria_count=3, constraint_count=3, total_features=11),
actual=dict(
criteria_count=len(problem_spec["success_criteria"]),
constraint_count=len(problem_spec["constraints"]),
total_features=sum(len(v) for v in problem_spec["features"].values()),
),
passed=c1_ok,
))
# 2. Stage 2: Deterministic multi-source data collection & inner join
rng = np.random.default_rng(42)
ref_time = datetime(2026, 1, 1, 12, 0, 0)
n_users, n_behaviors, n_products = 1000, 5000, 500
users = pd.DataFrame({
"user_id": np.arange(1, n_users + 1),
"age": rng.integers(18, 65, n_users),
"gender": rng.choice(["男", "女"], n_users),
"city": rng.choice(["北京", "上海", "广州", "深圳"], n_users),
"registration_date": [ref_time - timedelta(days=int(d)) for d in rng.integers(1, 365, n_users)],
})
products = pd.DataFrame({
"product_id": np.arange(1, n_products + 1),
"category": rng.choice(["电子产品", "服装", "食品", "家居", "图书"], n_products),
"price": np.round(rng.uniform(10.0, 1000.0, n_products), 2),
"rating": np.round(rng.uniform(3.0, 5.0, n_products), 2),
"stock": rng.integers(0, 1000, n_products),
})
u_ids = rng.integers(1, n_users + 1, n_behaviors)
p_ids = rng.integers(1, n_products + 1, n_behaviors)
durations = np.round(rng.exponential(30.0, n_behaviors), 2)
# Generate realistic purchase signal driven by duration, product rating & price
p_map_rating = products.set_index("product_id")["rating"].to_dict()
p_map_price = products.set_index("product_id")["price"].to_dict()
b_ratings = np.array([p_map_rating[pid] for pid in p_ids])
b_prices = np.array([p_map_price[pid] for pid in p_ids])
buy_logit = -3.8 + 0.055 * durations + 0.9 * (b_ratings - 4.0) - 0.0015 * b_prices
buy_prob = 1.0 / (1.0 + np.exp(-buy_logit))
purchased = (rng.random(n_behaviors) < buy_prob).astype(int)
behaviors = pd.DataFrame({
"behavior_id": np.arange(1, n_behaviors + 1),
"user_id": u_ids,
"product_id": p_ids,
"duration": durations,
"purchased": purchased,
})
merged = behaviors.merge(users, on="user_id", how="inner").merge(products, on="product_id", how="inner")
merged["price_per_rating"] = merged["price"] / merged["rating"]
c2_ok = users.shape == (1000, 5) and behaviors.shape == (5000, 5) and products.shape == (500, 5) and len(merged) == 5000
cases.append(dict(
name="data_collection_and_merge",
inputs=dict(users=1000, behaviors=5000, products=500),
prerequisites="固定随机种子与参考时间构建用户/行为/商品三张业务表",
action="验证三表形状、零缺失值以及按 user_id 与 product_id 内连接得到 5000 条样本并派生 price_per_rating。",
expected=dict(merged_rows=5000, cities_count=4, missing_values=0),
actual=dict(merged_rows=len(merged), cities_count=int(users["city"].nunique()), missing_values=int(merged.isna().sum().sum())),
measurements=dict(positive_rate=round(float(merged["purchased"].mean()), 4)),
passed=c2_ok,
))
# 3. Stage 3: Leak-free data prep + verify source bug (scaling binary target breaks classifier)
df_prep = merged[["age", "duration", "price", "rating", "price_per_rating", "gender", "city", "category", "purchased"]].copy()
# Inject 50 missing durations & 20 extreme age outliers
df_prep.loc[df_prep.index[:50], "duration"] = np.nan
df_prep.loc[df_prep.index[50:70], "age"] = 135
# Reproduce source defect: scaling target turns binary int into continuous float -> ValueError
scaled_target = StandardScaler().fit_transform(df_prep[["purchased"]]).ravel()
target_bug_caught = False
try:
LogisticRegression().fit(np.zeros((len(scaled_target), 1)), scaled_target)
except ValueError as exc:
target_bug_caught = "continuous" in str(exc).lower()
# Correct order: split 60/20/20 first -> compute IQR bounds & imputer/scaler on train only
X_all = df_prep.drop(columns=["purchased"])
y_all = df_prep["purchased"].astype(int)
X_temp, X_test, y_temp, y_test = train_test_split(X_all, y_all, test_size=0.2, random_state=42, stratify=y_all)
X_train, X_val, y_train, y_val = train_test_split(X_temp, y_temp, test_size=0.25, random_state=42, stratify=y_temp)
q1, q3 = X_train["age"].quantile(0.25), X_train["age"].quantile(0.75)
lo, hi = q1 - 1.5 * (q3 - q1), q3 + 1.5 * (q3 - q1)
outliers_in_train = int(((X_train["age"] < lo) | (X_train["age"] > hi)).sum())
X_train = X_train.copy()
X_val = X_val.copy()
X_test = X_test.copy()
for part in (X_train, X_val, X_test):
part["age"] = part["age"].clip(lo, hi)
num_cols = ["age", "duration", "price", "rating", "price_per_rating"]
cat_cols = ["gender", "city", "category"]
preprocess = ColumnTransformer([
("num", Pipeline([("imp", SimpleImputer(strategy="median")), ("sc", StandardScaler())]), num_cols),
("cat", Pipeline([("imp", SimpleImputer(strategy="most_frequent")), ("ohe", OneHotEncoder(handle_unknown="ignore", sparse_output=False))]), cat_cols),
])
Xt_tr = preprocess.fit_transform(X_train)
c3_ok = (
target_bug_caught
and len(X_train) == 3000 and len(X_val) == 1000 and len(X_test) == 1000
and int(np.isnan(Xt_tr).sum()) == 0
and outliers_in_train > 0
and set(y_train.unique().tolist()) == {0, 1}
)
cases.append(dict(
name="leak_free_data_preparation",
inputs=dict(total=5000, injected_missing=50, injected_age_outliers=20),
prerequisites="先按 60/20/20 分层划分再在训练集拟合缺失填充、IQR 截断与编码缩放",
action="复现原代码标准化目标列触发 ValueError 的缺陷,并验证无泄漏预处理保持标签为 {0,1} 且输出零缺失。",
expected=dict(target_scaling_bug_caught=True, split_sizes=[3000, 1000, 1000], train_nans_after=0),
actual=dict(target_scaling_bug_caught=target_bug_caught, split_sizes=[len(X_train), len(X_val), len(X_test)], train_nans_after=int(np.isnan(Xt_tr).sum())),
measurements=dict(clipped_train_age_outliers=outliers_in_train, transformed_dim=int(Xt_tr.shape[1])),
passed=c3_ok,
))
# 4. Stage 4 & 5: Model training (LR/RF/SVC with probability=True) + Classification & Regression evaluation
candidates = {
"logistic_regression": Pipeline([("prep", preprocess), ("clf", LogisticRegression(max_iter=500, random_state=42))]),
"random_forest": Pipeline([("prep", preprocess), ("clf", RandomForestClassifier(n_estimators=80, max_depth=8, random_state=42))]),
"svc_rbf": Pipeline([("prep", preprocess), ("clf", CalibratedClassifierCV(SVC(random_state=42), ensemble=False, cv=3))]),
}
val_aucs = {}
for name, pipe in candidates.items():
pipe.fit(X_train, y_train)
val_aucs[name] = round(float(roc_auc_score(y_val, pipe.predict_proba(X_val)[:, 1])), 4)
best_name = max(val_aucs, key=val_aucs.get)
best_pipe = candidates[best_name]
y_te_pred = best_pipe.predict(X_test)
y_te_prob = best_pipe.predict_proba(X_test)[:, 1]
clf_metrics = dict(
accuracy=round(float(accuracy_score(y_test, y_te_pred)), 4),
precision=round(float(precision_score(y_test, y_te_pred, zero_division=0)), 4),
recall=round(float(recall_score(y_test, y_te_pred, zero_division=0)), 4),
f1=round(float(f1_score(y_test, y_te_pred, zero_division=0)), 4),
roc_auc=round(float(roc_auc_score(y_test, y_te_prob)), 4),
confusion_matrix=confusion_matrix(y_test, y_te_pred).tolist(),
)
# Regression metric check (MSE/RMSE/MAE/R²)
y_reg_true = np.array([10.0, 20.0, 30.0, 40.0])
y_reg_pred = np.array([11.0, 19.0, 31.0, 39.0])
reg_mse = float(mean_squared_error(y_reg_true, y_reg_pred))
reg_rmse = float(np.sqrt(reg_mse))
reg_mae = float(mean_absolute_error(y_reg_true, y_reg_pred))
reg_r2 = round(float(r2_score(y_reg_true, y_reg_pred)), 4)
c4_ok = clf_metrics["roc_auc"] >= 0.80 and reg_mse == 1.0 and reg_rmse == 1.0 and reg_mae == 1.0 and abs(reg_r2 - 0.992) < 1e-4
cases.append(dict(
name="model_training_and_evaluation",
inputs=dict(models=list(candidates.keys()), selection_metric="val_roc_auc"),
prerequisites="同一 ColumnTransformer 流水线训练逻辑回归、随机森林与开启 probability=True 的 SVC",
action="按验证集 ROC-AUC 择优后在测试集输出分类指标与混淆矩阵,并核对回归 MSE/RMSE/MAE/R²。",
expected=dict(test_auc_ge_080=True, reg_mse=1.0, reg_rmse=1.0, reg_mae=1.0, reg_r2=0.992),
actual=dict(test_auc_ge_080=clf_metrics["roc_auc"] >= 0.80, reg_mse=reg_mse, reg_rmse=reg_rmse, reg_mae=reg_mae, reg_r2=reg_r2),
measurements=dict(val_aucs=val_aucs, best_model=best_name, test_metrics=clf_metrics),
passed=c4_ok,
))
# 5. Stage 6: End-to-end Pipeline persistence & raw-input prediction service (no double scaling!)
raw_batch = X_test.head(5).copy()
with tempfile.TemporaryDirectory() as tmp:
model_file = Path(tmp) / "production_pipeline.pkl"
with model_file.open("wb") as fh:
pickle.dump(best_pipe, fh)
loaded_pipe = pickle.load(model_file.open("rb"))
preds_orig = best_pipe.predict_proba(raw_batch)
preds_loaded = loaded_pipe.predict_proba(raw_batch)
max_diff = float(np.max(np.abs(preds_orig - preds_loaded)))
service_resp = dict(
status="success",
model_name=best_name,
input_rows=len(raw_batch),
predictions=loaded_pipe.predict(raw_batch).tolist(),
positive_probs=[round(float(p), 4) for p in preds_loaded[:, 1]],
)
file_bytes = model_file.stat().st_size
c5_ok = max_diff == 0.0 and service_resp["status"] == "success" and service_resp["input_rows"] == 5
cases.append(dict(
name="pipeline_deploy_save_load_monitor",
inputs=dict(batch_size=5, raw_columns=list(raw_batch.columns)),
prerequisites="将预处理与分类器打包为单一 Pipeline 序列化,推理时直接接收原始未编码表格",
action="保存并重载完整 Pipeline,验证原始 5 条输入预测概率与训练期零误差并生成监控日志结构。",
expected=dict(reload_max_diff=0.0, service_status="success", predictions_len=5),
actual=dict(reload_max_diff=max_diff, service_status=service_resp["status"], predictions_len=len(service_resp["predictions"])),
measurements=dict(pipeline_bytes=file_bytes, sample_probs=service_resp["positive_probs"]),
passed=c5_ok,
))
print(json.dumps(dict(version=platform.python_version(), system=platform.system(), cases=cases), 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-project-lifecycle-lab/explore-project-lifecycle.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-project-lifecycle.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。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联58章) · 含当前章节或实例 · mbskycom202612a449.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a494.zip