🔥 Transformers实战:Text分类×SQuAD问答×CoNLL实体识别(含超参调优方案)

本文较长,建议点赞收藏,以免遗失。更多AI大模型应用开发学习视频及资料,尽在聚客AI学院

本文将通过代码实战带你快速掌握NLP三大核心任务,使用Hugging Face Transformers库实现工业级AI应用开发。

一、环境准备

复制代码
pip install transformers datasets torch tensorboard

二、文本分类实战(情感分析)

1. 数据加载与预处理

ini 复制代码
from datasets import load_dataset
from transformers import AutoTokenizer
dataset = load_dataset("imdb")
tokenizer = AutoTokenizer.from_pretrained("distilbert-base-uncased")
def tokenize_function(examples):
    return tokenizer(examples["text"], padding="max_length", truncation=True)
tokenized_datasets = dataset.map(tokenize_function, batched=True)

2. 模型训练

ini 复制代码
from transformers import AutoModelForSequenceClassification, TrainingArguments, Trainer
model = AutoModelForSequenceClassification.from_pretrained(
    "distilbert-base-uncased", num_labels=2
)
training_args = TrainingArguments(
    output_dir="./results",
    evaluation_strategy="epoch",
    learning_rate=2e-5,
    per_device_train_batch_size=16,
    num_train_epochs=3,
)
trainer = Trainer(
    model=model,
    args=training_args,
    train_dataset=tokenized_datasets["train"],
    eval_dataset=tokenized_datasets["test"],
)
trainer.train()

3. 推理预测

scss 复制代码
from transformers import pipeline
classifier = pipeline("text-classification", model=model, tokenizer=tokenizer)
result = classifier("This movie was absolutely fantastic!")
print(result)  # [{'label': 'POSITIVE', 'score': 0.999}]

三、问答系统实战(SQuAD数据集)

1. 加载问答数据集

ini 复制代码
dataset = load_dataset("squad")
tokenizer = AutoTokenizer.from_pretrained("distilbert-base-uncased")
def preprocess_function(examples):
    questions = [q.strip() for q in examples["question"]]
    inputs = tokenizer(
        questions,
        examples["context"],
        max_length=384,
        truncation="only_second",
        return_offsets_mapping=True,
        padding="max_length",
    )
    return inputs
tokenized_squad = dataset.map(preprocess_function, batched=True)

2. 训练问答模型

ini 复制代码
from transformers import AutoModelForQuestionAnswering
model = AutoModelForQuestionAnswering.from_pretrained("distilbert-base-uncased")
training_args = TrainingArguments(
    output_dir="./qa_results",
    evaluation_strategy="epoch",
    learning_rate=3e-5,
    per_device_train_batch_size=12,
    num_train_epochs=2,
)
trainer = Trainer(
    model=model,
    args=training_args,
    train_dataset=tokenized_squad["train"],
    eval_dataset=tokenized_squad["validation"],
)
trainer.train()

3. 执行问答

ini 复制代码
question = "What does NLP stand for?"
context = "Natural Language Processing (NLP) is a subfield of artificial intelligence."
qa_pipeline = pipeline("question-answering", model=model, tokenizer=tokenizer)
result = qa_pipeline(question=question, context=context)
print(result)
# {'score': 0.982, 'start': 0, 'end': 24, 'answer': 'Natural Language Processing'}

四、命名实体识别实战(CoNLL-2003)

1. 数据预处理

ini 复制代码
dataset = load_dataset("conll2003")
tokenizer = AutoTokenizer.from_pretrained("bert-base-cased")
label_list = dataset["train"].features["ner_tags"].feature.names
def tokenize_and_align_labels(examples):
    tokenized_inputs = tokenizer(
        examples["tokens"], 
        truncation=True,
        is_split_into_words=True
    )
    
    labels = []
    for i, label in enumerate(examples["ner_tags"]):
        word_ids = tokenized_inputs.word_ids(batch_index=i)
        previous_word_idx = None
        label_ids = []
        for word_idx in word_ids:
            if word_idx is None:
                label_ids.append(-100)
            elif word_idx != previous_word_idx:
                label_ids.append(label[word_idx])
            else:
                label_ids.append(-100)
            previous_word_idx = word_idx
        labels.append(label_ids)
    
    tokenized_inputs["labels"] = labels
    return tokenized_inputs
tokenized_dataset = dataset.map(tokenize_and_align_labels, batched=True)

2. 训练NER模型

ini 复制代码
from transformers import AutoModelForTokenClassification
model = AutoModelForTokenClassification.from_pretrained(
    "bert-base-cased", 
    num_labels=len(label_list)
    
training_args = TrainingArguments(
    output_dir="./ner_results",
    evaluation_strategy="epoch",
    learning_rate=2e-5,
    per_device_train_batch_size=16,
    num_train_epochs=3,
)
trainer = Trainer(
    model=model,
    args=training_args,
    train_dataset=tokenized_dataset["train"],
    eval_dataset=tokenized_dataset["validation"],
)
trainer.train()

3. 实体识别推理

ini 复制代码
from transformers import pipeline
ner_pipeline = pipeline("ner", model=model, tokenizer=tokenizer)
sample_text = "Apple was founded by Steve Jobs in Cupertino, California."
entities = ner_pipeline(sample_text)
for entity in entities:
    print(f"{entity['word']} -> {label_list[entity['entity'][-1]]}")
    
# Apple -> B-ORG
# Steve Jobs -> B-PER
# Cupertino -> B-LOC
# California -> B-LOC

五、核心技巧总结

迁移学习优势:使用预训练模型可节省90%训练时间

动态填充:使用DataCollator提升训练效率

混合精度训练:添加fp16=True参数加速训练

学习率调度:采用线性衰减策略更稳定收敛

早停机制:监控验证集损失防止过拟合

六、进阶学习方向

关键提示:实践时注意调整超参数(batch size、学习率)以适应你的硬件配置,小显存设备建议使用distilbert等轻量模型。更多AI大模型应用开发学习视频内容和资料,尽在聚客AI学院

相关推荐
zandy10118 分钟前
架构解析:衡石科技如何基于AI+Data Agent重构智能数据分析平台
人工智能·科技·架构
golang学习记25 分钟前
免费解锁 Cursor AI 全功能:4 种开发者私藏方案揭秘
人工智能
图扑软件33 分钟前
热力图可视化为何被广泛应用?| 图扑数字孪生
大数据·人工智能·信息可视化·数字孪生·可视化·热力图·电力能源
qq_4369621835 分钟前
AI驱动数据分析革新:奥威BI一键生成智能报告
人工智能·信息可视化·数据分析
卓码软件测评1 小时前
借助大语言模型实现高效测试迁移:Airbnb的大规模实践
开发语言·前端·javascript·人工智能·语言模型·自然语言处理
小白狮ww1 小时前
dots.ocr 基于 1.7B 参数实现多语言文档处理,性能达 SOTA
人工智能·深度学习·机器学习·自然语言处理·ocr·小红书·文档处理
hrrrrb1 小时前
【机器学习】无监督学习
人工智能·学习·机器学习
IT_陈寒1 小时前
SpringBoot 3.0实战:这套配置让我轻松扛住百万并发,性能提升300%
前端·人工智能·后端
阿烦大大@1 小时前
探索Perplexity:当AI遇上搜索引擎的革命性突破
人工智能·搜索引擎
chenchihwen9 小时前
AI代码开发宝库系列:Function Call
人工智能·python·1024程序员节·dashscope