混淆矩阵
本课属于 Coddy Machine Learning 学习旅程的“监督学习”单元。第 21 课,共 58 课。
准确率只统计错误数量,不区分错误类型。对于流感检测来说,让患病患者回家远比误报严重。confusion_matrix 会统计每种错误:
流感是正类,值为 1。错误都出现在对角线之外:假阳性(误报)和假阴性(漏诊)。
from sklearn.metrics import confusion_matrix, ConfusionMatrixDisplay
cm = confusion_matrix(y_test, pred) # 真实值在前
print(cm)
print(cm[1, 0]) # 第 1 行:患流感,第 0 列:预测为健康
ConfusionMatrixDisplay.from_predictions(y_test, pred, display_labels=["healthy", "flu"],
ax=ax, colorbar=False) # 不用颜色条:计数已经说明了这会打印:
[[50 3]
[ 5 42]]
5本章将介绍如何缩小漏掉病例的单元格范围。最后会进行一项筛查测试,几乎不会漏掉任何人。
挑战
中等如果可能形成离岸流,救生员会在早上收到警报。初始代码会训练警报模型,并为测试日期填入 pred(1 表示有离岸流)。
- 生成混淆矩阵,并按下面的格式打印四个计数。
- 在
ax上绘制矩阵,标签使用calm和rip,然后显示图表。
对于另一个模型:
Rips caught: 30
Rips missed: 2
False alarms: 9
Calm days cleared: 59Coddy 会描述你的图表。它应该看起来像下面这个水管漏水警报图表:
亲手试试
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import confusion_matrix, ConfusionMatrixDisplay
# 冲浪海滩每天早上的数据占一行:rip 中的 1 表示当天形成了离岸流
beach = pd.read_csv("rips.csv")
features = ["wave_height_m", "wave_period_s", "wind_kmh", "tide_change_m"]
X = beach[features]
y = beach["rip"]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=0)
# 救生员的离岸流预警
model = LogisticRegression(max_iter=1000)
model.fit(X_train, y_train)
pred = model.predict(X_test)
fig, ax = plt.subplots()
ax.set_title("Rip Current Alerts")
# 在下方编写你的代码
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
监督学习中的所有课
自己练习: Python 在线编译器