在自然语言处理任务中,我们常常需要从一组示例中选择最适合当前输入的示例。这不仅影响到模型的性能,还影响到我们从模型中获得的结果质量。在这篇文章中,我们将探讨一种使用n-gram重叠评分来选择示例的策略:NGramOverlapExampleSelector
。
技术背景介绍
NGramOverlapExampleSelector
是一种选择和排序示例的方法,基于与输入最相似的n-gram重叠得分。n-gram重叠得分是介于0.0到1.0之间的浮点数,表示输入与示例之间的相似程度。此选择器允许设定一个阈值,排除得分低于该阈值的示例。默认情况下,阈值设为-1.0,从而只会对示例进行重新排序,而不做排除。
核心原理解析
n-gram重叠是通过比较输入和示例之间的词序列来计算的。这个得分可以用来识别输入与示例之间的相似性,从而帮助我们选择最有帮助的示例。当阈值设置为0.0时,选择器会排除那些与输入没有任何n-gram重叠的示例。
代码实现演示(重点)
以下是如何使用NGramOverlapExampleSelector
来选择示例的代码示例:
from langchain_community.example_selectors import NGramOverlapExampleSelector
from langchain_core.prompts import FewShotPromptTemplate, PromptTemplate
example_prompt = PromptTemplate(
input_variables=["input", "output"],
template="Input: {input}\nOutput: {output}",
)
# 示例输入集合
examples = [
{"input": "See Spot run.", "output": "Ver correr a Spot."},
{"input": "My dog barks.", "output": "Mi perro ladra."},
{"input": "Spot can run.", "output": "Spot puede correr."},
]
example_selector = NGramOverlapExampleSelector(
examples=examples,
example_prompt=example_prompt,
threshold=-1.0,
)
dynamic_prompt = FewShotPromptTemplate(
example_selector=example_selector,
example_prompt=example_prompt,
prefix="Give the Spanish translation of every input",
suffix="Input: {sentence}\nOutput:",
input_variables=["sentence"],
)
# 显示选择的示例
print(dynamic_prompt.format(sentence="Spot can run fast."))
# 添加新的示例
new_example = {"input": "Spot plays fetch.", "output": "Spot juega a buscar."}
example_selector.add_example(new_example)
print(dynamic_prompt.format(sentence="Spot can run fast."))
# 设置阈值排除没有重叠的示例
example_selector.threshold = 0.0
print(dynamic_prompt.format(sentence="Spot can run fast."))
# 设置小的非零阈值
example_selector.threshold = 0.09
print(dynamic_prompt.format(sentence="Spot can play fetch."))
# 设置阈值大于1.0的情况
example_selector.threshold = 1.0 + 1e-9
print(dynamic_prompt.format(sentence="Spot can play fetch."))
应用场景分析
这项技术特别适用于以下场景:
- 机翻(机器翻译)任务中,关联翻译示例的筛选。
- 自然语言生成任务中,选择上下文相关的示例。
- 文档摘要或信息检索中的相似内容检索。
实践建议
- 在实际应用中,根据需求调整阈值,以确保选择器能够排除或包含最有用的示例。
- 尽可能确保输入示例集的多样性,以提高选择器的选择质量。
- 定期更新示例集以反映新的数据和任务需求。
如果遇到问题欢迎在评论区交流。
—END—