用五個步驟做出人工智慧
每個專案都要經過同樣的五個步驟:準備、與視覺化、資料前處理、和模型。在裡做一個小小的垃圾訊息過濾器,把五個步驟全部走一遍。
五個步驟
不管做什麼,垃圾訊息過濾器也好,也好,大型也好,工作都按同樣的五個步驟進行。和的大小會變,工作的順序不會變。
在這門課裡,你要做一個能分辨垃圾訊息和正常訊息的小人工智慧。資料來自三個不同的地方,每個地方的格式都不一樣。你要把它們合在一起,仔細查看,清理乾淨,教給模型,最後誠實地替它打分數。
每個步驟就是這個頁面上 JupyterLab 裡的一個簡短 筆記本。你逐一執行儲存格,讀一讀它輸出的內容,再動手修改。每個筆記本讀取上一步產生的檔案,再為下一步寫出新的檔案。
五個步驟
- 資料準備 1-prepare.ipynb
- 與視覺化 2-analyze.ipynb
- 資料前處理 3-preprocess.ipynb
- 模型 4-train.ipynb
- 模型 5-evaluate.ipynb
評估找出要改的地方後,回到第 1 步
這些步驟組成一個循環。評估之後,你查看答錯的地方,決定改一樣東西,然後再走一圈。每一圈只改一樣東西,這樣你就知道是什麼讓分數變好或變差。
工作流程 — 每個步驟產生什麼,什麼時候進入下一步
只有最後一欄的成立時,才進入下一步。如果不成立,問題就出在這一步,而不是後面的步驟。
| 步驟 | 產生 | 進入下一步的條件 | |
|---|---|---|---|
| 資料準備 |
1-prepare.ipynb
|
data/all.csv
|
總列數等於三個原始檔案的列數 |
| 資料分析與視覺化 |
2-analyze.ipynb
|
notes.md
|
清理規則已經寫進 notes.md |
| 資料前處理 |
3-preprocess.ipynb
|
data/train.csv · valid.csv · test.csv · vocab.json
|
沒有任何文字同時出現在兩部分裡(overlap 0) |
| 模型訓練 |
4-train.ipynb
|
model.json
|
下降了,model.json 已儲存 |
| 模型評估 |
5-evaluate.ipynb
|
—
|
分數、比較和下一次的一個改動都寫好了 |
專案資料夾
所有工作都在 JupyterLab 裡的一個資料夾 basic/ 中進行。JupyterLab 打開時,assets/ 裡的原始資料和每個步驟的一個筆記本就已經準備好了。每個筆記本裡有這一步的完整程式碼,分成一個個儲存格:執行一個儲存格,讀一讀它輸出的內容,然後修改它再執行一次。
basic/
├── assets/ 原始資料(不要修改)
│ ├── sms.csv message,is_spam (1 / 0)
│ ├── mail.tsv body⇥category (spam / ham)
│ └── chat.jsonl {"text": …, "label": "yes" / "no"}
├── data/ 你的程式產生的檔案
├── 1-prepare.ipynb ①
├── 2-analyze.ipynb ②
├── 3-preprocess.ipynb ③
├── 4-train.ipynb ④
└── 5-evaluate.ipynb ⑤
為什麼只用純 Python
這門課只用 Python 標準(csv、、random、math 和 collections),所以每一行都能在你裡的 Python 中執行,你也能看到每一步計算。
在真實專案中,同樣的五個步驟會用工具來完成:資料用 pandas 和 ,圖表用 seaborn 和 matplotlib,切分資料和傳統模型用 ,用 Keras 或 。下面每個步驟都會說明哪個工具做同樣的事,等你理解了,就可以改用這些工具。
動手輸入並實驗
JupyterLab 會在課程旁邊打開(窄螢幕上在課程下方)。先看看原始資料:在檔案瀏覽器裡打開 basic/assets,雙擊每個檔案。注意,每個檔案儲存文字和答案(是不是垃圾訊息)的方式都不一樣。
完成標準
你能按順序說出五個步驟,也能說出每個步驟產生哪個檔案。你已經在 JupyterLab 裡打開過全部三個原始檔案。
遇到問題時
如果 JupyterLab 一直是空白的,請等幾秒:第一次會下載 Python(約 30 )。如果看不到 basic/,點一下左上角的資料夾圖示。千萬不要修改 assets/ 裡的檔案:它們是原始資料,你改動任何東西時,每個步驟都會重新從這裡讀取。
資料準備
資料很少只來自一個地方。這裡的訊息放在三個格式不同的檔案裡:
- (sms.csv):用逗號分隔各欄的文字檔,可以用 開成表格。
- TSV(mail.tsv):用定位字元(Tab)分隔各欄的文字檔。
- (chat.jsonl):JSON 是在 { } 裡用 "名稱": 值 成對寫資料的格式。這個檔案每行寫一個 JSON 物件。
每個檔案替欄位取的名字不同,寫答案的方式也不同。
資料準備就是先不改動內容,把所有資料收集成一種共同的格式。清理放在後面的第 3 步,要等你在第 2 步看過資料之後再做。如果現在就清理,可能會把還沒弄明白的東西丟掉。
一步一步看邏輯
-
讀取每個檔案 csv · json
-
改成共同的欄位名稱 text · label · source
-
數一數列數 (rows)
-
儲存成一張表 data/all.csv
csv.DictReader 把 CSV 檔案一列一列讀成,所以 r["message"] 就是 message 欄。對於 TSV 檔案,delimiter="\t" 告訴它欄與欄之間用定位字元分隔。JSONL 檔案用 json.loads 一次讀一行。
每一列都變成 {"text": …, "label": …, "source": …}。label 原樣複製,所以 1、spam 和 yes 現在還是不同的值。source 欄記住每一列來自哪裡;第 2 步比較各個來源時會用到它。
用真實工具做同樣的事
用 pandas 的話,每個檔案一次 read 就能讀進來,再用 pd.concat 把它們疊成一張表。
pd.read_csv()pd.read_json(lines=True)pd.concat()df.to_csv()
動手輸入並實驗
打開 1-prepare.ipynb,按 Shift+Enter 逐一執行儲存格。執行完最後一個儲存格後,在檔案瀏覽器裡打開 data/all.csv,看看產生的表。
1-prepare.ipynb本筆記本的完整程式碼
# Step 1. Data preparation — read three sources and save them in one common format.
import csv
import json
import os
rows = []
# sms.csv: columns message, is_spam (1 or 0)
with open("assets/sms.csv", newline="", encoding="utf-8") as f:
for r in csv.DictReader(f):
rows.append({"text": r["message"], "label": r["is_spam"], "source": "sms"})
# mail.tsv: columns body, category (spam or ham), separated by tabs
with open("assets/mail.tsv", newline="", encoding="utf-8") as f:
for r in csv.DictReader(f, delimiter="\t"):
rows.append({"text": r["body"], "label": r["category"], "source": "mail"})
# chat.jsonl: one JSON object per line, keys text and label (yes or no)
with open("assets/chat.jsonl", encoding="utf-8") as f:
for line in f:
r = json.loads(line)
rows.append({"text": r["text"], "label": r["label"], "source": "chat"})
print("rows by source")
for source in ["sms", "mail", "chat"]:
count = sum(1 for r in rows if r["source"] == source)
print(f" {source:5} {count}")
print("total", len(rows))
os.makedirs("data", exist_ok=True)
with open("data/all.csv", "w", newline="", encoding="utf-8") as f:
writer = csv.DictWriter(f, fieldnames=["text", "label", "source"])
writer.writeheader()
writer.writerows(rows)
print("saved data/all.csv")
Run ▸ Run All Cells你應該看到的結果
rows by source
sms 65
mail 59
chat 59
total 183
saved data/all.csv
完成標準
筆記本顯示 sms 65 列、mail 59 列、chat 59 列,共 183 列。拿它和原始檔案對照:在新儲存格裡,len(open("assets/sms.csv").readlines()) 可以數出一個檔案的行數,CSV 或 TSV 檔案會多一行欄位名稱。一列也不能少,一列也不能多。
遇到問題時
: 'message' 表示欄位名稱和檔案的第一行對不上;打開 assets/sms.csv 比較一下。 表示筆記本不在 basic/ 資料夾裡;請在檔案瀏覽器的 basic/ 裡打開它。
資料分析與視覺化
改動任何東西之前,先看。分析就是回答一些簡單的問題:一共有多少列?有沒有空的文字?每個來源怎麼寫標籤?訊息有多長?同一則訊息有沒有出現兩次?
視覺化把數字變成圖,讓你一眼就能看出問題。這裡的圖表直接在儲存格的輸出裡用方塊字元畫出來:長條越長,數字越大。
這一步的結果不是資料檔案,而是一張簡短的規則清單。每條規則都來自你看到的東西。
一步一步看邏輯
-
找出空文字 text == ""
-
按來源數標籤 Counter
-
畫長條圖 █ bar()
-
找出重複 n > 1
-
寫下規則 notes.md
Counter 數出每個值出現了多少次。按 source 分組後可以看到,sms 寫 1 和 0,mail 寫 ham 和 spam(有時寫成 SPAM 或 Spam),chat 寫 yes 和 no。
bar 函式畫出「值 / 最大值 × 30」個方塊,所以最長的長條總是 30 個方塊。垃圾訊息比例圖用一條暫時的規則把標籤變成「是不是垃圾訊息」;真正的規則在第 3 步再寫。
找重複時,先把每段文字變成小寫,空格統一成一個,所以 "See you at lunch" 和 "see you at lunch" 算作同一則訊息。
用真實工具做同樣的事
用 pandas 的話,isnull().sum() 找出空值,describe() 給出統計數字,pivot_table() 做出標籤表,seaborn 畫出圖表。
df.isnull().sum()df.describe()df.pivot_table()sns.countplot()sns.barplot()
動手輸入並實驗
打開 2-analyze.ipynb,選擇 Run ▸ Run All Cells。然後把你發現的東西當作規則寫進一個新檔案:File ▸ New ▸ File,再把它改名為 notes.md。
2-analyze.ipynb本筆記本的完整程式碼
# Step 2. Data analysis and visualization — look at the data with numbers and bar charts.
import csv
from collections import Counter
with open("data/all.csv", newline="", encoding="utf-8") as f:
rows = list(csv.DictReader(f))
def bar(name, value, top, width=30):
"""One line of a bar chart drawn with text."""
print(f" {name:8} {'█' * round(value / top * width)} {value}")
print("rows:", len(rows))
# 1) Missing values: rows whose text is empty
empty = [r for r in rows if r["text"].strip() == ""]
print("empty text:", len(empty))
# 2) Rows by source (chart)
print("\nrows by source")
by_source = Counter(r["source"] for r in rows)
for source, count in by_source.items():
bar(source, count, max(by_source.values()))
# 3) Label values by source — every source writes the label differently
print("\nlabel values by source")
for source in by_source:
labels = Counter(r["label"] for r in rows if r["source"] == source)
print(f" {source:5}", dict(labels))
# 4) Spam ratio by source (chart, with a temporary label rule)
print("\nspam ratio by source (%)")
for source in by_source:
part = [r for r in rows if r["source"] == source]
spam = sum(1 for r in part if r["label"].lower() in ("1", "spam", "yes"))
bar(source, round(spam / len(part) * 100), 100)
# 5) Text length (chart)
lengths = [len(r["text"]) for r in rows if r["text"].strip()]
print("\ntext length: min", min(lengths), "avg", round(sum(lengths) / len(lengths)), "max", max(lengths))
groups = Counter(min(n // 20, 4) for n in lengths)
names = ["0-19", "20-39", "40-59", "60-79", "80+"]
for g in range(5):
bar(names[g], groups[g], max(groups.values()))
# 6) Duplicates: the same text more than once
texts = Counter(" ".join(r["text"].lower().split()) for r in rows if r["text"].strip())
duplicates = {t: n for t, n in texts.items() if n > 1}
print("\nduplicate texts:", len(duplicates))
for text, n in duplicates.items():
print(f" {n}x {text}")
Run ▸ Run All Cells你應該看到的結果
rows: 183
empty text: 3
rows by source
sms ██████████████████████████████ 65
mail ███████████████████████████ 59
chat ███████████████████████████ 59
label values by source
sms {'1': 28, '0': 37}
mail {'ham': 33, 'spam': 24, 'SPAM': 1, 'Spam': 1}
chat {'no': 32, 'yes': 27}
spam ratio by source (%)
sms █████████████ 43
mail █████████████ 44
chat ██████████████ 46
text length: min 1 avg 39 max 82
0-19 ███████ 17
20-39 ██████████████████████████████ 75
40-59 ██████████████████████████████ 74
60-79 █████ 13
80+ 1
duplicate texts: 3
3x congratulations! you won a free iphone. click the link to claim it now
3x see you at lunch
2x call me now
完成標準
你的 notes.md 裡至少有下面四條規則,每條都根據你看到的數字:
- 去掉空的和很短的文字(有 3 則空文字,最短的文字只有 1 個字元)。
- 把每個標籤都變成 1(垃圾訊息)或 0(不是垃圾訊息):1、spam、yes 和 0、ham、no,不分大小寫。
- 重複的文字只留一份,標籤互相矛盾的文字去掉("call me now" 在一個來源裡是垃圾訊息,在另一個來源裡是正常訊息)。
- 切分資料時讓每一部分的垃圾訊息比例差不多(每個來源都大約是 45%)。
遇到問題時
如果長條圖看起來是亂的,可能是字型裡沒有方塊字元;重要的是每個長條最後的數字。如果沒看到重複,檢查一下數之前有沒有把文字變成小寫。如果 data/all.csv 出現 FileNotFoundError,表示還沒有執行 1-prepare.ipynb。
資料前處理
前處理就是把原始資料變成模型能學習的資料。這裡的每個動作都來自你在第 2 步寫下的規則,程式在每個動作之後都會顯示列數,讓你看到每條規則去掉了什麼。
有兩個想法最重要。第一,test 資料必須完全沒被看過:如果同一則訊息同時出現在 train 和 test 裡,分數會比模型的真實水準好看。第二,模型學習用的任何東西,連單字表也一樣,都只從 train 部分來做。
一步一步看邏輯
-
清理文字 lower() · split()
-
統一標籤 1 / 0
-
去掉重複 set()
-
分成三份 80 / 10 / 10
-
把單字變成數字 vocab.json
清理時把文字變成小寫,單字之間只留一個空格,並去掉短於 3 個字元的文字。標籤用兩組單字變成 1 或 0;兩組裡都沒有的標籤不去猜,直接去掉。
處理重複時,程式先收集每段文字帶有的所有標籤。只有一種標籤的文字保留一份;有兩種不同標籤的文字去掉,因為誰也不知道正確答案。
切分時,把垃圾訊息和正常訊息分開打亂,用 random.seed(42) 讓每次結果都一樣,再從每一組裡取 80% 做 train,10% 做 valid,10% 做 test。這樣三部分的垃圾訊息比例就一樣。最後,在 train 裡出現至少兩次的每個單字都會得到一個編號:這張單字表(vocab.json)就是把文字變成數字的方法。
用真實工具做同樣的事
用 pandas 和 scikit-learn 的話:dropna 和 drop_duplicates 清理表格,train_test_split(stratify=…) 保持比例來切分,TfidfVectorizer 把文字變成數字。
df.dropna()df.drop_duplicates()train_test_split(stratify=…)TfidfVectorizer
動手輸入並實驗
打開 3-preprocess.ipynb,逐一執行儲存格。每個儲存格就是一條規則:看它輸出的列數,和你的筆記對一對。
3-preprocess.ipynb本筆記本的完整程式碼
# Step 3. Data preprocessing — clean, unify, remove duplicates, split, and turn text into numbers.
import csv
import json
import random
from collections import Counter
SPAM = {"1", "spam", "yes"}
HAM = {"0", "ham", "no"}
with open("data/all.csv", newline="", encoding="utf-8") as f:
rows = list(csv.DictReader(f))
print("start", len(rows))
# 1) Clean: lower case, one space between words, drop texts shorter than 3 characters
for r in rows:
r["text"] = " ".join(r["text"].lower().split())
rows = [r for r in rows if len(r["text"]) >= 3]
print("after cleaning", len(rows))
# 2) Unify labels: every source becomes 1 (spam) or 0 (not spam)
for r in rows:
label = r["label"].strip().lower()
r["spam"] = 1 if label in SPAM else 0 if label in HAM else None
rows = [r for r in rows if r["spam"] is not None]
# 3) Duplicates: keep one row per text, drop texts that got different labels
labels = {}
for r in rows:
labels.setdefault(r["text"], set()).add(r["spam"])
seen = set()
unique = []
for r in rows:
if len(labels[r["text"]]) == 1 and r["text"] not in seen:
seen.add(r["text"])
unique.append(r)
print("after duplicates", len(unique))
# 4) Split 80 / 10 / 10, keeping the same spam ratio in each part (seed 42 = same result every time)
random.seed(42)
parts = {"train": [], "valid": [], "test": []}
for value in (0, 1):
group = [r for r in unique if r["spam"] == value]
random.shuffle(group)
a, b = round(len(group) * 0.8), round(len(group) * 0.9)
parts["train"] += group[:a]
parts["valid"] += group[a:b]
parts["test"] += group[b:]
for name, part in parts.items():
spam = sum(r["spam"] for r in part)
print(f"{name:5} {len(part):3} rows, spam {spam}")
with open(f"data/{name}.csv", "w", newline="", encoding="utf-8") as f:
writer = csv.DictWriter(f, fieldnames=["text", "spam"], extrasaction="ignore")
writer.writeheader()
writer.writerows(part)
# Check: no text may be in two parts
train_texts = {r["text"] for r in parts["train"]}
overlap = sum(1 for r in parts["valid"] + parts["test"] if r["text"] in train_texts)
print("overlap", overlap)
# 5) Text to numbers: give each word a number, using the train part only
counts = Counter(w for r in parts["train"] for w in r["text"].split())
words = sorted(w for w, n in counts.items() if n >= 2)
vocab = {w: i for i, w in enumerate(words)}
with open("data/vocab.json", "w", encoding="utf-8") as f:
json.dump(vocab, f, indent=1)
print("vocabulary", len(vocab), "words")
Run ▸ Run All Cells你應該看到的結果
start 183
after cleaning 178
after duplicates 172
train 137 rows, spam 62
valid 18 rows, spam 8
test 17 rows, spam 8
overlap 0
vocabulary 147 words
完成標準
列數從 183 → 178 → 172,三部分是 train 137、valid 18、test 17,overlap 是 0。詞彙表有 147 個單字。
遇到問題時
如果 overlap 不是 0,表示你是在切分之後才去掉重複,而不是在切分之前。如果列數和上面的數字不一樣,先重新執行 1-prepare.ipynb,再用 Run ▸ Run All Cells 從頭執行這個筆記本。
模型訓練
永遠先從最簡單的答案開始,這叫基準線。這裡的基準線是「總是說不是垃圾訊息」。你做的任何模型都必須打敗它,否則就不值得用。
學習模型給每個單字一個。像垃圾訊息的單字得到正的權重,正常的單字得到負的權重。判斷一則訊息時,模型把其中單字的權重和一個偏差值加起來,再把總和壓縮成 0 到 1 之間的。
訓練就是讓模型把每個例子看很多遍,每猜一次就把權重稍一點。損失(loss)衡量猜得有多錯;它必須往下降。
一步一步看邏輯
-
做一個基準線 most common
-
把文字變成單字編號 features()
-
猜一個機率
-
稍微調整權重 weight -= rate × error
-
儲存模型 model.json
features() 用第 3 步的 vocab.json,把一則訊息變成它認識的單字的編號。猜測是 p = 1 / (1 + e^-(偏差值 + 單字權重之和));這個 sigmoid 函式能把任何總和變成機率。
error = p − y 表示猜得有多錯(y 是真正的答案,1 或 0)。訊息裡每個單字的權重都朝相反方向移動 rate × error,所以下一次猜測會更接近一點。把全部跑過一遍叫一個 ;這個程式跑 20 個 epoch。
權重和偏差值儲存在 model.json 裡。這個檔案就是模型:它學到的那些數字。
用真實工具做同樣的事
用 scikit-learn 的話就是 LogisticRegression().fit(X, y)。深度學習模型(Keras 的 Dense 層,或者用 PyTorch 寫的 )也用同樣的方法訓練:猜測,計算損失,調整權重。
LogisticRegression().fit()keras Sequential · DensePyTorch
動手輸入並實驗
打開 4-train.ipynb,執行所有儲存格。每過一組 epoch 就看看損失,然後看看模型認為最像垃圾訊息和最正常的單字。改一改 rate,再執行一次訓練儲存格,看看會發生什麼。
4-train.ipynb本筆記本的完整程式碼
# Step 4. Model training — a baseline rule first, then a small learning model (logistic regression).
import csv
import json
import math
import random
with open("data/vocab.json", encoding="utf-8") as f:
vocab = json.load(f)
with open("data/train.csv", newline="", encoding="utf-8") as f:
train = [(r["text"], int(r["spam"])) for r in csv.DictReader(f)]
def features(text):
"""Text -> numbers: the numbers of the known words in the text."""
return [vocab[w] for w in dict.fromkeys(text.split()) if w in vocab]
# 1) Baseline: always answer the most common label
spam = sum(y for _, y in train)
baseline = 1 if spam > len(train) - spam else 0
print("baseline answer:", baseline)
# 2) Logistic regression: one weight per word + bias -> probability of spam
weights = [0.0] * len(vocab)
bias = 0.0
rate = 0.3
data = [(features(text), y) for text, y in train]
random.seed(42)
for epoch in range(1, 21):
random.shuffle(data)
total = 0.0
for x, y in data:
p = 1 / (1 + math.exp(-(bias + sum(weights[i] for i in x))))
p = min(max(p, 1e-9), 1 - 1e-9)
total += -(y * math.log(p) + (1 - y) * math.log(1 - p))
error = p - y # how wrong the guess was
bias -= rate * error
for i in x:
weights[i] -= rate * error
if epoch == 1 or epoch % 5 == 0:
print(f"epoch {epoch:2} loss {total / len(data):.4f}")
with open("model.json", "w", encoding="utf-8") as f:
json.dump({"baseline": baseline, "bias": bias, "weights": weights}, f)
print("saved model.json")
words = sorted(vocab, key=lambda w: weights[vocab[w]])
print("spam words:", ", ".join(words[-5:][::-1]))
print("normal words:", ", ".join(words[:5]))
Run ▸ Run All Cells你應該看到的結果
baseline answer: 0
epoch 1 loss 0.4373
epoch 5 loss 0.0944
epoch 10 loss 0.0481
epoch 15 loss 0.0322
epoch 20 loss 0.0241
saved model.json
spam words: message, now, confirm, here, your
normal words: the, is, are, remember, home
完成標準
損失從大約 0.44 降到大約 0.02,model.json 已儲存,垃圾訊息單字也說得通(例如 now、confirm、here、your)。
遇到問題時
如果損失往上走或者忽高忽低,表示 rate 太大了;試試 0.1。如果看到 math error,檢查一下 math.exp(-(…)) 裡的負號。
模型評估
模型好不好,要看它在從沒見過的資料上的分數。還在改動東西的時候用 valid 部分,test 部分只在最後用一次。
只看準確率可能會被騙。基準線每次都說「不是垃圾訊息」,就能答對一半以上,但它一則垃圾訊息也抓不到。所以垃圾訊息過濾器還要看另外兩個數字:
- 精確率:模型說是垃圾訊息的訊息中,真正是垃圾訊息的有多少。
- 召回率:真正的垃圾訊息中,模型抓到了多少。
- F1 把這兩個數字合成一個。
最後,讀一讀答錯的地方。它們會告訴你下一圈要改什麼。
一步一步看邏輯
-
預測是不是垃圾訊息 p ≥ 0.5
-
數四種情況 tp · fp · fn · tn
-
計算分數 accuracy · F1
-
和基準線比較 baseline
-
讀答錯的地方 wrong answers
機率在 0.5 或以上時,就判斷這則訊息是垃圾訊息。這樣每個答案都會落進四種情況之一:tp(垃圾訊息,判為垃圾訊息)、fp(正常訊息,判為垃圾訊息)、fn(垃圾訊息,判為正常訊息)和 tn(正常訊息,判為正常訊息)。這就是。
accuracy = (tp + tn) / 全部,precision = tp / (tp + fp),recall = tp / (tp + fn),F1 = 2 × precision × recall / (precision + recall)。程式也為基準線算出同樣的分數,只有模型的 F1 更高時才使用模型。
用真實工具做同樣的事
scikit-learn 為這裡的每個分數都準備了現成的函式,confusion_matrix 可以做出四種情況的表。
accuracy_scoreprecision_scorerecall_scoref1_scoreconfusion_matrix
動手輸入並實驗
打開 5-evaluate.ipynb,在 valid 部分上執行所有儲存格。讀一讀答錯的地方,在 notes.md 裡寫下下一次要試的一個改動。只有全部完成後,才把 part = "valid" 改成 part = "test",再全部執行一次。
5-evaluate.ipynb本筆記本的完整程式碼
# Step 5. Model evaluation — score the model on data it never saw, and compare it with the baseline.
import csv
import json
import math
part = "valid" # change to "test" only once, at the very end
with open("data/vocab.json", encoding="utf-8") as f:
vocab = json.load(f)
with open("model.json", encoding="utf-8") as f:
model = json.load(f)
with open(f"data/{part}.csv", newline="", encoding="utf-8") as f:
rows = [(r["text"], int(r["spam"])) for r in csv.DictReader(f)]
def predict(text):
x = [vocab[w] for w in dict.fromkeys(text.split()) if w in vocab]
p = 1 / (1 + math.exp(-(model["bias"] + sum(model["weights"][i] for i in x))))
return 1 if p >= 0.5 else 0
def scores(answers):
tp = sum(1 for (_, y), a in zip(rows, answers) if y == 1 and a == 1)
fp = sum(1 for (_, y), a in zip(rows, answers) if y == 0 and a == 1)
fn = sum(1 for (_, y), a in zip(rows, answers) if y == 1 and a == 0)
tn = sum(1 for (_, y), a in zip(rows, answers) if y == 0 and a == 0)
precision = tp / (tp + fp) if tp + fp else 0.0
recall = tp / (tp + fn) if tp + fn else 0.0
f1 = 2 * precision * recall / (precision + recall) if precision + recall else 0.0
return {"accuracy": (tp + tn) / len(rows), "precision": precision, "recall": recall, "f1": f1, "table": (tp, fp, fn, tn)}
model_answers = [predict(text) for text, _ in rows]
base = scores([model["baseline"]] * len(rows))
mine = scores(model_answers)
print(f"{part}: {len(rows)} rows")
print(f"{'':10} {'baseline':>9} {'model':>7}")
for key in ("accuracy", "precision", "recall", "f1"):
print(f"{key:10} {base[key]:9.3f} {mine[key]:7.3f}")
tp, fp, fn, tn = mine["table"]
print("\nconfusion table said spam said normal")
print(f" really spam {tp:9} {fn:11}")
print(f" really normal {fp:9} {tn:11}")
print("\nwrong answers")
for (text, y), a in zip(rows, model_answers):
if y != a:
print(f" answer {y}, model {a}: {text}")
print("\nuse the model" if mine["f1"] > base["f1"] else "\nkeep the baseline")
Run ▸ Run All Cells你應該看到的結果
valid: 18 rows
baseline model
accuracy 0.556 0.778
precision 0.000 1.000
recall 0.000 0.500
f1 0.000 0.667
confusion table said spam said normal
really spam 4 4
really normal 0 10
wrong answers
answer 1, model 0: dear friend i need your help to move my money. you will get a share
answer 1, model 0: we are hiring. work two hours a day and earn more
answer 1, model 0: make money fast. join my team now
answer 1, model 0: exclusive discount for our best customers. click the link
use the model
完成標準
在 valid 上,模型的 F1 是 0.667,基準線是 0.000,所以程式說要使用模型。召回率只有 0.5:它漏掉了用沒學過的單字寫的垃圾訊息,例如 money、hiring 和 share。你已經為下一圈寫下了一個改動,例如增加那類垃圾訊息的例子,或者保留只出現一次的單字。
遇到問題時
ZeroDivisionError 表示某一部分裡沒有垃圾訊息,或者模型一則都沒判為垃圾訊息;程式已經為這種情況保護了 precision 和 recall。如果你的分數不一樣,在執行 5 之前重新執行筆記本 3 和 4,因為每一步都讀取上一步的檔案。