AI Wiki中文/EN

问答系统:找到相关网页,还没有找到答案

Question answering

搭建小型检索—阅读流程,返回精确支持文本,并分别测量检索、回答质量与拒答。

本页目录直觉理解数学与方法代码实现局限与误解实验与练习研究脉络

网页可以重复问题里的词,却始终没有回答问题

有人问:“River Hall在哪里?”一页虚构档案反复提到“River Hall”,却没有当前位置;另一页短得多,只写“River Hall is in Cedar.”。前者可能看起来非常相关,后一句才提供所需证据。

问答必须在明确的知识边界内,把问题连接到合适答案。系统从给定段落、索引文档集、结构化记录,还是模型参数中回答?任务需要短事实、列表、计算结果,还是解释?这些选择决定什么算证据、评测应接受什么。

对于小型服务目录,在已批准记录中精确查找,是有用的非学习基线。它能返回已知位置及记录ID,不支持的问题转交其他流程。当信息散落在文章中、精确查找覆盖率不足时,检索问答才有明确用途。测试集应包含答案缺失、陈旧陈述和冲突记录,而不只有容易匹配的样本。

DrQA明确区分开放域事实问答中的文档检索与阅读抽取,这也是本篇采用的工程思路。原系统把哈希bigram TF-IDF检索与循环网络读者结合;本程序使用普通unigram向量及刻意限定的规则读者。检索器与读者,第3.1—3.2节

重复名称的干扰文档排在支持事实之前。增加检索深度改善了这个小例子的支持召回,已回答准确率却不变;返回证据保留源文区间。
重复名称的干扰文档排在支持事实之前。增加检索深度改善了这个小例子的支持召回,已回答准确率却不变;返回证据保留源文区间。

检索、阅读和证据,分别承诺了什么

若系统把一个段落d作为答案a的潜在支持,可以采用混合模型:

P(a∣q,C)=∑d∈CP(d∣q,C)P(a∣q,d).P(a\mid q,C)=\sum_{d\in C}P(d\mid q,C)P(a\mid q,d).

q为问题,C为文档集合。这个公式假设选定段落与问题足以供读者作答,不需要联合多个段落;它是建模选择,不是所有问答的通用描述。下面的余弦分数不是归一化段落概率,不能直接填入该式当作概率使用。

原型词表来自文档集合,把英文词转小写并移除一个明确的小型停用词表。设文档数D、文档频率df-w、原始计数tf-dw,使用平滑权重:

idf⁡(w)=log⁡D+1df⁡(w)+1+1,vdw=tf⁡dwidf⁡(w).\operatorname{idf}(w)=\log\frac{D+1}{\operatorname{df}(w)+1}+1,\qquad v_{dw}=\operatorname{tf}_{dw}\operatorname{idf}(w).

问题使用同一词表和IDF,再比较L2归一化向量:

s(q,d)=vqTvd∥vq∥2∥vd∥2.s(q,d)=\frac{v_q^Tv_d}{\|v_q\|_2\|v_d\|_2}.

零查询向量不产生结果。分数排序有正重合的文档,同分按文档ID决定顺序。词语重复、词表不匹配和无关上下文都可能改变排序,却不改变段落是否真正支持答案。玩具语料故意包含这样的干扰项。

读者只接受Where is NAME?问句和完整源句NAME is in PLACE.。其他主体、过去时、否定及条件句不符合明确语法,因此被拒绝。这是受限事实读取约定,不是通用语言理解。程序返回精确原句和字符区间,便于消费者核对实际读到了什么。

没有匹配支持时,应返回“这些检索文档中没有找到支持的答案”,而不是“任何地方都不存在答案”。匹配证据若提供不同位置,应报告冲突,不能悄悄挑一个。不可回答的阅读任务正是要包含“看起来像答案,却没有由篇章支持”的候选。任务构造

设可回答问题集合为Q-plus,每题标注支持文档为E-q,前k检索结果为R-k(q),支持召回定义为:

Recall⁡support@k=1∣Q+∣∑q∈Q+1[Rk(q)∩Eq≠∅].\operatorname{Recall}_{\mathrm{support}}@k=\frac1{|Q_+|}\sum_{q\in Q_+}\mathbf1[R_k(q)\cap E_q\ne\varnothing].

