Transformer应用
自然语言处理应用
机器翻译
Transformer最初就是为机器翻译任务设计的,现在已成为翻译系统的标准架构。
应用场景:
- 多语言翻译系统
- 实时语音翻译
- 文档翻译
- 网页翻译
代码示例:
from transformers import MarianMTModel, MarianTokenizer
# 英语到德语翻译
model_name = 'Helsinki-NLP/opus-mt-en-de'
model = MarianMTModel.from_pretrained(model_name)
tokenizer = MarianTokenizer.from_pretrained(model_name)
text = "Hello, how are you?"
inputs = tokenizer(text, return_tensors="pt")
translated = model.generate(**inputs)
result = tokenizer.decode(translated[0], skip_special_tokens=True)
print(result) # "Hallo, wie geht es dir?"
文本生成
基于Transformer的语言模型在文本生成方面表现出色。
应用场景:
- 创意写作辅助
- 代码生成
- 对话系统
- 内容创作
代码示例:
from transformers import GPT2LMHeadModel, GPT2Tokenizer
model = GPT2LMHeadModel.from_pretrained('gpt2')
tokenizer = GPT2Tokenizer.from_pretrained('gpt2')
prompt = "The future of artificial intelligence is"
inputs = tokenizer.encode(prompt, return_tensors='pt')
# 生成文本
with torch.no_grad():
outputs = model.generate(
inputs,
max_length=100,
temperature=0.8,
do_sample=True,
pad_token_id=tokenizer.eos_token_id
)
generated_text = tokenizer.decode(outputs[0], skip_special_tokens=True)
print(generated_text)
情感分析
Transformer模型在文本情感分析任务中表现优异。
应用场景:
- 社交媒体情感监控
- 产品评论分析
- 客户反馈分析
- 市场情绪分析
代码示例:
from transformers import pipeline
# 使用预训练的情感分析管道
sentiment_pipeline = pipeline("sentiment-analysis")
texts = [
"I love this product!",
"This movie is terrible.",
"The weather is okay today."
]
results = sentiment_pipeline(texts)
for text, result in zip(texts, results):
print(f"Text: {text}")
print(f"Sentiment: {result['label']}, Score: {result['score']:.3f}\n")
问答系统
Transformer在阅读理解和问答任务中展现了强大能力。
应用场景:
- 智能客服
- 教育辅导
- 知识检索
- 文档问答
代码示例:
from transformers import pipeline
# 创建问答管道
qa_pipeline = pipeline("question-answering")
context = """
Transformers are a type of neural network architecture that has revolutionized
natural language processing. They were introduced in 2017 by Vaswani et al.
in the paper "Attention Is All You Need". The key innovation is the self-attention
mechanism that allows the model to process all positions in a sequence simultaneously.
"""
question = "When were Transformers introduced?"
result = qa_pipeline(question=question, context=context)
print(f"Answer: {result['answer']}")
print(f"Confidence: {result['score']:.3f}")
文本摘要
自动文本摘要是Transformer的重要应用领域。
应用场景:
- 新闻摘要
- 学术论文摘要
- 报告总结
- 会议纪要
代码示例:
from transformers import pipeline
summarizer = pipeline("summarization")
article = """
Artificial intelligence (AI) is intelligence demonstrated by machines,
in contrast to the natural intelligence displayed by humans and animals.
Leading AI textbooks define the field as the study of "intelligent agents":
any device that perceives its environment and takes actions that maximize
its chance of successfully achieving its goals...
"""
summary = summarizer(article, max_length=130, min_length=30, do_sample=False)
print(summary[0]['summary_text'])
计算机视觉应用
图像分类
Vision Transformer (ViT) 在图像 分类任务中取得了优异性能。
应用场景:
- 医学影像诊断
- 产品质量检测
- 自动驾驶
- 安防监控
代码示例:
from transformers import ViTImageProcessor, ViTForImageClassification
from PIL import Image
import requests
# 加载模型和处理器
processor = ViTImageProcessor.from_pretrained('google/vit-base-patch16-224')
model = ViTForImageClassification.from_pretrained('google/vit-base-patch16-224')
# 加载图像
url = 'http://images.cocodataset.org/val2017/000000039769.jpg'
image = Image.open(requests.get(url, stream=True).raw)
# 预处理和预测
inputs = processor(images=image, return_tensors="pt")
outputs = model(**inputs)
logits = outputs.logits
# 获取预测结果
predicted_class_idx = logits.argmax(-1).item()
print(f"Predicted class: {model.config.id2label[predicted_class_idx]}")
目标检测
DETR等模型将Transformer应用于目标检测任务。
应用场景:
- 自动驾驶车辆检测
- 工业质量检测
- 体育赛事分析
- 安防监控
代码示例:
from transformers import DetrImageProcessor, DetrForObjectDetection
import torch
from PIL import Image, ImageDraw
import requests
# 加载模型
processor = DetrImageProcessor.from_pretrained("facebook/detr-resnet-50")
model = DetrForObjectDetection.from_pretrained("facebook/detr-resnet-50")
# 处理图像
url = "http://images.cocodataset.org/val2017/000000039769.jpg"
image = Image.open(requests.get(url, stream=True).raw)
inputs = processor(images=image, return_tensors="pt")
outputs = model(**inputs)
# 后处理
target_sizes = torch.tensor([image.size[::-1]])
results = processor.post_process_object_detection(outputs, target_sizes=target_sizes)[0]
# 绘制检测结果
draw = ImageDraw.Draw(image)
for score, label, box in zip(results["scores"], results["labels"], results["boxes"]):
if score > 0.5:
box = [round(i, 2) for i in box.tolist()]
draw.rectangle(box, outline="red", width=2)
draw.text((box[0], box[1]), f"{model.config.id2label[label.item()]}: {score:.2f}")
图像生成
DALL-E等模型展示了Transformer在图像生成方面的潜力。
应用场景:
- 创意设计
- 广告素材生成
- 游戏资产创建
- 艺术创作