蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

从词项匹配到本机模型训练

PYTHONPython 3.12.14,PyTorch 2.10.0 CPU,固定样本与本机浏览器。methods.py
methods.py57 行
"""Compare a hand-written rule, a fitted Naive Bayes classifier and a trained MLP."""
from collections import Counter
from math import log

import torch

from lab_tools import run_exercise


DATA = [("free offer","spam"),("claim coupon","spam"),("team meeting","ham"),("project notes","ham")]


def predict_bayes(examples, text):
    counts={label:Counter(word for message,tag in examples if label==tag for word in message.split())
            for label in ("spam","ham")}
    vocab=set().union(*counts.values())
    words=[word for word in text.split() if word in vocab]
    if not words:
        return "review"
    scores={label:log(sum(tag==label for _,tag in examples)/len(examples))+
        sum(log((1+terms[word])/(sum(terms.values())+len(vocab))) for word in words)
        for label,terms in counts.items()}
    return "review" if scores["spam"]==scores["ham"] else max(scores,key=scores.__getitem__)


def exercise(checks,_):
    expect=checks.expect
    messages=["free offer","claim coupon","team meeting","unknown"]
    expect("ai_about_rule",messages,"Run a hand-written substring rule including a missed alternative",
           ["spam","ham","ham","ham"],["spam" if "free offer" in text else "ham" for text in messages])
    expect("ai_about_bayes",messages,"Fit token likelihoods with Laplace smoothing, then predict or route unknown text",
           ["spam","spam","ham","review"],[predict_bayes(DATA,text) for text in messages])
    torch.set_num_threads(1)
    torch.manual_seed(62)
    inputs=torch.tensor([[0.0,0.0],[0.0,1.0],[1.0,0.0],[1.0,1.0]])
    labels=torch.tensor([0,1,1,1])
    model=torch.nn.Sequential(torch.nn.Linear(2,8),torch.nn.ReLU(),torch.nn.Linear(8,2))
    optimizer=torch.optim.SGD(model.parameters(),lr=0.2)
    loss_fn=torch.nn.CrossEntropyLoss()
    before=float(loss_fn(model(inputs),labels).detach())
    for _ in range(100):
        optimizer.zero_grad()
        loss=loss_fn(model(inputs),labels)
        loss.backward()
        optimizer.step()
    with torch.inference_mode():
        logits=model(inputs)
        after=float(loss_fn(logits,labels))
        probabilities=logits.softmax(dim=-1)
    expect("ai_about_mlp",inputs.tolist(),"Train two linear layers with ReLU, then check logits, loss and normalized probabilities",
           [[4,2],True,True,[0,1,1,1]],[list(logits.shape),after<before,
             bool(torch.allclose(probabilities.sum(-1),torch.ones(4))),logits.argmax(-1).tolist()])


if __name__=="__main__":
    run_exercise(exercise)
本例需在 Python 3.12.14,PyTorch 2.10.0 CPU,固定样本与本机浏览器。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Python 3.12.14,PyTorch 2.10.0 CPU,固定样本与本机浏览器。

入口文件:projects/ai-about/methods.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 methods.py,或下载右侧课程工程包。
  2. 确认本地已准备 Python 3.12.14,PyTorch 2.10.0 CPU,固定样本与本机浏览器。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:AI(人工智能)

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1.zip

下载课程关联工程包:AI(人工智能)

课程关联工程包(登记关联30章) · 含当前章节或实例 · mbskycom202612a5.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习