指标针对给定支持标注。若标注遗漏有效支持文档,检索到它也可能被记成失败。在支持标注完整、且正确答案必须使用检索证据的前提下,可回答问题上的有依据准确率受到上界:

Accuracy⁡grounded,Q+≤Recall⁡support@k.\operatorname{Accuracy}_{\mathrm{grounded},Q_+}\le\operatorname{Recall}_{\mathrm{support}}@k.

这些条件不可省略。允许从其他知识猜答案的系统,可以不检索标注证据就输出正确字符串,却没有证明这条流程提供了依据。答案正确性与证据有效性应分别报告。

拒答还会改变分母。若测试题数为M,实际回答A题,则:

coverage⁡=A/M,accuracy⁡answered=correct answered questionsA.\operatorname{coverage}=A/M,\qquad \operatorname{accuracy}_{\mathrm{answered}}=\frac{\text{correct answered questions}}{A}.

A=0时第二项无定义;没有可回答问题时,支持召回无定义。总体精确正确率可以给标注无答案题上的适当拒答记正确,但不支持的问句格式仍是读者能力限制,不能证明世界中没有相应事实。

让证据始终跟着答案

完整原创程序使用Python 3.12和NumPy 1.26.4,四篇文档与三道测试题全部虚构。代码把输入文档复制进索引,证据偏移按Python Unicode字符计数,并保留冲突证据。

"""Original tiny retrieve-then-read QA pipeline with auditable evidence.

The reader accepts only 'Where is NAME?' and 'NAME is in PLACE.' facts.
TF-IDF cosine scores are retrieval scores, not answer confidence probabilities.
No real Wikipedia corpus, neural reader or DrQA benchmark is reproduced.
"""
from collections import Counter
import json
import math
import re
import numpy as np

STOP={'where','is','in','the','a','an'}


def tokens(s):
    if not isinstance(s,str) or len(s)>20000:raise ValueError('Use a bounded English teaching string')
    return [x for x in re.findall('[a-z]+',s.lower()) if x not in STOP]


def index(documents):
    docs=[dict(d) for d in documents]
    if not 1<=len(docs)<=64:raise ValueError('Use1..64 documents')
    if any(set(d)!={'id','text'} or not isinstance(d['id'],str) or not d['id'] for d in docs):raise ValueError('Documents need a nonempty ID and text')
    if len({d['id'] for d in docs})!=len(docs):raise ValueError('Document IDs must be unique')
    counts=[Counter(tokens(d['text'])) for d in docs];vocabulary=sorted(set().union(*(set(c) for c in counts)))
    if len(vocabulary)>2048:raise ValueError('Teaching vocabulary cap is2048')
    df=np.array([sum(word in c for c in counts) for word in vocabulary])
    idf=np.log((len(docs)+1)/(df+1))+1
    vectors=np.array([[c[word] for word in vocabulary] for c in counts],dtype=float)*idf
    lengths=np.linalg.norm(vectors,axis=1,keepdims=True)
    vectors=np.divide(vectors,lengths,out=np.zeros_like(vectors),where=lengths>0)
    return dict(documents=docs,vocabulary=vocabulary,idf=idf,vectors=vectors)


def retrieve(store,question,k=2):
    if isinstance(k,bool) or not isinstance(k,int) or not 1<=k<=64:raise ValueError('Use retrieval depth1..64')
    counts=Counter(tokens(question));q=np.array([counts[w] for w in store['vocabulary']],float)*store['idf']
    norm=np.linalg.norm(q)
    if norm==0:return []
    scores=store['vectors']@(q/norm)
    order=sorted(range(len(scores)),key=lambda i:(-float(scores[i]),store['documents'][i]['id']))
    return [dict(document=store['documents'][i],score=float(scores[i])) for i in order[:k] if scores[i]>0]


def read_fact(document,entity):
    results=[];text=document['text']
    for segment in re.finditer(r'[^.!?]+[.!?]?',text):
        raw=segment.group();sentence=raw.strip()
        match=re.fullmatch(r'([A-Za-z]+(?: [A-Za-z]+)*) is in ([A-Za-z]+(?: [A-Za-z]+)*)\.',sentence)
        if match and match[1].lower()==entity.lower():
            start=segment.start()+len(raw)-len(raw.lstrip());end=start+len(sentence)
            results.append(dict(answer=match[2],document_id=document['id'],start=start,end=end,quote=text[start:end]))
    return results


