"""Independent offline ML applications lab: CV NMS, NLP intent/sentiment, CF recommender, fraud RF & anomaly IF."""
import json
import platform
import numpy as np
from sklearn.ensemble import IsolationForest, RandomForestClassifier
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import f1_score, precision_score, recall_score
from sklearn.model_selection import train_test_split
def compute_iou(box: np.ndarray, others: np.ndarray) -> np.ndarray:
x1 = np.maximum(box[0], others[:, 0])
y1 = np.maximum(box[1], others[:, 1])
x2 = np.minimum(box[2], others[:, 2])
y2 = np.minimum(box[3], others[:, 3])
inter = np.maximum(0.0, x2 - x1) * np.maximum(0.0, y2 - y1)
area_a = (box[2] - box[0]) * (box[3] - box[1])
area_b = (others[:, 2] - others[:, 0]) * (others[:, 3] - others[:, 1])
return inter / np.maximum(area_a + area_b - inter, 1e-9)
def run_cases():
cases = []
# 1. CV object detection post-processing (confidence threshold + IoU Non-Maximum Suppression)
raw_boxes = np.array([
[10, 20, 110, 120], # car high conf
[14, 24, 112, 122], # duplicate overlapping car
[200, 50, 260, 160], # pedestrian
[300, 10, 340, 60], # low confidence noise
], dtype=float)
raw_scores = np.array([0.92, 0.78, 0.86, 0.25])
raw_classes = ["car", "car", "pedestrian", "sign"]
# Step 1: filter low confidence (<0.5)
keep_conf = raw_scores >= 0.5
boxes_f, scores_f = raw_boxes[keep_conf], raw_scores[keep_conf]
classes_f = [c for c, ok in zip(raw_classes, keep_conf) if ok]
# Step 2: greedy NMS (IoU > 0.5 suppresses duplicate)
order = np.argsort(-scores_f)
kept_idx = []
while len(order) > 0:
cur = int(order[0])
kept_idx.append(cur)
if len(order) == 1:
break
ious = compute_iou(boxes_f[cur], boxes_f[order[1:]])
order = order[1:][ious <= 0.5]
kept_classes = [classes_f[i] for i in kept_idx]
c1_ok = len(kept_idx) == 2 and kept_classes == ["car", "pedestrian"]
cases.append(dict(
name="cv_iou_nms_and_detection_pipeline",
inputs=dict(raw_candidates=4, conf_thresh=0.5, iou_thresh=0.5),
prerequisites="目标检测候选框置信度过滤与 IoU 非极大值抑制(离线替代外部 YOLO/OpenCV 模型)",
action="滤除置信度 0.25 噪声框并抑制与高分车辆框高度重叠的重复检测,保留 2 个有效目标。",
expected=dict(kept_count=2, kept_classes=["car", "pedestrian"]),
actual=dict(kept_count=len(kept_idx), kept_classes=kept_classes),
measurements=dict(duplicate_car_iou=round(float(compute_iou(raw_boxes[0], raw_boxes[1:2])[0]), 4)),
passed=c1_ok,
))
# 2. NLP smart assistant intent routing + Chinese sentiment analysis (lexicon + TF-IDF LR)
def route_intent(text: str) -> str:
if "天气" in text:
return "weather"
if "时间" in text:
return "time"
if "笑话" in text:
return "joke"
return "unknown"
intent_tests = ["今天天气怎么样", "现在几点时间", "讲个笑话吧", "帮我订机票"]
intents = [route_intent(t) for t in intent_tests]
pos_words = ["好", "棒", "喜欢", "满意", "推荐"]
neg_words = ["差", "坏", "讨厌", "失望", "不推荐"]
def lexicon_sentiment(text: str) -> str:
# Match longer negation phrases first so "不推荐" does not also trigger "推荐"
cleaned = text
neg_hits = 0
for w in sorted(neg_words, key=len, reverse=True):
if w in cleaned:
neg_hits += 1
cleaned = cleaned.replace(w, "")
pos_hits = sum(1 for w in pos_words if w in cleaned)
if pos_hits > neg_hits:
return "正面情感"
if neg_hits > pos_hits:
return "负面情感"
return "中性情感"
reviews = [
"这个产品真的很棒,我非常喜欢!",
"质量太差了,完全不推荐购买。",
"还可以,没什么特别的。",
]
sentiments = [lexicon_sentiment(r) for r in reviews]
# Also verify supervised char n-gram sentiment classifier on 12 reviews
tr_texts = [
"质量很好非常满意", "做工很棒强烈推荐", "非常喜欢物超所值", "好评体验极佳",
"质量太差很失望", "完全不推荐很糟糕", "非常讨厌做工差", "差评非常不满意",
]
tr_y = [1, 1, 1, 1, 0, 0, 0, 0]
vec = TfidfVectorizer(analyzer="char", ngram_range=(1, 2))
clf_s = LogisticRegression(random_state=42).fit(vec.fit_transform(tr_texts), tr_y)
clf_preds = clf_s.predict(vec.transform(["很棒非常喜欢", "太差非常失望"])).tolist()
c2_ok = (
intents == ["weather", "time", "joke", "unknown"]
and sentiments == ["正面情感", "负面情感", "中性情感"]
and clf_preds == [1, 0]
)
cases.append(dict(
name="nlp_intent_and_sentiment_analysis",
inputs=dict(intent_queries=4, lexicon_reviews=3, clf_train_docs=8),
prerequisites="离线意图路由与修正子串冲突(不推荐/推荐)的中文情感词典+监督分类器",
action="验证 4 条意图路由结果、3 条商品评论正/负/中性判定及字符 n-gram 监督情感分类。",
expected=dict(
intents=["weather", "time", "joke", "unknown"],
sentiments=["正面情感", "负面情感", "中性情感"],
clf_preds=[1, 0],
),
actual=dict(intents=intents, sentiments=sentiments, clf_preds=clf_preds),
passed=c2_ok,
))
# 3. E-commerce user-based collaborative filtering (exact 5x4 rating matrix)
ratings = np.array([
[5, 3, 0, 1],
[4, 0, 0, 1],
[1, 1, 0, 5],
[1, 0, 0, 4],
[0, 1, 5, 4],
], dtype=float)
def user_sim(u1: np.ndarray, u2: np.ndarray) -> float:
common = np.where((u1 > 0) & (u2 > 0))[0]
if len(common) == 0:
return 0.0
a, b = u1[common], u2[common]
denom = float(np.linalg.norm(a) * np.linalg.norm(b))
return float(np.dot(a, b) / denom) if denom > 0 else 0.0
sims = sorted([(i, round(user_sim(ratings[0], ratings[i]), 4)) for i in range(1, len(ratings))], key=lambda x: x[1], reverse=True)
# Predict unrated item index 2 (商品3) using top k=2 neighbors
w_sum = float(sum(sim * float(ratings[uid, 2]) for uid, sim in sims[:2] if sim > 0 and ratings[uid, 2] > 0))
s_sum = float(sum(sim for uid, sim in sims[:2] if sim > 0 and ratings[uid, 2] > 0))
pred_item3 = round(w_sum / s_sum, 4) if s_sum > 0 else 0.0
c3_ok = bool([u for u, _ in sims[:2]] == [1, 4] and pred_item3 == 5.0)
cases.append(dict(
name="collaborative_filtering_recommender",
inputs=dict(users=5, items=4, target_user=0, top_k=2),
prerequisites="5x4 用户-商品评分矩阵与基于共同评分项的余弦相似度协同过滤",
action="计算用户 0 与其他用户余弦相似度,选取前 2 位近邻预测未评分商品 3 的评分。",
expected=dict(top2_neighbors=[1, 4], pred_item3_score=5.0),
actual=dict(top2_neighbors=[u for u, _ in sims[:2]], pred_item3_score=pred_item3),
measurements=dict(all_similarities=sims),
passed=c3_ok,
))
# 4. Financial risk control: 1000-sample (950 normal / 50 fraud) RandomForestClassifier
np.random.seed(42)
normal_tx = np.random.normal(loc=[100, 14, 2, 3], scale=[50, 4, 1, 1], size=(950, 4))
fraud_tx = np.random.normal(loc=[500, 3, 4, 1], scale=[200, 2, 1, 0.5], size=(50, 4))
Xf = np.vstack([normal_tx, fraud_tx])
yf = np.hstack([np.zeros(950, dtype=int), np.ones(50, dtype=int)])
Xf_tr, Xf_te, yf_tr, yf_te = train_test_split(Xf, yf, test_size=0.2, random_state=42, stratify=yf)
rf = RandomForestClassifier(n_estimators=100, random_state=42).fit(Xf_tr, yf_tr)
yf_pred = rf.predict(Xf_te)
acc_f = round(float(rf.score(Xf_te, yf_te)), 4)
prec_f = round(float(precision_score(yf_te, yf_pred, zero_division=0)), 4)
rec_f = round(float(recall_score(yf_te, yf_pred, zero_division=0)), 4)
f1_f = round(float(f1_score(yf_te, yf_pred, zero_division=0)), 4)
p_fraud_abn = round(float(rf.predict_proba(np.array([[450, 2, 4, 1]]))[0, 1]), 4)
p_fraud_norm = round(float(rf.predict_proba(np.array([[95, 14, 2, 3]]))[0, 1]), 4)
c4_ok = bool(acc_f >= 0.98 and rec_f >= 0.90 and p_fraud_abn > 0.80 and p_fraud_norm < 0.10)
cases.append(dict(
name="financial_fraud_random_forest",
inputs=dict(normal=950, fraud=50, test_size=0.2, stratify=True),
prerequisites="1000 条 95:5 不平衡交易特征与随机森林风控模型",
action="验证分层测试集准确率、欺诈召回率/精确率/F1,并核对高危交易 [450,2,4,1] 与正常交易 [95,14,2,3] 的欺诈概率差异。",
expected=dict(acc_ge_098=True, fraud_recall_ge_090=True, abnormal_prob_gt_080=True, normal_prob_lt_010=True),
actual=dict(acc_ge_098=bool(acc_f >= 0.98), fraud_recall_ge_090=bool(rec_f >= 0.90), abnormal_prob_gt_080=bool(p_fraud_abn > 0.80), normal_prob_lt_010=bool(p_fraud_norm < 0.10)),
measurements=dict(accuracy=acc_f, fraud_precision=prec_f, fraud_recall=rec_f, fraud_f1=f1_f, abnormal_fraud_prob=p_fraud_abn, normal_fraud_prob=p_fraud_norm),
passed=c4_ok,
))
# 5. Industrial anomaly detection: 200 normal + 10 anomaly sensors with IsolationForest
np.random.seed(42)
normal_s = np.random.normal(loc=10.0, scale=1.0, size=(200, 2))
anomaly_s = np.random.normal(loc=[15.0, 5.0], scale=[1.0, 1.0], size=(10, 2))
all_s = np.vstack([normal_s, anomaly_s])
true_anom = np.array([0] * 200 + [1] * 10)
iso = IsolationForest(contamination=0.05, random_state=42)
preds = iso.fit_predict(all_s)
flagged = (preds == -1).astype(int)
n_flagged = int(flagged.sum())
true_caught = int(((flagged == 1) & (true_anom == 1)).sum())
c5_ok = bool(n_flagged == 11 and true_caught >= 8)
cases.append(dict(
name="industrial_isolation_forest_anomaly",
inputs=dict(normal=200, injected_anomalies=10, contamination=0.05),
prerequisites="200 条正常设备传感器读数 + 10 条故障偏移读数与孤立森林(contamination=0.05)",
action="拟合 IsolationForest 检测异常点总数并核对注入故障的检出数量。",
expected=dict(flagged_count=11, injected_caught_ge_8=True),
actual=dict(flagged_count=n_flagged, injected_caught_ge_8=bool(true_caught >= 8)),
measurements=dict(true_anomalies_caught=true_caught, false_positives=n_flagged - true_caught),
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-applications-lab/explore-applications.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-applications.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章) · 含当前章节或实例 · mbskycom202612a448.zip