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

训练中文词频分类器并运行留出短句

PYTHONWindows、Python 3.12.14。只需标准库。filter-token-counts.py
filter-token-counts.py77 行
"""Train and exercise a small offline multinomial text classifier."""
from collections import Counter
import json
from math import isclose, isfinite, log
import platform


TRAIN = [
    ("折扣 优惠 订购", "spam"), ("奖品 优惠 领取", "spam"),
    ("促销 订购 优惠", "spam"), ("折扣 赠品 领取", "spam"),
    ("会议 讨论 日程", "ham"), ("发票 项目 报告", "ham"),
    ("会议 纪要 项目", "ham"), ("日程 讨论 团队", "ham"),
]


class WordModel:
    def __init__(self, messages):
        self.doc_counts = Counter(label for _, label in messages)
        self.counts = {label:Counter() for label in self.doc_counts}
        for text,label in messages:
            self.counts[label].update(text.split())
        self.vocab = set().union(*(set(counter) for counter in self.counts.values()))

    def probability(self, word, label):
        counts = self.counts[label]
        return (1 + counts[word]) / (counts.total() + len(self.vocab))

    def classify(self, text):
        tokens = Counter(word for word in text.split() if word in self.vocab)
        scores = {label:log(count / self.doc_counts.total()) +
                  sum(n * log(self.probability(word,label)) for word,n in tokens.items())
                  for label, count in self.doc_counts.items()}
        ordered = sorted(scores,key=scores.get,reverse=True)
        label = ordered[0] if tokens and not isclose(scores[ordered[0]],scores[ordered[1]]) else "review"
        return label,scores


def main():
    cases=[]

    def record(name, operation, inputs, expected, actual):
        assert expected == actual, (name, expected, actual)
        cases.append(dict(name=name,operation=operation,inputs=inputs,expected=expected,actual=actual,passed=True))

    model=WordModel(TRAIN)
    samples=["领取 优惠 赠品","会议 项目 纪要","折扣 订购 促销","报告 发票 团队","未知","", "奖品 团队"]
    record("classify_held_out_messages","fit eight labeled documents and evaluate fixed token sequences",
           samples,["spam","ham","spam","ham","review","review","review"],[model.classify(text)[0] for text in samples])
    record("laplace_normalizes_each_class","sum normalized token probabilities separately",
           {"columns":len(model.vocab)},[1.,1.],
           [round(sum(model.probability(word,label) for word in model.vocab),10) for label in model.counts])
    record("unknown_tokens_do_not_invent_mass","compare known terms with and without an out-of-vocabulary term",
           ["领取","领取 未知"],True,model.classify("领取")==model.classify("领取 未知"))
    _, scores=model.classify(("优惠 ")*1000)
    record("long_document_score_stays_finite","contrast the probability product and log scoring",
           {"repeats":1000},[True,True],
           [model.probability("优惠","spam")**1000==0,all(isfinite(v) for v in scores.values())])
    plain=model.classify("会议")[1]["ham"]
    repeated=model.classify("会议 会议")[1]["ham"]
    record("each_repeat_counts","inspect score increment under an extra occurrence",
           [1,2],True,isclose(repeated-plain,log(model.probability("会议","ham"))))
    record("absent_per_class_has_positive_mass","query a known vocabulary term absent from one class",
           ["奖品","ham"],True,model.counts["ham"]["奖品"]==0 and model.probability("奖品","ham")>0)
    mixture=[.8*a+.2*b for a,b in zip((.75,.25),(.25,.75))]
    record("topic_mixture_normalization","combine two normalized distributions as a document topic mixture",
           {"mix":[.8,.2]},[.65,.35,1.], [round(value,8) for value in (*mixture,sum(mixture))])
    common=-log(model.probability("会议","ham"))
    rare=-log(model.probability("订购","ham"))
    record("anomaly_score_under_one_class","compare length-normalized negative likelihood under normal mail model",
           ["会议 会议","订购 订购"],True,rare>common)
    print(json.dumps(dict(version=platform.python_version(),library_versions={},cases=cases),ensure_ascii=False))


if __name__=="__main__":
    main()

本例需在 Windows、Python 3.12.14。只需标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows、Python 3.12.14。只需标准库。

入口文件:projects/ai-math-naive-bayes-spam-lab/filter-token-counts.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 filter-token-counts.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows、Python 3.12.14。只需标准库。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:AI 数学基础

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

下载课程关联工程包:AI 数学基础

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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