def answer(store,question,k=2):
    tokens(question)
    parsed=re.fullmatch(r'Where is ([A-Za-z]+(?: [A-Za-z]+)*)\?',question)
    if not parsed:return dict(answer=None,status='unsupported_question',retrieved=[],evidence=[])
    hits=retrieve(store,question,k);evidence=[e for hit in hits for e in read_fact(hit['document'],parsed[1])]
    values={e['answer'].lower() for e in evidence}
    if not values:status='no_supported_answer';value=None
    elif len(values)>1:status='conflicting_evidence';value=None
    else:status='answered';value=evidence[0]['answer']
    return dict(answer=value,status=status,retrieved=[dict(id=h['document']['id'],score=h['score']) for h in hits],evidence=evidence)


def evaluate(store,examples,k):
    examples=list(examples)
    if not examples:raise ValueError('Need at least one evaluation example')
    rows=[];answerable=0;retrieved_support=0;answered=0;correct=0;answerable_correct=0
    for ex in examples:
        prediction=answer(store,ex['question'],k);pred=prediction['answer']
        gold=ex['answers'];has_answer=bool(gold);answerable+=has_answer
        ids={d['id'] for d in prediction['retrieved']};support=bool(ids&set(ex['support_ids']))
        retrieved_support+=has_answer and support
        ok=pred.lower() in {s.lower() for s in gold} if pred is not None else not has_answer
        answered+=pred is not None;correct+=ok;answerable_correct+=has_answer and ok
        rows.append(dict(question=ex['question'],prediction=prediction,correct=ok,support_retrieved=support))
    return dict(rows=rows,total=len(rows),answerable=answerable,answered=answered,correct=correct,
        accuracy=correct/len(rows),coverage=answered/len(rows),
        accuracy_when_answered=sum(r['correct'] and r['prediction']['answer'] is not None for r in rows)/answered if answered else None,
        support_recall= retrieved_support/answerable if answerable else None,
        answerable_accuracy=answerable_correct/answerable if answerable else None)


def demo():
    docs=[dict(id='river-no-answer',text=('River Hall '*20)+'has historical notes but no current location.'),
          dict(id='river-current',text='River Hall is in Cedar.'),
          dict(id='museum-current',text='Cedar Museum is in Aspen.'),
          dict(id='river-past',text='River Hall was in Birch.')]
    store=index(docs)
    examples=[dict(question='Where is River Hall?',answers=['Cedar'],support_ids=['river-current']),
              dict(question='Where is Cedar Museum?',answers=['Aspen'],support_ids=['museum-current']),
              dict(question='Where is Stone Lab?',answers=[],support_ids=[])]
    return dict(documents=docs,vocabulary=store['vocabulary'],idf=store['idf'].tolist(),
        depth1=evaluate(store,examples,1),depth2=evaluate(store,examples,2),
        conditions='Invented documents and explicit fact grammar; support recall concerns supplied annotations; no calibrated answer probability')


if __name__=='__main__':print(json.dumps(demo(),indent=2,allow_nan=False))

k=1时,River Hall干扰文档排第一,读者找不到受支持位置;另一道可回答题成功,未知地点则不回答。支持召回为1/2,总体正确率2/3,回答覆盖率1/3。k=2时两个位置都找到了支持:支持召回1、总体正确率1、覆盖率2/3。两种深度的已回答题全对,所以只看已回答准确率会隐藏漏答问题。

检查手算一个TF-IDF/余弦例子,核对稳定同分与原文偏移,并覆盖词表无匹配、不支持语法、过去/否定/条件句和冲突位置。这证明明确语法下的行为,没有证明读者识别所有改写,或知道旧记录今天是否仍有效。

设文档数D、词表V,稠密实现建表为O(DV加词元化工作),存储O(DV)数值及原文,检索为O(DV+D log D)。倒排索引是扩展方向,本例未实现。上限为64篇、2,048词表项、每条教学字符串20,000字符;读者成本与扫描的检索文本长度成正比。

用能暴露故障环节的协议评测

冻结文档快照,划分评测问题时避免近重复记录或问题泄漏到调参过程。说明是否接受答案别名、多个有效段落、多个答案或拒答。答案可能碰巧拼对,却依据错误;正确来源也可能被引用得不完整。应同时检查返回字符串和上下文中的证据。

增加k会给读者更多候选,可能增加阅读工作,也可能带入冲突或干扰。本例检索器在两个深度都计算并排序全部文档分数,k只改变返回的子集;最终答案不保证更好。生产系统需要明确来源、时效、冲突和不支持问型的处理政策。在同一集合与解码预算下,同时测量延迟、每题工作量、检索与答案指标。

学习式读者用问题条件模型替代窄语法,生成式回答还可能整合多个来源,两者都会扩大需要验证的行为范围。检索相似度或归一化模型输出,不自动成为经过校准的事实正确概率。本原型没有这种置信声明。

官方DrQA仓库对检索器、读者与pipeline的拆分,可作为实现组织参考。这里引用固定快照,核读了README和软件许可,但没有复制或执行上游代码、数据或权重。官方实现结构

找出答案在哪个环节丢了

  1. 排第一的文档多次提到River Hall,却没有位置。高检索相似度足以返回答案吗?

答案:不足。相似度提供候选,不提供受支持的位置。读者必须找到适用证据,或者在这个检索集合内拒答。

  1. k=1时,两道可回答题中只有一道找回支持,第三道题正确拒答。例子中的支持召回与总体正确率是多少?

答案:支持召回1/2。若有支持的答案正确,总体正确率为2/3。两者分母不同,纳入的任务也不同。

  1. 两条检索记录把River Hall放在不同地点,程序怎么处理,为什么?

答案:返回conflicting_evidence,不选答案,并保留两条证据。语法没有判定哪个位置更新的规则;直接挑第一条会隐藏未解决的冲突。

  1. 系统在十题中只回答一道容易题且答对,已回答准确率为1,能否证明问答表现良好?

答案:不能,覆盖率只有1/10。要同时报告两项,并区分适当拒答与漏掉可回答题。一题都不答时,已回答准确率无定义,而不是完美。

比较系统前,先比较任务边界

DrQA研究集合规模的检索与阅读,不可回答SQuAD论文则说明貌似合理的片段仍可能不是有效答案,二者澄清不同故障位置。官方实现是组织参考,本篇的unigram索引、语法、语料及测量为原创小例子,没有复现论文基准分数。

先判断,再看解释

k=1时已回答准确率为1,支持召回只有1/2,缺少什么?

选择一个答案

学习目标

  • 区分检索相关性和答案支持。
  • 返回精确证据并保留冲突陈述。
  • 计算支持召回、回答覆盖与已回答准确率。
  • 说明规则读者的语法和知识边界。

先修与延伸

查看知识关联图 →

参考文献

  1. Reading Wikipedia to Answer Open-Domain Questions
    Danqi Chen, Adam Fisch, Jason Weston, Antoine Bordes · 2017
  2. Know What You Don’t Know: Unanswerable Questions for SQuAD
    Pranav Rajpurkar, Robin Jia, Percy Liang · 2018
  3. DrQA official repository: pinned README and software license
    Facebook Research / DrQA contributors · 2021

版本1 · 编写状态: 已完成记录中的技术复核

查看技术检查记录(AI)

Codex · 2026-09-12 · Single AI author checked knowledge boundaries, non-learning lookup baseline, retrieval/reading split and scoped DrQA/unanswerable-task evidence. Six paired equations and four explained exercises verified, including mixture assumptions, TF-IDF hand case, conditional support-recall ceiling, denominator/coverage distinctions, exact source intervals and conflict abstention. The strict location grammar is original and does not reproduce DrQA or calibrated confidence.

  • 单AI作者核知识边界、非学习查表基线、检索/阅读分工与限定DrQA/无答案任务证据。六公式四解释练习包含混合假设、TF-IDF手算、有条件的支持召回上界、分母/覆盖区别、精确字符证据与冲突拒答。位置语法原创,不冒充DrQA复现或校准信心。
  • 四张计算SVG绑定真实双语程序;本组八项数值/编码检查、24组语言/宽度及四字体检查通过,AI作者实际查看八张截图。冻结前检查普通正文AST;完整文章页面验收另记,不称人工同行审校。

核对的来源位置:

相关主题

没有匹配结果,试试英文名或缩写。

已显示 0 条结果

将整个查询放入双引号,可按短语匹配。