AI幻觉问题深度解析:成因、缓解与检测技术
幻觉:大模型的阿喀琉斯之踵 大模型生成流畅、自信但不正确的文本——这就是幻觉。它不是简单的"错误",而是模型对不存在事实的"确信"。理解幻觉的成因是构建可靠AI系统的前提。 幻觉的分类 事实性幻觉 vs 忠实性幻觉 HALLUCINATION_TYPES = { "事实性幻觉": { "description": "生成与客观事实不符的内容", "subtypes": { "实体幻觉": "编造不存在的人名、地名、机构", "关系幻觉": "错误描述实体间的关系", "数字幻觉": "编造不准确的统计数据", "时间幻觉": "错误的时间线", "来源幻觉": "编造不存在的引用来源" }, "example": "爱因斯坦于1923年获得诺贝尔物理学奖" # 实际是1921年 }, "忠实性幻觉": { "description": "生成与输入/上下文矛盾的内容", "subtypes": { "指令违背": "没有遵循用户指令", "上下文矛盾": "与给定上下文矛盾", "逻辑矛盾": "自身前后矛盾", "计算错误": "推理过程中计算错误" }, "example": "用户说'不要用Python',模型回复用Python实现" } } 幻觉的成因 1. 训练数据问题 class DataInducedHallucination: def __init__(self): self.causes = { "数据噪声": { "description": "训练数据本身包含错误信息", "example": "维基百科中的错误事实被学习", "mitigation": "数据清洗和事实核查" }, "知识冲突": { "description": "不同数据源对同一事实有不同表述", "example": "不同网站给出不同的历史日期", "mitigation": "可信度排序和数据源标注" }, "长尾知识不足": { "description": "小众领域数据不足,模型靠猜", "example": "冷门历史事件的细节", "mitigation": "RAG增强" }, "知识过时": { "description": "训练数据有时效性", "example": "模型不知道最新的公司财务数据", "mitigation": "实时检索" } } 2. 解码策略影响 class DecodingInducedHallucination: def analyze(self, model, prompt, strategies): """分析不同解码策略的幻觉率""" results = {} for strategy_name, params in strategies.items(): hallucination_count = 0 for _ in range(100): # 100次采样 response = model.generate(prompt, **params) if self._is_hallucination(response, prompt): hallucination_count += 1 results[strategy_name] = { "hallucination_rate": hallucination_count / 100, "params": params } return results # 典型结果: # greedy (temperature=0): 15% 幻觉率 # temperature=0.3: 18% 幻觉率 # temperature=0.7: 25% 幻觉率 # temperature=1.0: 35% 幻觉率 # top_p=0.9: 22% 幻觉率 # top_k=50: 28% 幻觉率 3. 模型知识表示问题 class KnowledgeRepresentationIssue: """ 模型的知识存储在参数中,不是数据库查询。 这意味着: 1. 知识边界模糊(不知道自己不知道什么) 2. 知识提取不可靠(同样的知识不同问法结果不同) 3. 知识干扰(相关知识互相干扰) """ def measure_knowledge_boundary(self, model, questions): """测量模型的知识边界感知""" results = [] for q in questions: # 让模型评估自己的确定性 response = model.generate(f"{q}\n\n你对答案的确定程度?(1-10)") # 验证答案正确性 is_correct = verify_answer(q, response) confidence = extract_confidence(response) results.append({ "question": q, "correct": is_correct, "confidence": confidence, "calibrated": (is_correct and confidence > 7) or (not is_correct and confidence < 4) }) calibration_rate = sum(r["calibrated"] for r in results) / len(results) return { "calibration_rate": calibration_rate, "over_confident": sum(1 for r in results if not r["correct"] and r["confidence"] > 7), "under_confident": sum(1 for r in results if r["correct"] and r["confidence"] < 4) } 幻觉缓解技术 训练阶段缓解 RLHF中的真实性奖励: ...