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

区分文字提示、群体差异与证据核对

PYTHONPython 3.12.14 标准库,固定虚构文本、通过结果、记录和文件。ethics_lab.py
ethics_lab.py110 行
"""Audit fixed training examples and separate review flags from decisions."""
from collections import Counter
from fractions import Fraction
from hashlib import sha256
import re

from lab_tools import run_exercise


RULE = re.compile(r"只招(?:男性|女性)|不适合担任.{1,12}(?:教师|技师)")


def scan(text):
    match = RULE.search(text)
    if not match:
        return ["no_match", None]
    fragment = match.group()
    quoted = f"“{fragment}”" in text
    contextual = quoted or ("撤下" in text or "不要写" in text)
    return ["context_review" if contextual else "claim_review", fragment]


def compare_groups(records, groups, threshold):
    counts = {group: Counter() for group in groups}
    if len(counts) != len(groups):
        raise ValueError("duplicate group")
    for group, outcome in records:
        if group not in counts or outcome not in {"pass", "reject"}:
            raise ValueError("unknown group or outcome")
        counts[group][outcome] += 1
    rows = []
    rates = []
    for group, result in counts.items():
        total = result.total()
        rate = Fraction(result["pass"], total) if total else None
        rows.append([group, result["pass"], total, str(rate) if rate is not None else None])
        if rate is not None:
            rates.append(rate)
    gap = max(rates) - min(rates) if len(rates) > 1 else None
    return [rows, str(gap) if gap is not None else None, gap > threshold if gap is not None else None]


def redact_for_demo(record):
    return {key: record[key] for key in ("topic", "date") if key in record}


def citation_status(citation, catalog):
    item = catalog.get(citation["id"])
    if item is None:
        return "not_in_catalog"
    return "metadata_matches" if citation["title"] == item["title"] and citation["year"] == item["year"] else "metadata_mismatch"


def exercise(checks, workspace):
    expect = checks.expect
    phrases = ["维修值班岗位只招男性。", "请撤下公告里“只招男性”的限制。",
               "岗位要求会读装配图。", "有照护任务的人一律不安排面试。",
               "女性不适合担任夜班技师。"]
    expect("ai_ethics_text_flags", phrases, "Match explicit rules and preserve quotation and unsupported patterns",
           [["claim_review", "只招男性"], ["context_review", "只招男性"], ["no_match", None],
            ["no_match", None], ["claim_review", "不适合担任夜班技师"]], [scan(text) for text in phrases])
    neutral = "两位女性技师共同审核了方案。"
    expect("ai_ethics_neutral", neutral, "Read a neutral reference to a group and occupation",
           ["no_match", None], scan(neutral))

    def samples(a, b):
        return [("甲", outcome) for outcome in a] + [("乙", outcome) for outcome in b]

    gap = samples(["pass"] * 4 + ["reject"], ["pass"] + ["reject"] * 4)
    boundary = samples(["pass"] * 3 + ["reject"] * 2, ["pass"] * 2 + ["reject"] * 3)
    missing = samples(["reject"], [])
    threshold = Fraction(1, 5)
    expect("ai_ethics_group_gap", gap, "Calculate exact rates, denominators and a strict demonstration threshold",
           [[["甲", 4, 5, "4/5"], ["乙", 1, 5, "1/5"]], "3/5", True],
           compare_groups(gap, ["甲", "乙"], threshold))
    expect("ai_ethics_group_boundary", boundary, "Check equality at the 20 percentage point demonstration threshold",
           [[["甲", 3, 5, "3/5"], ["乙", 2, 5, "2/5"]], "1/5", False],
           compare_groups(boundary, ["甲", "乙"], threshold))
    expect("ai_ethics_group_missing", missing, "Distinguish zero passes from no observations",
           [[["甲", 0, 1, "0"], ["乙", 0, 0, None]], None, None],
           compare_groups(missing, ["甲", "乙"], threshold))
    try:
        compare_groups([("甲", "unknown")], ["甲", "乙"], threshold)
    except ValueError as exc:
        failure = str(exc)
    else:
        failure = None
    expect("ai_ethics_group_input_error", "unknown", "Refuse unsupported outcome values instead of counting them as rejects",
           "unknown group or outcome", failure)

    record = {"topic": "照明维护", "date": "演示日", "name": "合成姓名", "account": "合成账号", "memo": "合成内部说明"}
    expect("ai_ethics_minimize", record, "Build a new object using only named fields",
           [{"topic": "照明维护", "date": "演示日"}, 5], [redact_for_demo(record), len(record)])
    catalog = {"demo-1": {"title": "本站模拟观测记录", "year": 2026}}
    refs = [{"id": "demo-1", "title": "本站模拟观测记录", "year": 2026},
            {"id": "demo-1", "title": "本站模拟观测记录", "year": 2024},
            {"id": "demo-2", "title": "虚构观测报告", "year": 2026}]
    expect("ai_ethics_citation", refs, "Compare reference ID and metadata with a closed local catalog",
           ["metadata_matches", "metadata_mismatch", "not_in_catalog"],
           [citation_status(item, catalog) for item in refs])
    original = b"local sample revision A"
    changed = b"local sample revision B"
    known = sha256(original).hexdigest()
    expect("ai_ethics_content_bytes", ["original", "edited"], "Compare file bytes against a known digest",
           [True, False], [sha256(content).hexdigest() == known for content in (original, changed)])


if __name__ == "__main__":
    run_exercise(exercise)
本例需在 Python 3.12.14 标准库,固定虚构文本、通过结果、记录和文件。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Python 3.12.14 标准库,固定虚构文本、通过结果、记录和文件。

入口文件:projects/ai-ethics/ethics_lab.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 ethics_lab.py,或下载右侧课程工程包。
  2. 确认本地已准备 Python 3.12.14 标准库,固定虚构文本、通过结果、记录和文件。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

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

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

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

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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