机器学习应用
系统梳理计算机视觉、自然语言处理、推荐系统、金融预测分析与异常检测五大落地方向,实测 NMS 去重、意图与否定情感修正、协同过滤、反欺诈与孤立森林检测。
学完这一章,你能够
- 系统梳理计算机视觉、自然语言处理、推荐系统、金融预测分析与异常检测五大落地方向,实测 NMS 去重、意图与否定情感修正、协同过滤、反欺诈与孤立森林检测。
五大应用版图与计算机视觉落地
机器学习的核心落地版图涵盖五大方向:让机器“看懂”世界的计算机视觉、理解人类语言的自然语言处理、个性化分发的推荐系统、预判风险与趋势的预测分析,以及揪出异常模式的异常检测。若沿用传统规则编程,面对人脸光照角度千变万化、多语语法词典庞大或亿级人货偏好匹配均难以维护,而机器学习可直接从海量样本中归纳复杂模式。
计算机视觉聚焦三类高频场景:人脸识别(定位人脸 → 提取五官特征 → 库内比对,用于解锁与身份核验)、自动驾驶(目标检测、车道线感知与路径规划)以及医疗影像辅助诊断(分析 X 光/CT/病理切片,降低疲劳误差并高速初筛细微病灶)。在无外置 YOLO 权重和摄像头设备的离线环境下,本站以纯 NumPy 实测自动驾驶检测核心后处理 IoU 与非极大值抑制(NMS):重叠车辆候选框 IoU 达 `0.8872` 被精准抑制,最终输出 `2` 个去重目标 `['car', 'pedestrian']`。
自然语言处理:智能助手、翻译与情感分析
自然语言处理支撑智能助手(串接语音识别、意图理解与多轮对话管理)与神经机器翻译(源语言编码 → 神经网络语义映射 → 目标语言解码)。本站离线实现免麦克风与免联网语音 API 的文本意图路由引擎,对天气、时间、笑话及未知查询准确分流为 `['weather', 'time', 'joke', 'unknown']`。
情感分析广泛用于商品评论与舆情监测。词典法常见陷阱是子串冲突:例如负向短语“不推荐”内部包含正向词“推荐”,朴素子串匹配会导致极性误抵消;实现时应先剥离较长否定短语再匹配基础情感词,或采用监督文本分类模型。本站实测修正后的词典分析准确判定三条中文评论为 `['正面情感', '负面情感', '中性情感']`,字符 n-gram 逻辑回归分类器亦正确预测 `[1, 0]`。
推荐系统、金融预测分析与异常检测
推荐系统在电商领域常融合基于用户行为相似度的协同过滤、基于物品属性的内容推荐及混合策略;在短视频与流媒体场景则进一步面对实时反馈调整、多模态特征融合与新用户/新内容冷启动挑战。本站实现用户余弦相似度协同过滤矩阵:算得目标用户与其他用户相似度排序 `[[1, 0.9989], [4, 0.5369], [3, 0.4281], [2, 0.4229]]`,选取 Top-2 近邻 `[1, 4]` 加权预测未看商品 3 评分为 `5.0`。
预测分析既用于信用卡反欺诈与贷款审批等金融风控,也探索量化交易股价建模——后者因市场噪声极大、序列高度非平稳且受宏观与情绪等多因素扰动,极具不确定性。本站在 1000 笔合成交易(5% 欺诈率)上实测随机森林反欺诈模型,测试集准确率 `0.995`、欺诈类精确率 `1.0`、召回率 `0.9`、F1 `0.9474`,对高额深夜异常交易给出 `1.0` 欺诈概率、常规日间小额交易给出 `0.0`。
异常检测通过刻画正常基线来捕捉罕见偏离,典型用于网络安全入侵阻断(识别偏离正常模式的流量)与工业质检及设备故障预警。本站使用无监督 `IsolationForest` 对 200 条传感器时序点(其中注入 10 条极端异常)进行实测,算法共告警 `11` 条记录,成功检出 `8` 条真实注入故障并产生 `3` 条误报。
运行 NMS 去重、意图与情感分析、协同过滤、反欺诈与孤立森林异常检测实验
"""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()
- 核对重复车辆框 IoU=0.8872 经 NMS 保留 2 目标、4 意图路由与修正否定情感判定、协同过滤近邻 [1, 4] 预测 5.0 分、反欺诈 F1=0.9474 及孤立森林捕获 8/10 注入故障。
所需环境: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。
当前源码 SHA256:253fbf33ced5ab768aeaf9de62c2faa1dfa07eea5d80630f5d0c75a6503c46bf
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境: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。
ZIP SHA256:f83e55b1be5e0e56a2f64686bdc9fad5a2eb1d398666017b4b15ff1bf298aeeb
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
在基于词典的中文情感分析中,为什么直接用 `word in text` 检查“推荐”和“不推荐”会产生错误结果,应如何改进?
展开参考解答
“不推荐”本身包含子串“推荐”,朴素子串匹配会同时记入 1 次负面与 1 次正面导致互相抵消;应先按长度降序匹配并移除否定短语,再统计剩余基础词,或在有标注语料时改用 n-gram 监督分类器。