解决:bert_score无法加载本地模型

相信很多小伙伴平时都使用内网进行工作,这些网络是无法连接huggingface的,使用魔塔加载模型网络断断续续的很容易失败。但是bert_score只接收一个模型名,然后自动在huggingface下载或在本地缓存加载。这个缓存跟huggingface官方缓存是不同的。

解决办法1:修改bert_score源码。bert_score虽说是只接受模型名,但内部还是通过AutoTokenizer.from_pretrained和AutoModel.from_pretrained这两个方法加载模型,相信这两个方法大家都很熟悉了。因此只需要在源码中添加自己的model_path,并且把源码中的model_type这个参数改为model_path

源码:

def get_model(model_type, num_layers, all_layers=None):
    if model_type.startswith("scibert"):
        model = AutoModel.from_pretrained(cache_scibert(model_type))
    elif "t5" in model_type:
        from transformers import T5EncoderModel

        model = T5EncoderModel.from_pretrained(model_type)
    else:
        model = AutoModel.from_pretrained(model_type)
    model.eval()

def get_tokenizer(model_type, use_fast=False):
    if model_type.startswith("scibert"):
        model_type = cache_scibert(model_type)

    if version.parse(trans_version) >= version.parse("4.0.0"):
        tokenizer = AutoTokenizer.from_pretrained(model_type, use_fast=use_fast)
    else:
        assert not use_fast, "Fast tokenizer is not available for version < 4.0.0"
        tokenizer = AutoTokenizer.from_pretrained(model_type)

    return tokenizer

改为:

def get_model(model_type, num_layers, all_layers=None):
    model_path = 'xxx'
    if model_type.startswith("scibert"):
        model = AutoModel.from_pretrained(cache_scibert(model_type))
    elif "t5" in model_type:
        from transformers import T5EncoderModel

        model = T5EncoderModel.from_pretrained(model_path)
    else:
        model = AutoModel.from_pretrained(model_path)
    model.eval()


def get_tokenizer(model_type, use_fast=False):
    if model_type.startswith("scibert"):
        model_type = cache_scibert(model_type)

    model_path = 'xxx'
    if version.parse(trans_version) >= version.parse("4.0.0"):
        tokenizer = AutoTokenizer.from_pretrained(model_path, use_fast=use_fast)
    else:
        assert not use_fast, "Fast tokenizer is not available for version < 4.0.0"
        tokenizer = AutoTokenizer.from_pretrained(model_path)

    return tokenizer

解决办法2:让bert_score找到缓存模型,相信聪明的小伙伴已经在前面的代码中看到bert_score是如何加载缓存模型的。如果要加载缓存模型,model_type字段加载的模型前要加scibert-前缀。并且需要把本地模型放在指定的目录下。可以看出这个函数下载的模型有它自己的命名规则,需要根据它的规则对自己的模型文件做出相应修改。

下面给出部分源码

def cache_scibert(model_type, cache_folder="~/.cache/torch/transformers"):
    if not model_type.startswith("scibert"):
        return model_type

    underscore_model_type = model_type.replace("-", "_")
    cache_folder = os.path.abspath(os.path.expanduser(cache_folder))
    filename = os.path.join(cache_folder, underscore_model_type)

  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是使用bert-base-chinese训练实体识别模型的代码示例: 1. 准备数据集 首先,需要准备实体识别任务的数据集。数据集应该包含标记好的实体标签,例如“B-PER”和“I-PER”表示人名实体的开始和内部标记。 2. 定义模型 定义一个使用bert-base-chinese预训练模型的实体识别模型,可以使用PyTorch和Transformers库: ```python import torch from transformers import BertForTokenClassification, BertTokenizer model = BertForTokenClassification.from_pretrained('bert-base-chinese', num_labels=5) tokenizer = BertTokenizer.from_pretrained('bert-base-chinese') ``` 在这里,我们使用“num_labels”参数指定模型输出的标签数,即实体类别数。 3. 定义训练循环 接下来,我们定义训练循环来训练我们的模型: ```python from torch.utils.data import DataLoader, RandomSampler, SequentialSampler from transformers import AdamW, get_linear_schedule_with_warmup device = torch.device("cuda" if torch.cuda.is_available() else "cpu") model.to(device) train_data = ... # 加载训练数据集 train_sampler = RandomSampler(train_data) train_dataloader = DataLoader(train_data, sampler=train_sampler, batch_size=32) optimizer = AdamW(model.parameters(), lr=5e-5, eps=1e-8) total_steps = len(train_dataloader) * 3 scheduler = get_linear_schedule_with_warmup(optimizer, num_warmup_steps=0, num_training_steps=total_steps) for epoch in range(3): for batch in train_dataloader: model.train() batch = tuple(t.to(device) for t in batch) inputs = {'input_ids': batch[0], 'attention_mask': batch[1], 'labels': batch[3]} outputs = model(**inputs) loss = outputs[0] loss.backward() torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0) optimizer.step() scheduler.step() optimizer.zero_grad() ``` 在这里,我们使用随机采样器将训练数据集的数据随机分成小批次。我们使用AdamW优化器和带有线性学习率调度程序的预热来训练模型。在每个时期内,我们遍历每个小批次并计算损失和梯度,然后更新模型参数。 4. 评估模型 训练完成后,我们可以使用测试数据集来评估模型的性能: ```python test_data = ... # 加载测试数据集 test_sampler = SequentialSampler(test_data) test_dataloader = DataLoader(test_data, sampler=test_sampler, batch_size=32) model.eval() predictions = [] true_labels = [] for batch in test_dataloader: batch = tuple(t.to(device) for t in batch) inputs = {'input_ids': batch[0], 'attention_mask': batch[1], 'labels': batch[3]} with torch.no_grad(): outputs = model(**inputs) logits = outputs[1].detach().cpu().numpy() label_ids = inputs['labels'].cpu().numpy() predictions.extend([list(p) for p in np.argmax(logits, axis=2)]) true_labels.extend(label_ids) from sklearn.metrics import f1_score f1_score = f1_score(true_labels, predictions, average='weighted') print("F1 score:", f1_score) ``` 在这里,我们将测试数据集分成小批次,并使用模型的“eval”方法来计算预测标签。然后,我们使用f1_score度量来评估模型性能。 这就是使用bert-base-chinese训练实体识别模型的代码示例。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值