3 命名实体识别调优化

能走到这里说明你对模型微调有了一个基本的认识。那么开始一段命名实体的任务过程,下面使用huggingface官网的数据。

1 准备模型

下面的模型自己选择一个吧,我的内存太第一个模型跑不了。

https://huggingface.co/ckiplab/bert-base-chinese-ner/tree/main

2 准备数据

https://huggingface.co/datasets/peoples_daily_ner

3 训练

评估指标

https://huggingface.co/spaces/evaluate-metric/seqeval

复制代码
import evaluate
from datasets import load_dataset
from transformers import AutoTokenizer, AutoModelForTokenClassification, TrainingArguments, Trainer, DataCollatorForTokenClassification

# 如果可以联网,直接使用load_dataset进行加载
#ner_datasets = load_dataset("peoples_daily_ner", cache_dir="./data")
# 如果无法联网,则使用下面的方式加载数据集
from datasets import DatasetDict
ner_datasets = DatasetDict.load_from_disk("../data/ner_data/")
ner_datasets

tokenizer = AutoTokenizer.from_pretrained("/Users/user/studyFile/2024/nlp/bert_base_chinese_ner/")

# 借助word_ids 实现标签映射
def process_function(examples):
    tokenized_exmaples = tokenizer(examples["tokens"], max_length=128, truncation=True, is_split_into_words=True)
    labels = []
    for i, label in enumerate(examples["ner_tags"]):
        word_ids = tokenized_exmaples.word_ids(batch_index=i)
        label_ids = []
        for word_id in word_ids:
            if word_id is None:
                label_ids.append(-100)
            else:
                label_ids.append(label[word_id])
        labels.append(label_ids)
    tokenized_exmaples["labels"] = labels
    return tokenized_exmaples
tokenized_datasets = ner_datasets.map(process_function, batched=True)
tokenized_datasets

# 自己定义数据的类别个数
label_list = ner_datasets["train"].features["ner_tags"].feature.names


#model = AutoModelForTokenClassification.from_pretrained("../bert_base_chinese_ner/", num_labels=len(label_list))
import torch
model = AutoModelForTokenClassification.from_pretrained("../bert_base_chinese_ner/",num_labels=len(label_list),ignore_mismatched_sizes=True)
#model.num_labels = len(label_list)
#num_labels = len(label_list)
#model.classifier.out_proj.weight.data = torch.nn.functional.linear(model.classifier.weight, (model.classifier.weight.shape[0] / num_labels)) 
#model.classifier.out_proj.bias.data = model.classifier.bias
 

# 这里方便大家加载,替换成了本地的加载方式,无需额外下载
seqeval = evaluate.load("seqeval_metric.py")
seqeval

import numpy as np
# 自定义评估指标
def eval_metric(pred):
    predictions, labels = pred
    predictions = np.argmax(predictions, axis=-1)

    # 将id转换为原始的字符串类型的标签
    true_predictions = [
        [label_list[p] for p, l in zip(prediction, label) if l != -100]
        for prediction, label in zip(predictions, labels) 
    ]

    true_labels = [
        [label_list[l] for p, l in zip(prediction, label) if l != -100]
        for prediction, label in zip(predictions, labels) 
    ]

    result = seqeval.compute(predictions=true_predictions, references=true_labels, mode="strict", scheme="IOB2")

    return {
        "f1": result["overall_f1"]
    }
    
args = TrainingArguments(
    output_dir="models_for_ner",
    per_device_train_batch_size=64,
    per_device_eval_batch_size=128,
    evaluation_strategy="epoch",
    save_strategy="epoch",
    metric_for_best_model="f1",
    load_best_model_at_end=True,
    logging_steps=50,
    num_train_epochs=1
)

trainer = Trainer(
    model=model,
    args=args,
    train_dataset=tokenized_datasets["train"],
    eval_dataset=tokenized_datasets["validation"],
    compute_metrics=eval_metric,
    data_collator=DataCollatorForTokenClassification(tokenizer=tokenizer)
)
trainer.train()

训练的过程太慢了。

相关推荐
GEO从入门到精通1 分钟前
GEO学习书籍或文章推荐哪本?
人工智能·学习
陌陌龙7 分钟前
Sub2API 源码技术分析与搭建教程:把 AI 订阅变成可管理的 API 网关
人工智能
老虎海子7 分钟前
从零入门 OpenAI Codex|登录、权限、终端、记忆配置全实操
人工智能·vscode·自然语言处理·chatgpt·个人开发·业界资讯
与芯同行7 分钟前
TP9243S与TP9311双芯片:AI语音产品从采集到回放的完整解决方案
人工智能
若兰幽竹12 分钟前
【大模型应用】抖音爆款视频深度分析系统:流水线式AI逆向拆解流量密码,精准预测播放量!
人工智能·python·音视频·抖音爆款分析
AI技术控12 分钟前
NeuroH-TGL 论文解读:面向脑疾病诊断的神经异质性引导时序图学习方法
人工智能·语言模型·自然语言处理·langchain·nlp
fuquxiaoguang13 分钟前
微软Maia 200的“算力经济学”:推理时代的专用芯片如何改写游戏规则
人工智能·microsoft
心中有国也有家16 分钟前
pytorch-adapter:让 PyTorch 模型“无缝”跑在昇腾 NPU 上
人工智能·pytorch·笔记·python·学习
Sharewinfo_BJ17 分钟前
从手工报表到实时BI:一个零售数据平台的踩坑与重构实战
大数据·人工智能·科技·数据分析·微软·powerbi
Elastic 中国社区官方博客32 分钟前
在 Elasticsearch 中,存储向量查询速度最高提升 3 倍
大数据·人工智能·elasticsearch·搜索引擎·ai·全文检索