理解单样本学习的原理和应用,掌握如何通过单个示例引导AI模型完成新任务
def one_shot_classification(model, new_text, categories):
"""单样本文本分类"""
prompt = f"""
任务:将文本分类到给定类别中
示例:
文本:这家餐厅的菜品非常美味,服务态度也很好
类别:[正面, 负面, 中性]
输出:正面
现在分类:
文本:{new_text}
类别:{categories}
输出:
"""
return model.generate(prompt, max_tokens=10)
# 使用示例
result = one_shot_classification(
model,
"产品质量一般,不是很满意",
"[正面, 负面, 中性]"
)
# 输出:负面
def one_shot_format_conversion(model, input_data, target_format):
"""单样本数据格式转换"""
prompt = f"""
任务:将数据转换为指定格式
示例:
输入:姓名:张三,年龄:25,职业:工程师
目标格式:JSON
输出:{{"name": "张三", "age": 25, "profession": "工程师"}}
现在转换:
输入:{input_data}
目标格式:{target_format}
输出:
"""
return model.generate(prompt)
# 使用示例
result = one_shot_format_conversion(
model,
"姓名:李四,年龄:30,职业:医生",
"JSON"
)
def one_shot_creative_writing(model, theme, style):
"""单样本创意写作"""
prompt = f"""
任务:根据主题和风格创作内容
示例:
主题:友谊
风格:诗歌
输出:
真正的友谊如金子般珍贵,
在岁月的洗礼中愈发闪亮,
无论风雨还是阳光,
都有彼此相伴的温暖。
现在创作:
主题:{theme}
风格:{style}
输出:
"""
return model.generate(prompt)
# 使用示例
result = one_shot_creative_writing(
model,
theme="春天",
style="散文"
)
def one_shot_code_generation(model, function_description):
"""单样本代码生成"""
prompt = f"""
任务:根据功能描述生成Python函数
示例:
功能描述:计算两个数的最大公约数
输出:
def gcd(a, b):
\"\"\"计算两个数的最大公约数\"\"\"
while b:
a, b = b, a % b
return a
现在生成:
功能描述:{function_description}
输出:
"""
return model.generate(prompt)
# 使用示例
result = one_shot_code_generation(
model,
"实现冒泡排序算法"
)
class AdaptiveOneShot:
"""自适应单样本学习"""
def __init__(self, model, example_pool):
self.model = model
self.example_pool = example_pool
def select_best_example(self, query, task_type):
"""为查询选择最佳示例"""
similarities = []
for example in self.example_pool[task_type]:
# 计算查询与示例的相似度
similarity = self.calculate_similarity(query, example['input'])
similarities.append((example, similarity))
# 选择最相似的示例
best_example = max(similarities, key=lambda x: x[1])[0]
return best_example
def one_shot_predict(self, query, task_type):
"""基于最佳示例的单样本预测"""
example = self.select_best_example(query, task_type)
prompt = f"""
任务:{task_type}
示例:
输入:{example['input']}
输出:{example['output']}
现在处理:
输入:{query}
输出:
"""
return self.model.generate(prompt)
def structured_one_shot(model, task_desc, example, new_input):
"""结构化单样本学习(2024年最佳实践)"""
prompt = f"""
<task>
{task_desc}
</task>
<example>
<input>{example['input']}</input>
<output>{example['output']}</output>
</example>
<new_task>
<input>{new_input}</input>
<output>
"""
return model.generate(prompt, stop=["</output>"])
class MultimodalOneShot:
"""多模态单样本学习"""
def __init__(self, multimodal_model):
self.model = multimodal_model
def image_classification_one_shot(self, example_image, example_label,
new_image, categories):
"""图像分类的单样本学习"""
prompt = f"""
任务:图像分类
示例:
[展示图像:{example_image}]
类别:{categories}
标签:{example_label}
现在分类:
[展示图像:{new_image}]
类别:{categories}
标签:
"""
return self.model.generate_with_images(
[example_image, new_image],
prompt
)
def visual_question_answering_one_shot(self, example_img, example_q,
example_a, new_img, new_q):
"""视觉问答的单样本学习"""
prompt = f"""
任务:根据图像回答问题
示例:
图像:[{example_img}]
问题:{example_q}
答案:{example_a}
现在回答:
图像:[{new_img}]
问题:{new_q}
答案:
"""
return self.model.generate_with_images([example_img, new_img], prompt)
class ExampleOptimizer:
"""示例质量优化器"""
def __init__(self, model):
self.model = model
def evaluate_example_quality(self, example, test_cases):
"""评估示例质量"""
scores = []
for test_input, expected_output in test_cases:
prompt = self.create_one_shot_prompt(example, test_input)
actual_output = self.model.generate(prompt)
# 计算输出质量分数
score = self.calculate_output_similarity(
expected_output, actual_output
)
scores.append(score)
return sum(scores) / len(scores)
def optimize_example(self, candidate_examples, test_cases):
"""从候选中选择最优示例"""
best_example = None
best_score = 0
for example in candidate_examples:
score = self.evaluate_example_quality(example, test_cases)
if score > best_score:
best_score = score
best_example = example
return best_example, best_score
def optimized_one_shot_prompt(task_desc, example, new_input,
output_constraints=None):
"""优化的单样本提示词结构"""
constraints_text = ""
if output_constraints:
constraints_text = f"\n\n<constraints>\n{output_constraints}\n</constraints>"
prompt = f"""
<instruction>
{task_desc}
{constraints_text}
</instruction>
<demonstration>
Input: {example['input']}
Output: {example['output']}
</demonstration>
<task>
Input: {new_input}
Output:
"""
return prompt
# 使用示例
prompt = optimized_one_shot_prompt(
task_desc="将非正式文本转换为正式文本",
example={
'input': "这个东西真的超级棒!",
'output': "这个产品确实表现优异。"
},
new_input="咋回事啊,怎么还没到?",
output_constraints="保持原意,使用正式用词,避免口语化表达"
)
def rapid_prototyping_one_shot(model, task_idea, single_example):
"""快速原型的单样本实现"""
prompt = f"""
新任务原型:{task_idea}
参考示例:
{single_example}
请按照示例模式处理新输入:
"""
return lambda new_input: model.generate(prompt + new_input)
def format_standardization_one_shot(model, source_format, target_format,
conversion_example):
"""格式标准化的单样本学习"""
prompt = f"""
任务:{source_format} → {target_format} 格式转换
转换示例:
{conversion_example}
请按相同模式转换:
"""
return prompt
def domain_adaptation_one_shot(model, general_example, domain_context):
"""领域适应的单样本学习"""
prompt = f"""
任务:在{domain_context}领域执行相同任务
通用示例:
{general_example}
请在指定领域执行相同类型任务:
"""
return prompt
class OneShotEvaluator:
"""单样本学习评估器"""
def __init__(self, model):
self.model = model
def compare_shot_methods(self, task_data, evaluation_metric):
"""比较零样本、单样本、少样本性能"""
results = {}
# 零样本
zero_shot_scores = []
for item in task_data:
prompt = f"任务:{item['task_desc']}\n输入:{item['input']}\n输出:"
output = self.model.generate(prompt)
score = evaluation_metric(item['expected'], output)
zero_shot_scores.append(score)
# 单样本
one_shot_scores = []
example = task_data[0] # 使用第一个作为示例
for item in task_data[1:]:
prompt = f"""
任务:{item['task_desc']}
示例:
输入:{example['input']}
输出:{example['expected']}
现在处理:
输入:{item['input']}
输出:
"""
output = self.model.generate(prompt)
score = evaluation_metric(item['expected'], output)
one_shot_scores.append(score)
# 少样本(3个示例)
few_shot_scores = []
examples = task_data[:3]
for item in task_data[3:]:
prompt = f"任务:{item['task_desc']}\n\n"
for ex in examples:
prompt += f"输入:{ex['input']}\n输出:{ex['expected']}\n\n"
prompt += f"输入:{item['input']}\n输出:"
output = self.model.generate(prompt)
score = evaluation_metric(item['expected'], output)
few_shot_scores.append(score)
return {
'zero_shot': sum(zero_shot_scores) / len(zero_shot_scores),
'one_shot': sum(one_shot_scores) / len(one_shot_scores),
'few_shot': sum(few_shot_scores) / len(few_shot_scores)
}
任务类型 | 零样本 | 单样本 | 少样本(3) | 提升幅度 |
---|---|---|---|---|
文本分类 | 72.3% | 85.7% | 88.2% | +13.4% |
情感分析 | 78.1% | 89.3% | 91.5% | +11.2% |
格式转换 | 65.4% | 92.1% | 93.8% | +26.7% |
数据提取 | 69.8% | 87.4% | 89.6% | +17.6% |
创意写作 | 71.2% | 82.9% | 86.3% | +11.7% |
class AutoExampleGenerator:
"""自动示例生成器"""
def __init__(self, model):
self.model = model
def generate_optimal_example(self, task_description, target_input_type):
"""为特定任务生成最优示例"""
prompt = f"""
任务:{task_description}
请生成一个高质量的示例,包含:
1. 典型的{target_input_type}输入
2. 正确且清晰的输出
3. 能够很好展示任务模式
示例格式:
输入:[示例输入]
输出:[示例输出]
"""
return self.model.generate(prompt)
class DynamicExampleAdjuster:
"""动态示例调整器"""
def adjust_example_complexity(self, base_example, user_level):
"""根据用户水平调整示例复杂度"""
complexity_levels = {
'beginner': '简单直接的',
'intermediate': '适中复杂度的',
'advanced': '具有挑战性的'
}
prompt = f"""
请将以下示例调整为{complexity_levels[user_level]}版本:
原始示例:{base_example}
调整后的示例:
"""
return self.model.generate(prompt)