什么是少样本提示?
少样本提示是一种技术:向语言模型提供少量示例,引导其对特定任务生成响应。该方法介于零样本学习(不给任何示例)与完全监督的微调(需要大量标注数据)之间。关于这一机器学习技术的详细解释,请参见有关少样本学习的博文。
换言之,少样本提示是在提示词本身中给语言模型提供少量示范或示例。这些示例起到引导作用,展示模型应如何处理并回应某类任务或问题。当您提供这些示例时,本质上是在对模型说:“在类似情境中请按这种方式作答。”
我们来看一个例子。
假设我们希望模型对影评进行情感分类。一个少样本提示可能如下:
提示:
Classify the sentiment of the third movie review. Use the information from the first two examples:Review: "This movie was a waste of time."Sentiment: NegativeReview: "I couldn't stop laughing throughout the film!"Sentiment: PositiveReview: "The special effects were amazing, but the plot was confusing."Sentiment:```markdownIf we input this prompt to the LLM, and if it understands the task correctly, it will output:```markdownSentiment: Mixed在这个示例中,LLM 利用提示中的示例来理解如何对第三条影评进行情感分类,并据此生成输出。
少样本提示之所以重要,是因为它让 LLM 更实用、更易用。首先,它节省时间与精力,因为您无需完全重训模型或收集海量数据。
其次,它非常灵活——只需更换您提供的示例,就能快速将模型适配到不同任务。第三,与毫无引导地让模型直接执行任务相比,它往往能在特定或复杂任务上带来更好的表现。这种方法也让更多人能够使用强大的 AI 工具,而不仅仅是拥有大量资源的技术专家。
少样本提示如何工作
少样本提示的核心在于:在提示中向 LLM 提供一小组相关的示例或示范。这些示例为模型提供指引,说明应如何处理并回应某类任务或问题。示范通常具有以下结构:
- 输入-输出对: 每个示范通常包含一个输入(如问题或一段文本)及其对应输出(期望的回应或解答)。
- 格式一致性: 示范保持一致的格式,有助于模型识别应当遵循的模式。
- 任务相关性: 提供的示例需与当前任务直接相关,展示所需的特定技能或知识。
例如,如果我们希望模型生成押韵的对句,一个少样本提示可能如下:
Generate a rhyming couplet about a tree:Input: "cat"Output: The curious cat, so sleek and fat, Curled up cozy on the welcome mat.Input: "sky"Output: Look up high into the endless sky, Where birds and clouds go drifting by.Input: "tree"Output:当看到这些示范时,语言模型会进行一种通常称为“上下文学习”(in-context learning)或“以例为师”的过程。其工作方式如下:
- 模式识别: 模型分析所给示例,识别输入如何被转换为输出的模式。
- 任务推断: 基于这些模式,模型推断出它被要求执行的任务性质。
- 泛化: 随后,模型尝试从给定示例泛化到新的、未见过的输入。
- 应用: 最后,模型将所学模式应用于提示末尾提供的新输入。
![]()
通过这一过程,模型无需更改其底层参数,就能将自身知识与能力适配到特定任务。
需要注意的是,少样本提示的效果会因任务复杂度、示例的质量与相关性、以及底层语言模型的能力等因素而异。但在有效使用时,少样本提示能让语言模型以令人惊讶的准确性与灵活性胜任多种不同任务。
少样本提示的优势
少样本提示有不少好处。我们来看看这种方法为何如此有用。
性能提升
少样本提示最显著的优势之一,是与零样本方法相比,性能有大幅提升。
- 准确度更高: 通过提供相关示例,少样本提示帮助模型更好地理解特定任务,从而输出更准确的结果。
- 相关性更强: 示例引导模型产出更贴近预期目标的响应。
- 任务定制化适配: 少样本提示帮助 LLM 将既有知识用于理解并执行新的、具体的任务。
例如,设想我们希望模型以特定的语气和格式生成产品描述。
Generate product descriptions:Product: Wireless EarbudsDescription: Immerse yourself in crystal-clear audio with our sleek wireless earbuds. Featuring noise-cancellation technology and a comfortable fit, these earbuds are perfect for music lovers on the go.Product: Smart WatchDescription: Stay connected and track your fitness with our advanced smart watch. With heart rate monitoring, GPS, and a vibrant touch screen, it's your perfect companion for an active lifestyle.Product: Ergonomic Office ChairDescription:借助这些示例,与零样本方法可能生成更通用或不够聚焦的描述相比,模型更有可能为办公椅生成更相关、风格更合适的描述。
一个可能的输出为:```markdown
Description: Transform your workspace with our state-of-the-art ergonomic office chair. Designed for ultimate comfort and support, this chair features adjustable lumbar support, breathable mesh backrest, and customizable armrests. Whether you're working from home or in a corporate setting, this chair is the perfect blend of style and functionality for the modern professional.
Faster adaptationFew-shot prompting helps the LLM to quickly learn new tasks or topics, making it fast and easy to switch between different jobs.Quick task learning: Models can quickly grasp new tasks with just a handful of examples, allowing for rapid prototyping and testing of new applications.Domain adaptation: It's easy to shift the model's focus to different domains or styles by simply changing the examples in the prompt.Iterative refinement: Users can quickly iterate and refine their prompts based on initial results, leading to a more agile development process.For example, if we wanted to adapt the model to generate different types of poetry, we could quickly switch between haikus, limericks, or sonnets just by changing the examples in our prompt:```markdownGenerate poetry based on the given theme and format.Theme: SpringHaiku: Cherry blossoms bloom Soft petals dance in the breeze Nature awakensTheme: SummerHaiku:Theme: A funny catLimerick: There once was a cat named Lou Who always knew just what to do He'd climb up a tree Then meow with glee And slide down as if on a chuteTheme: A clumsy dogLimerick:一个可能的输出为:
Haiku:Scorching sun aboveCicadas sing endlesslyBeach waves cool bare feetLimerick:There once was a dog quite unsteadyHis paws were not quite readyHe'd trip on his tailKnock over the mailBut his smile kept his owner steady降低数据需求
少样本提示显著减少对大量标注数据的需求,这相较于传统微调方法是一大优势。
- 所需示例极少: 许多任务中,2–5 个示例往往就足以有效引导模型。
- 无需微调: 与传统机器学习方法不同,少样本提示无需更新模型参数,节省算力与时间。
- 可达性更强: 这种方法让高级 NLP 能力更易于被缺乏大型数据集或充足训练资源的用户所用。
少样本提示的应用
少样本提示可应用于众多领域。其灵活高效的特点使其在需要专业知识或创意输出的任务中尤为有用。我们来探索一些重点应用:
复杂推理任务
少样本提示能显著提升 LLM 处理多步推理、逻辑推断或领域专知识题的能力。
来看一个用于医疗诊断任务的少样本提示:
Provide a possible diagnosis and explain your reasoning:Symptoms: Fever, cough, fatigueDiagnosis: Common coldExplanation: The combination of fever, cough, and fatigue is typical of a common cold. No severe symptoms are present, suggesting a mild viral infection.Symptoms: Chest pain, shortness of breath, dizzinessDiagnosis: Possible heart attackExplanation: The combination of chest pain, shortness of breath, and dizziness are warning signs of a possible heart attack. Immediate medical attention is required.Symptoms: Headache, sensitivity to light, nauseaDiagnosis:Explanation: 该提示不仅引导模型给出诊断,还要解释其背后的推理过程,体现复杂的医疗推理。
LLM 将输出:```markdown
Diagnosis: Migraine
Explanation: These symptoms together are typical of a migraine. The headache combined with light sensitivity (photophobia) is a strong indicator of migraine, and nausea often accompanies this condition. While other causes are possible, this combination strongly suggests a migraine headache.
Creative writingFew-shot prompting is particularly effective in guiding LLMs to generate text in specific styles, formats, or genres.Let’s see how to generate movie synopsis in different genres using few-shot prompting:```markdownGenerate movie synopsis:Genre: Sci-FiSynopsis: In a world where dreams can be shared, a skilled "dream thief" is tasked with the impossible: planting an idea in someone's mind. As he delves deeper into the target's subconscious, the lines between reality and dreams blur, threatening to trap him forever.Genre: RomanceSynopsis: A chance encounter on a rainy day in Paris leads two strangers on a whirlwind 24-hour adventure. As they explore the city and each other's hearts, they must decide if their connection is strong enough to overcome the ocean that will separate them come morning.Genre: HorrorSynopsis: 该提示引导模型生成能体现所选题材关键要素与基调的梗概。
输出:
Synopsis: A remote mountain town is plagued by a series of mysterious disappearances. As a skeptical detective investigates, she uncovers an ancient cult that awakens every hundred years to feed on the town's inhabitants. With time running out and the cult's power growing, she must confront her own dark past to save the remaining townspeople and herself from a terrifying fate.代码生成
少样本提示在帮助 LLM 生成符合特定规范、遵循最佳实践或满足特定要求的代码方面非常有用。示例可以演示某种编程语言的正确语法与结构。
下面看看如何用少样本提示生成带有文档字符串与类型注解的 Python 函数:
def calculate_area(length: float, width: float) -> float: """ Calculate the area of a rectangle. Args: length (float): The length of the rectangle. width (float): The width of the rectangle. Returns: float: The area of the rectangle. """ return length * widthdef celsius_to_fahrenheit(celsius: float) -> float: """ Convert temperature from Celsius to Fahrenheit. Args: celsius (float): Temperature in Celsius. Returns: float: Temperature in Fahrenheit. """ return (celsius * 9/5) + 32def calculate_bmi(weight: float, height: float) -> float: """ [Generate a docstring for this function] """ # [Generate the function body]该提示引导模型按照既定模式,生成带有正确类型注解与详细文档字符串的函数。
输出将为:
def calculate_bmi(weight: float, height: float) -> float: """ Calculate the Body Mass Index (BMI) of a person. Args: weight (float): The weight of the person in kilograms. height (float): The height of the person in meters. Returns: float: The calculated BMI value. Note: BMI is calculated as weight (kg) divided by height squared (m^2). This function assumes weight is in kilograms and height is in meters. """ return weight / (height ** 2)少样本提示:挑战与最佳实践
尽管少样本提示在许多情况下表现良好,但也存在自身的挑战。理解这些挑战并遵循最佳实践,有助于最大化提示的有效性并获得更佳结果。
选择有效示例
您选择的示例之质量与相关性,对成功的少样本提示至关重要。建议如下:
- 确保示例与您希望模型执行的任务直接相关。不相关的示例会让模型困惑,导致表现不佳。
- 使用覆盖任务不同方面的多样化示例,帮助模型更好地泛化到新输入。
- 示例应当清晰明了、毫不含糊。避免复杂或晦涩的示例,以免干扰模型。
提示设计
要创建有效的提示,需要仔细考量如何呈现示例以及如何设定任务。这些策略可供参考:
- 为所有示例保持一致的格式,帮助模型识别需要遵循的模式。
- 在提示中提供足够上下文,让任务更清晰。有时一段简短的说明即可为示例搭好舞台。
- 在保证信息充分的前提下尽量简洁。过于复杂的提示会引发混淆。
避免过拟合
少样本提示的风险之一是模型可能对提供的示例过拟合,导致输出与示例过于相似,或无法很好地泛化到新输入。为避免此类情况:
- 使用涵盖不同场景与边界情况的多样化示例,帮助模型学习泛化,而非简单模仿。
- 避免示例数量过多,以免导致过拟合。少而精、精心挑选的示例通常优于大量相似示例。
- 在多种新输入上测试模型表现,确保其具备良好泛化能力,并据此调整示例与提示。
遵循这些最佳实践,能帮助您创建更有效的少样本提示,准确高效地引导模型完成目标任务。

