"""Offline verification lab for Real-World Costs & Limits of ML Models (labeling, cloud/inference cost, OOD/adversarial fragility, TCO & human-in-loop)."""
import json
import platform
import numpy as np
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score
def estimate_labeling_cost(num_images: int, time_per_image: float, cost_per_hour: float):
total_hours = num_images * time_per_image
total_cost = total_hours * cost_per_hour
return total_hours, total_cost
def estimate_training_cost(training_hours: float, instance_hourly_rate: float, num_trials: int = 1):
return training_hours * instance_hourly_rate * num_trials
def estimate_annual_inference_cost(qps: float, cost_per_million_req: float):
seconds_per_year = 365 * 24 * 3600
total_requests = qps * seconds_per_year
return total_requests, (total_requests / 1_000_000.0) * cost_per_million_req
def trained_classifier_confidence(image: np.ndarray, clarity_threshold: float = 1000.0) -> float:
clarity = float(np.var(image))
return 0.95 if clarity > clarity_threshold else 0.55
def run_cases():
rng = np.random.default_rng(2026)
cases = []
# 1. Data labeling & cleaning effort estimation
hours, label_cost = estimate_labeling_cost(100_000, 0.05, 20.0)
# Typical project schedule where data cleaning consumes 60%-80% of total engineering hours
dev_total_hours = 1000.0
cleaning_hours_range = [round(dev_total_hours * 0.6, 1), round(dev_total_hours * 0.8, 1)]
c1_ok = hours == 5000.0 and label_cost == 100_000.0
cases.append(dict(
name="data_labeling_cost_estimation",
inputs=dict(num_images=100_000, time_per_image_hr=0.05, cost_per_hour=20.0),
prerequisites="按 10 万张图像、单张 3 分钟(0.05 小时)、每小时 20 元核对标注总工时与总费用。",
action="验证标注工时精确为 5,000 小时、标注直接成本为 100,000 元。",
expected=dict(total_hours=5000.0, total_cost=100000.0),
actual=dict(total_hours=hours, total_cost=label_cost),
measurements=dict(cleaning_hours_60_80_pct_of_1000h=cleaning_hours_range),
passed=c1_ok,
))
# 2. Cloud training (hyperparameter search multiplier) vs cumulative high-QPS inference cost
train_single = estimate_training_cost(10.0, 4.0, num_trials=1)
train_20_trials = estimate_training_cost(10.0, 4.0, num_trials=20)
annual_reqs, annual_inf_cost = estimate_annual_inference_cost(qps=200.0, cost_per_million_req=1.5)
# Include quarterly retraining (4x) + baseline serving infra ($1200/mo)
annual_retrain = train_20_trials * 4.0
annual_infra = 1200.0 * 12.0
annual_serving_total = round(annual_inf_cost + annual_retrain + annual_infra, 2)
c2_ok = train_single == 40.0 and train_20_trials == 800.0 and annual_inf_cost > train_20_trials * 10
cases.append(dict(
name="compute_training_and_inference_cost",
inputs=dict(training_hours=10.0, hourly_rate=4.0, num_trials=20, qps=200.0, usd_per_1m_req=1.5),
prerequisites="核对单次云训练、20 组超参数实验以及 200 QPS 全年在线推理与季度再训练的综合算力账单。",
action="验证 20 组实验使训练费由 40 美元放大至 800 美元,且高并发全年推理费用远超一次性训练费。",
expected=dict(single_train_usd=40.0, hpo_20_trials_usd=800.0, inference_exceeds_10x_train=True),
actual=dict(
single_train_usd=train_single,
hpo_20_trials_usd=train_20_trials,
inference_exceeds_10x_train=(annual_inf_cost > train_20_trials * 10),
),
measurements=dict(
annual_requests=int(annual_reqs),
annual_inference_usd=round(annual_inf_cost, 2),
annual_retrain_usd=annual_retrain,
annual_infra_usd=annual_infra,
annual_serving_total_usd=annual_serving_total,
),
passed=c2_ok,
))
# 3. OOD clarity variance bug reproduction + corrected OOD check + adversarial FGSM-like perturbation
clear_img = rng.normal(0.0, 255.0, (100, 100))
# Source code bug: std=50 gives var ≈ 2500 > 1000, so it STILL returns 0.95!
source_blurry_img = rng.normal(128.0, 50.0, (100, 100))
fixed_blurry_img = rng.normal(128.0, 20.0, (100, 100))
clear_var = round(float(np.var(clear_img)), 1)
src_blur_var = round(float(np.var(source_blurry_img)), 1)
fix_blur_var = round(float(np.var(fixed_blurry_img)), 1)
conf_clear = trained_classifier_confidence(clear_img)
conf_src_blur = trained_classifier_confidence(source_blurry_img)
conf_fix_blur = trained_classifier_confidence(fixed_blurry_img)
# Linear classifier adversarial perturbation (L-inf step eps=0.35 along sign(w))
X_adv_tr = rng.normal(0.0, 1.0, (800, 20))
w_true = np.linspace(0.4, 1.0, 20)
y_adv_tr = (X_adv_tr @ w_true > 0.0).astype(int)
X_adv_te = rng.normal(0.0, 1.0, (300, 20))
y_adv_te = (X_adv_te @ w_true > 0.0).astype(int)
clf_adv = LogisticRegression(random_state=42).fit(X_adv_tr, y_adv_tr)
clean_acc = round(float(accuracy_score(y_adv_te, clf_adv.predict(X_adv_te))), 4)
# Perturb each test sample opposite to its true label direction by tiny eps=0.35
w_sign = np.sign(clf_adv.coef_[0])
direction = np.where(y_adv_te == 1, -1.0, 1.0)[:, None]
X_perturbed = X_adv_te + 0.35 * direction * w_sign[None, :]
adv_acc = round(float(accuracy_score(y_adv_te, clf_adv.predict(X_perturbed))), 4)
c3_ok = (
conf_clear == 0.95
and src_blur_var > 1000.0
and conf_src_blur == 0.95
and fix_blur_var < 1000.0
and conf_fix_blur == 0.55
and clean_acc >= 0.95
and adv_acc <= 0.40
)
cases.append(dict(
name="ood_variance_bug_and_adversarial_fragility",
inputs=dict(threshold=1000.0, clear_std=255.0, src_blur_std=50.0, fixed_blur_std=20.0, adv_eps=0.35),
prerequisites="复现来源模糊图 std=50 方差约 2500>1000 误判高置信度缺陷,验证修正后 std=20 返回 0.55,并实测 20 维分类器对抗扰动脆弱性。",
action="确认来源参数因 50^2=2500>1000 导致模糊图仍输出 0.95、修正 std=20 后降为 0.55,且 ε=0.35 微小对抗扰动使准确率暴跌。",
expected=dict(
clear_conf=0.95, source_blur_bug_conf=0.95, fixed_blur_conf=0.55,
clean_acc_ge_095=True, adversarial_acc_le_040=True,
),
actual=dict(
clear_conf=conf_clear, source_blur_bug_conf=conf_src_blur, fixed_blur_conf=conf_fix_blur,
clean_acc_ge_095=(clean_acc >= 0.95), adversarial_acc_le_040=(adv_acc <= 0.40),
),
measurements=dict(
clear_var=clear_var, source_blur_var=src_blur_var, fixed_blur_var=fix_blur_var,
clean_acc=clean_acc, adversarial_acc=adv_acc,
),
passed=c3_ok,
))
# 4. Cost-Benefit & Human-in-the-Loop selective deferral vs full automation
# Simulate 1,000 production factory inspection items where false alarm costs $500 (line stop)
# and missed defect costs $1,500, while human review costs $15/item.
n_prod = 1000
X_p = rng.normal(0.0, 1.0, (n_prod, 4))
y_p = (X_p[:, 0] + 0.8 * X_p[:, 1] > 0.3).astype(int)
clf_p = LogisticRegression(random_state=42).fit(X_p[:500], y_p[:500])
probs_p = clf_p.predict_proba(X_p[500:])[:, 1]
y_eval = y_p[500:]
# Inject 20% OOD noise on eval items to mimic factory drift
probs_noisy = np.clip(probs_p + rng.normal(0.0, 0.22, size=len(probs_p)), 0.01, 0.99)
auto_preds = (probs_noisy >= 0.5).astype(int)
auto_fp = int(np.sum((auto_preds == 1) & (y_eval == 0)))
auto_fn = int(np.sum((auto_preds == 0) & (y_eval == 1)))
auto_risk_cost = auto_fp * 500 + auto_fn * 1500
# Human-in-the-loop: defer uncertain band [0.25, 0.75] to human (assumed 98% accurate -> negligible miss)
uncertain = (probs_noisy >= 0.25) & (probs_noisy <= 0.75)
deferred_count = int(np.sum(uncertain))
confident_mask = ~uncertain
hitl_fp = int(np.sum((auto_preds[confident_mask] == 1) & (y_eval[confident_mask] == 0)))
hitl_fn = int(np.sum((auto_preds[confident_mask] == 0) & (y_eval[confident_mask] == 1)))
hitl_total_cost = deferred_count * 15 + hitl_fp * 500 + hitl_fn * 1500
# Rule-based vs ML opportunity cost check (1-month rule system vs 3-month ML project)
rule_tco = 15_000.0
ml_tco = 15_000.0 * 3 + 25_000.0 # 3x engineering months + infra/data
c4_ok = hitl_total_cost < auto_risk_cost * 0.5 and rule_tco < ml_tco
cases.append(dict(
name="cost_benefit_and_human_in_loop",
inputs=dict(eval_items=500, fp_cost=500, fn_cost=1500, human_review_cost=15, defer_band=[0.25, 0.75]),
prerequisites="在含产线分布扰动的 500 条检测样本上,对比全自动推理误判损失与低置信区间人工复核(人机协作)总成本。",
action="验证将 [0.25, 0.75] 不确定样本转交人工复核后,误判与复核综合成本低于全自动方案一半,并对比规则系统与 ML 机会成本。",
expected=dict(hitl_saves_over_50pct=True, rule_cheaper_than_ml=True),
actual=dict(
hitl_saves_over_50pct=(hitl_total_cost < auto_risk_cost * 0.5),
rule_cheaper_than_ml=(rule_tco < ml_tco),
),
measurements=dict(
auto_fp=auto_fp, auto_fn=auto_fn, auto_risk_cost=auto_risk_cost,
deferred_count=deferred_count, hitl_fp=hitl_fp, hitl_fn=hitl_fn,
hitl_total_cost=hitl_total_cost,
savings_ratio=round(1.0 - hitl_total_cost / auto_risk_cost, 4),
rule_tco=rule_tco, ml_tco=ml_tco,
),
passed=c4_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-cost-of-models-lab/explore-cost-of-models.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-cost-of-models.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章) · 含当前章节或实例 · mbskycom202612a455.zip