SONUB 首頁

只有我們的團隊會閱讀。請不要填寫密碼或卡號。

謝謝!每則意見我們都會閱讀,並用來決定下一步改進什麼。

關閉 送出
ZH-HANT English 한국어 日本語 简体中文 繁體中文 हिन्दी বাংলা اردو Español Português Français Deutsch Русский العربية Bahasa Indonesia Tiếng Việt ไทย Türkçe

如何開啟通知

此瀏覽器或網址無法使用通知。請使用支援通知的瀏覽器,透過安全連線訪問SONUB。

如果通知被遮蔽,請在瀏覽器設定中允許通知。

  1. 開啟位址列旁的站點設定或瀏覽器的站點設定,將此網站的通知設為允許。
  2. 在裝置設定中允許瀏覽器傳送通知,並檢查勿擾模式或專注模式。
  3. 返回SONUB並重新整理頁面。通知開啟後,鈴鐺將不再顯示。

在iPhone或iPad上,將SONUB新增到主螢幕,從主螢幕開啟後允許通知。

用五個步驟做出人工智慧

每個專案都要經過同樣的五個步驟:準備、與視覺化、資料前處理、和模型。在裡做一個小小的垃圾訊息過濾器,把五個步驟全部走一遍。

雜亂的文字碎片進入一台過濾機器,重複的內容和碎屑掉了出來,最後出來一疊整齊乾淨的資料
4

模型訓練

永遠先從最簡單的答案開始,這叫基準線。這裡的基準線是「總是說不是垃圾訊息」。你做的任何模型都必須打敗它,否則就不值得用。

學習模型給每個單字一個。像垃圾訊息的單字得到正的權重,正常的單字得到負的權重。判斷一則訊息時,模型把其中單字的權重和一個偏差值加起來,再把總和壓縮成 0 到 1 之間的。

訓練就是讓模型把每個例子看很多遍,每猜一次就把權重稍一點。損失(loss)衡量猜得有多錯;它必須往下降。

一步一步看邏輯

  1. 做一個基準線 most common
  2. 把文字變成單字編號 features()
  3. 猜一個機率
  4. 稍微調整權重 weight -= rate × error
  5. 儲存模型 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 · Dense
  • PyTorch

動手輸入並實驗

打開 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(-(…)) 裡的負號。

可預約時間已過