结论
少样本提示是一种技术,帮助 LLM 将其知识应用到特定任务。
它无需大量再训练即可快速适配新任务;通过提供相关示例,提升在复杂任务上的准确性;广泛适用于从推理到创作写作与编码等各个领域,并让高级语言模型更易获取、更具适应性。
然而,其效果取决于示例选择与提示设计的细致程度。示例的质量与相关性对达到最佳表现至关重要。
展望未来,这一方向令人期待。想象一下,系统能够自动挑选最合适的示例,或根据实时表现即时自适应调整。
以上就是少样本提示的要点。请继续尝试、持续学习,我们下篇见!
FAQs
与零样本方法相比,是否有办法衡量或量化使用少样本提示后任务表现的提升?
可以。可依据任务采用标准机器学习评估指标来量化改进。对于分类任务,可使用准确率、精确率、召回率和 F1 分数;对于生成任务,可使用 BLEU、ROUGE 或人工评估等指标。
是否有在某些行业或领域中,少样本提示的应用尤其成功?
少样本提示已在多个行业取得成功应用,包括客户服务(用于生成回复)、内容创作(写作辅助)与软件开发(代码生成)。它在医疗领域也很有价值,如病历摘要;在金融领域用于市场分析和报告生成。
少样本提示会如何影响数据科学家与机器学习工程师的未来就业市场?
少样本提示有望让 AI 应用开发更为大众化,使非专家也能轻松创建专业化的 AI 解决方案。这可能使数据科学家与机器学习工程师的工作重心转向更复杂的任务、提示工程以及更先进 AI 系统的开发;同时也可能催生专注于为各类应用打造高效提示与示例的新角色。
在高度专业或技术性领域中,少样本提示有哪些局限?
在高度专业化的领域中,若模型在该领域缺乏基础知识,少样本提示可能会遇到困难。仅凭少量示例也可能难以涵盖复杂的领域规则或流程。在此情况下,可能需要更广泛的微调或面向领域的训练。
在使用少样本提示时,是否存在需要注意的伦理问题或潜在滥用?
是的,存在伦理方面的担忧。如果示例选择不当,少样本提示可能被用来引导模型生成带有偏见或有害的内容。若提示中包含敏感信息,也存在无意泄露数据的风险。
Ana Rojo Echeburúa 是一位人工智能与数据专家,拥有应用数学博士学位。她热衷于将数据转化为可执行的洞见,并在带领技术团队方面拥有丰富经验。Ana 喜欢与客户密切合作,解决其业务难题并打造创新的 AI 解决方案。她以出色的问题解决能力和清晰的沟通著称,对人工智能,尤其是生成式 AI 充满热情。Ana 致力于持续学习与负责任的 AI 开发,同时专注于简化复杂问题,并以通俗易懂的方式解释技术。

大型语言模型能够理解并写出听起来非常接近人类的文本。但要让这些模型完全按照我们的预期行事,并不容易。要获得令人满意的答案,必须选择合适的技巧。
其中一种技巧就是少样本提示(few-shot prompting)。这是一种巧妙的方法,可以把模型已有的知识与我们希望它为特定任务所做的事情连接起来——您给模型几个快速示例来展示您的需求,从而让它更容易理解并正确完成任务。
在本教程中,您将了解:
本教程属于我的“提示工程:从入门到精通”系列博文: