少样本提示:给哪些例子,按什么顺序?
Few-shot prompting
枚举示例顺序,分开任务证据、近因效应和标签偏差。
few-shot-prompting例子没有换,答案却变了
拿两个负类、两个正类示例,先把正类放最后,再反转顺序。若方法更重视靠后的示例,即使四对输入输出完全相同,也可能改变预测。因此“用了四个例子”没有完整描述实验。
少样本提示把少量示范放在输入中。Brown等人第2节的定义不让这些示例触发模型权重更新,但上下文仍会消耗计算。少样本提示是组织上下文学习的一种方式;模型如何从上下文适应任务,与实践中如何挑选示例,是不同问题。
本文使用固定的二分类核模型,显式编入近因效应,从而枚举四个示例的全部24种顺序。概率不由语言模型生成,近因参数也没有拟合论文实测。
指定配对、次序和答案词表
设候选答案是一个有限集合。直接分类设置根据有序示例,选择概率最高的答案:
一个标签可能包含多个词元,其序列概率相乘,在对数空间中则相加:
所以分词、标签拼写、答案终止方式及是否按长度归一,都属于评测规格。只比较首词元通常不等价于比较完整标签。程序使用整数类别ID,跳过分词,展示其他影响而不冒称模拟这一因素。
选择与任务相关、配对正确、预测时可获得且与最终评测分离的示例,检查是否覆盖必要类别和失败情况。四个几乎相同的正类例子,与平衡集合提供的信息不同。增加数量可能有用,也可能占用上下文或放大误导模式;数量本身不能证明质量。
原创分类器为每个标量示例分配高斯相似度,再乘近因因子。i从1数到k:
Tau用输入单位控制相似度宽度;gamma=1关闭近因加权,较小gamma降低早期示例影响。这是明确的建模选择,不是断言Transformer注意力遵循此式。
在各类别证据上加正伪计数alpha乘固定类别先验pi,再归一化:
正先验防止零分,包括没有示例或相似度下溢的情况。没有示例时输出恰好是pi。Gamma=1时,数学求和不受次序影响;gamma小于1时,各类别可能获得不同的总近因权重。
Zhao等人第5节用无内容输入估计提示造成的标签偏好。为展示决策修正,本例query=None把全部相似度设为1,但保留近因、标签和先验。查询概率除以该基线,再归一化比值:
所有基线分量必须为正。基线中稀少的标签被提升;基线不合适,也可能提升错误答案。这不构成置信度校准的证明。还要分清程序显示的概率与论文公式:Zhao的公式1对缩放后的概率做softmax,预测时取argmax。零偏置、对角缩放取基线倒数时:
两种变换都对r单调,因此最大类别相同,具体概率却不同。若p=(0.6,0.4)、b=(0.8,0.2),本例按比值归一的结果是(3/11,8/11),不能把它写成论文softmax所得概率。
固定查询集后,计算每种排列的准确率,同时报告范围与均值:
四条互不相同的示例记录有24种排列。程序通过argmax把类别分数平局判给类别0;在无内容或完全平局时,这一约定会影响结果。
把所有顺序都试一遍
完整程序使用Python3.12和NumPy1.26.4。负类示例位于−1、−0.7,正类位于0.7、1;查询为−1、−0.5、0.5、1。先验为(0.2,0.8),带宽0.8,先验伪计数0.5。这些常量是为了显露机制而设定的原创条件。
"""A fixed kernel classifier with authored recency and label priors, not an LM."""
import itertools,json,math
import numpy as np
def distribution(examples,query,gamma=1.0,bandwidth=.8,alpha=.5,prior=(.2,.8)):
for value in [gamma,bandwidth,alpha]:
if isinstance(value,bool) or not math.isfinite(value):raise ValueError('finite parameters required')
if not 0<gamma<=1 or bandwidth<=0 or alpha<=0:raise ValueError('positive scale and gamma in(0,1] required')
prior=np.asarray(prior,dtype=float)
if prior.shape!=(2,) or not np.isfinite(prior).all() or np.any(prior<=0) or not np.isclose(prior.sum(),1):raise ValueError('positive normalized binary prior required')
if query is not None and (isinstance(query,bool) or not math.isfinite(query) or abs(query)>100):raise ValueError('bounded query required')
if len(examples)>100:raise ValueError('at most100 examples')
scores=alpha*prior.copy()
for i,(x,y) in enumerate(examples):
if isinstance(x,bool) or not math.isfinite(x) or abs(x)>100 or type(y) is not int or y not in [0,1]:raise ValueError('finite scalar and binary label required')
similarity=1.0 if query is None else math.exp(-.5*((query-x)/bandwidth)**2)
scores[y]+=gamma**(len(examples)-1-i)*similarity
return scores/scores.sum()
def normalized_ratio(probability,baseline):
p=np.asarray(probability,dtype=float);b=np.asarray(baseline,dtype=float)
if p.shape!=(2,) or b.shape!=(2,) or not np.isfinite(p).all() or not np.isfinite(b).all() or np.any(p<0) or np.any(b<=0) or not np.isclose(p.sum(),1) or not np.isclose(b.sum(),1):raise ValueError('normalized binary distributions; positive baseline required')
ratio=p/b
return ratio/ratio.sum()
def accuracy(examples,queries,truth,gamma):
raw=[];corrected=[];baseline=distribution(examples,None,gamma)
for q in queries:
p=distribution(examples,q,gamma);raw.append(int(p.argmax()));corrected.append(int(normalized_ratio(p,baseline).argmax()))
return dict(raw=float(np.mean(np.array(raw)==truth)),ratio=float(np.mean(np.array(corrected)==truth)),baseline=baseline.tolist())
def demo():
examples=[(-1,0),(-.7,0),(.7,1),(1,1)];queries=np.array([-1,-.5,.5,1]);truth=(queries>0).astype(int)
permutations=list(itertools.permutations(examples));rows=[]
for g in [1.0,.5,.2]:
values=[accuracy(e,queries,truth,g) for e in permutations]
rows.append(dict(gamma=g,raw_min=min(v['raw'] for v in values),raw_max=max(v['raw'] for v in values),raw_mean=float(np.mean([v['raw'] for v in values])),ratio_min=min(v['ratio'] for v in values),ratio_max=max(v['ratio'] for v in values),ratio_mean=float(np.mean([v['ratio'] for v in values]))))
positive_only=[(.7,1),(1,1),(.8,1),(.9,1)]
comparison={name:accuracy(e,queries,truth,.5) for name,e in [('balanced',examples),('positive_only',positive_only),('flipped',[(x,1-y) for x,y in examples])]}
return dict(examples=[list(x) for x in examples],queries=queries.tolist(),truth=truth.tolist(),order_results=rows,comparison=comparison,order_count=len(permutations),zero_shot=accuracy([],queries,truth,1.0))
if __name__=='__main__':print(json.dumps(demo(),indent=2,allow_nan=False))
Gamma=1时,每种排列在这四个查询上都得1.0。Gamma=0.5时,原始准确率介于0.5和1.0,均值约0.88542;该条件下比值修正使所有排列达到1.0。Gamma=0.2时,修正后仍介于0.75和1.0,因此修正不是保证。
comparison固定gamma=0.5,再改变示例。所选平衡顺序的原始准确率为0.5,修正后为1.0;四个全正类示例修正后只有0.5;把所有标签翻转,修正后为0.0。模型仍依赖输入输出配对,偏差修正不能凭空补出缺失类别证据,也不能修复每个错标签。
标量输入的单次预测需O(k)运算,使用两个类别累加器。对Q个查询穷举排列需要O(k! Qk),本例k=4才很轻量。更长提示应事先声明抽样顺序集合或受控排序策略,并计入评测成本,不能免费挑出最好顺序后只报其成绩。
限定解释随机标签实验
Min等人第3—4节在分类与多选任务中比较正确标签和随机标签。默认使用16个示例;最大的模型只在较小的六数据集子集上评测。在这些条件下,随机标签的影响经常小于直觉预期;消融也显示模型和任务间存在差异。
这不能证明正确标签永远无关、新造的标签映射总能被恢复,或示例可以任意互换。本例反例让边界具体可见:翻转标签会摧毁该分类器表现。这不否定Min的测量,而是说明必须保留其实验范围。
核模型在gamma=1时对排列不敏感,且只有两个数字标签。语言模型可能更复杂地响应格式、措辞、语义关系、词元频率和位置。应检查新输入、类别平衡、矛盾示例和领域变化,不把一个有利顺序写成通用提示配方。
只改变示例的一部分
- 为什么gamma=1能消除本程序的顺序影响?
答案:每个近因因子都变为1,类别分数成为对同一组示例的普通求和。除了浮点舍入,重排不改变总和。
- p=(0.6,0.4)、b=(0.8,0.2),比值修正是多少?它是论文的softmax分布吗?
答案:比值为0.75和2,归一后为3/11和8/11。最大类别与对这些比值做softmax相同,概率值却不同。
- 为什么在最终测试集上挑24种顺序中的最好者,会使比较有偏?
答案:测试集已变成选择集。应在独立开发数据上选排序规则,冻结后只在未碰过的样本上评测,并报告候选顺序的评测成本。
- 正确/随机标签的实验结果,是否支持在陌生任务里故意损坏全部标签?
答案:不支持。它们针对特定模型和任务集合。本例翻转标签得0.0,说明标签依赖确实可能存在。应保留正确示例,并测试实际任务。
三个问题,对应三处资料
Brown第2节定义评测设置。Min第3—4节检验特定条件下哪些示例信息有用。Zhao第5节用无内容基线改变标签决策分数,并明确区别于置信度校准。提示选择方法见提示工程,生成后的答案投票见自一致性。
先判断,再看解释
随机标签的某项结果能证明正确示例永远不重要吗?
学习目标
- 明确示例、次序、答案词表及对照成本。
- 运行有界原创示例并解释失败情况。
先修与延伸
查看知识关联图 →参考文献
- Language Models are Few-Shot Learners — arXiv v4
Tom B. Brown; Benjamin Mann; Nick Ryder and coauthors · 2020 - Rethinking the Role of Demonstrations: What Makes In-Context Learning Work? — v1
Sewon Min; Xinxi Lyu; Ari Holtzman; Mikel Artetxe; Mike Lewis; Hannaneh Hajishirzi; Luke Zettlemoyer · 2022 - Calibrate Before Use: Improving Few-Shot Performance of Language Models — v1
Tony Z. Zhao; Eric Wallace; Shi Feng; Dan Klein; Sameer Singh · 2021
版本1 · 编写状态: 已完成记录中的技术复核
查看技术检查记录(AI)
Codex · 2026-09-20 · Single AI author. New scoped reading: viewed PDF6/7 section2 and Figure2.1, read PDF3 Figure1.1 text. No task-specific gradient update; existing Source object preserved. Viewed PDF3/4:26 datasets,16 default demonstrations, reduced six-dataset evaluation for largest models, gold/random labels and ablations. Not a claim that labels never matter. Viewed PDF5 section5 and footnotes: content-free inputs, diagonal probability scaling, softmax versus argmax, and distinction from confidence calibration. Do not implement the suspect zero-W generation footnote. 7 paired equations and four explained exercises. All24 orders, prior and recency counts, ratio/softmax rank versus probability distinction, wrong labels and incomplete class evidence checked. Empirical paper scope preserved.
- 核全部24排列、先验近因计数、比值与softmax排名相同但概率不同、错标签和缺类证据;保留论文实证范围。
- 每题四张计算SVG,9数值/几何与24响应式组合通过;实看8张最终图,完整页面验收另记。
- 最终页面发现英文数字边界缺空格,仅插入清单中的空格;公式、程序、行内字面值、链接及元数据不变。原冻结稿保留,精确插入回归及页面重检另记。
核对的来源位置:
- Language Models are Few-Shot Learners — arXiv v4 · New scoped reading: viewed PDF6/7 section2 and Figure2.1, read PDF3 Figure1.1 text. No task-specific gradient update; existing Source object preserved.
- Rethinking the Role of Demonstrations: What Makes In-Context Learning Work? — v1 · Viewed PDF3/4:26 datasets,16 default demonstrations, reduced six-dataset evaluation for largest models, gold/random labels and ablations. Not a claim that labels never matter.
- Calibrate Before Use: Improving Few-Shot Performance of Language Models — v1 · Viewed PDF5 section5 and footnotes: content-free inputs, diagonal probability scaling, softmax versus argmax, and distinction from confidence calibration. Do not implement the suspect zero-W generation footnote.
相关主题