SONUB 首页

只有我们的团队会阅读。请不要填写密码或卡号。

谢谢!每条意见我们都会阅读,并用来决定下一步改进什么。

关闭 发送
ZH 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(-(…)) 里的负号。

可预约时间已过