`
wx1568037608
  • 浏览: 33534 次
最近访客 更多访客>>
文章分类
社区版块
存档分类
最新评论

BERT-Pytorch demo初探

 
阅读更多

https://zhuanlan.zhihu.com/p/50773178

概述

本文基于 pytorch-pretrained-BERT(huggingface)版本的复现,探究如下几个问题:

  1. pytorch-pretrained-BERT的基本框架和使用
  2. 如何利用BERT将句子转为词向量
  3. 如何使用BERT训练模型(针对SQuAD数据集的问答模型,篇幅问题,可能下篇再写)

因为已经有很多文章对BERT的结构和效果做了详尽的介绍,所以对于模型的效果和结构就不在这里赘述了。

基本框架和使用

环境

首先,利用pip安装包:

1    pip install pytorch-pretrained-bert

这种安装方法可能会导致一个编码问题,具体细节可以参考这里。作者已经把这个错误改了过来,但是没有发布新的版本(当前版本为0.1.2),因此需要我们先从github上下载源码,然后安装:

1    pip install [--editable] .

结构

Google提供了6种预训练的模型,具体细节如下:

  • bert-base-uncased: 12-layer, 768-hidden, 12-heads, 110M parameters
  • bert-large-uncased: 24-layer, 1024-hidden, 16-heads, 340M parameters
  • bert-base-cased: 12-layer, 768-hidden, 12-heads , 110M parameters
  • bert-base-multilingual: 102 languages, 12-layer, 768-hidden, 12-heads, 110M parameters
  • bert-base-chinese: Chinese Simplified and Traditional, 12-layer, 768-hidden, 12-heads, 110M parameters

作者对于每个预训练的模型都提供了6个model类和3个tokenizer类供我们使用。具体的模型简介和参数可以参照这里README中pytorch model和Tokenizer部分。

1    tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
2    model = BertModel.from_pretrained('bert-base-uncased')

初始化

上面就是对model和tokenizer进行初始化的代码,“BertTokenizer”和“BertModel”可以替换为自己需要的模型和分词器,后面函数的参数对应6中预训练的模型。由于是预训练的模型,所以肯定是要下模型和词表的,作者把资源放到了亚马逊的云上,链接写在了一个环境变量里,如果第一次使用,要提前下载,下载后的文件存放在cache文件夹:~/.pytorch_pretrained_bert/下。

1    PRETRAINED_MODEL_ARCHIVE_MAP = {
2        'bert-base-uncased': "https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-uncased.tar.gz",
3        'bert-large-uncased': "https://s3.amazonaws.com/models.huggingface.co/bert/bert-large-uncased.tar.gz",
4        'bert-base-cased': "https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-cased.tar.gz",
5        'bert-base-multilingual': "https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-multilingual.tar.gz",
6        'bert-base-chinese': "https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-chinese.tar.gz",
7    }

不知道其他人下载情况如何,反正在我这边利用requeset去下就很慢,所以肯定是想提前下好,然后放过去的。这是我踩的一个大坑。在Folx上下好模型后,我欣喜的关掉了那个贼慢的python程序(虽然显示已经下了一半了),一波美滋滋的拷贝之后,发现并没有卵用,它并没有识别我下好的文件,又重新开始request了。只能先让它慢悠悠的下着,看看下下来的东西是啥,然后去读读源码。

后来发现大概的流程是这样的,它会把文件先下到一个tmp文件夹中,然后复制到cache文件夹下。(但我已经把资源放到里面了啊,并无卵用!)在读代码的同时,tokenizer的东西下好了,经过代码和文件的双重验证:它会把链接名和一堆烂七八糟的tag加起来做MD5,然后作为文件名,过程很复杂,看不太懂。

经过再一次深入的阅读,我发现了它大概的流程:它会先判断 from_pretrained 函数的参数,如果是上文中 PRETRAINED_MODEL_ARCHIVE_MAP 已有的,就会去cache里找;如果不是,就会判断它是不是一个路径,会在这个路径下找需要的文件,一个config文件和一个bin文件,正好和我们下载的文件对应。

 1    """
 2    Params:
 3    pretrained_model_name: either:
 4    - a str with the name of a pre-trained model to load selected in the list of:
 5    . `bert-base-uncased`
 6    . `bert-large-uncased`
 7    . `bert-base-cased`
 8    . `bert-base-multilingual`
 9    . `bert-base-chinese`
10    - a path or url to a pretrained model archive containing:
11    . `bert_config.json` a configuration file for the model
12    . `pytorch_model.bin` a PyTorch dump of a BertForPreTraining instance
13    *inputs, **kwargs: additional input for the specific Bert class
14    (ex: num_labels for BertForSequenceClassification)
15    """
16

接下来的操作就简单了,直接贴代码:

1    UNCASED='./bert-base-uncased' # your path for model and vocab 
2    VOCAB='bert-base-uncased-vocab.txt'
3    tokenizer=BertTokenizer.from_pretrained(os.path.join(UNCASED,VOCAB))
4    model = BertModel.from_pretrained(UNCASED)

需要注意的是,Tokenizer需要的是词表,我们看到的model需要的是文件,词表的链接如下:

1    PRETRAINED_VOCAB_ARCHIVE_MAP = {
2        'bert-base-uncased': "https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-uncased-vocab.txt",
3        'bert-large-uncased': "https://s3.amazonaws.com/models.huggingface.co/bert/bert-large-uncased-vocab.txt",
4        'bert-base-cased': "https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-cased-vocab.txt",
5        'bert-base-multilingual': "https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-multilingual-vocab.txt",
6        'bert-base-chinese': "https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-chinese-vocab.txt",
7    }

利用BERT获取词向量

作者其实在README中的 Usage给出了将句子转为词向量的demo,但是有点简略。同时,作者在extract_features.py中提供了详细的使用方法,接下来的内容就是对这里面的代码进行解读了。

因为Usage中的注释已经很详细了,所以接下来重点关注两个点:

  1. 如何批量处理(将文件中的句子转为词向量)
  2. 获得的词向量结构如何,是模型的哪个部分的输出

批量处理

1    layer_indexes = [int(x) for x in args.layers.split(",")]
2    tokenizer = BertTokenizer.from_pretrained(args.bert_model)
3    examples = read_examples(args.input_file)
4    features = convert_examples_to_features(
5        examples=examples, seq_length=args.max_seq_length, tokenizer=tokenizer)
6    unique_id_to_feature = {}
7    for feature in features:
8        unique_id_to_feature[feature.unique_id] = feature
9    model = BertModel.from_pretrained(args.bert_model)

其实处理的流程很简单,就是读入文件,然后将其转为需要的格式(InputFeatures类),然后利用模型进行处理。重点在于文件读取的函数中:

 1    def read_examples(input_file):
 2        """Read a list of `InputExample`s from an input file."""
 3        examples = []
 4        unique_id = 0
 5        with open(input_file, "r") as reader:
 6            while True:
 7                line = convert_to_unicode(reader.readline())
 8                if not line:
 9                    break
10                line = line.strip()
11                text_a = None
12                text_b = None
13                m = re.match(r"^(.*) \|\|\| (.*)$", line)
14                if m is None:
15                    text_a = line
16                else:
17                    text_a = m.group(1)
18                    text_b = m.group(2)
19                examples.append(
20                    InputExample(unique_id=unique_id, text_a=text_a, text_b=text_b))
21                unique_id += 1
22        return examples

最关键的部分就是13行的那个正则表达式,模型中对于文本会分成两部分,part A 和 part B。在这个函数中,将两个部分的文本以“ ||| ” 分割(注意前后有空格),所以文件中的每一行应该是“I love you ||| Hello world”这样。

词向量结构

 1    all_encoder_layers, _ = model(input_ids, token_type_ids=None, attention_mask=input_mask)
 2    all_encoder_layers = all_encoder_layers
 3
 4    for b, example_index in enumerate(example_indices):
 5        feature = features[example_index.item()]
 6        unique_id = int(feature.unique_id)
 7        # feature = unique_id_to_feature[unique_id]
 8        output_json = collections.OrderedDict()
 9        output_json["linex_index"] = unique_id
10        all_out_features = []
11        for (i, token) in enumerate(feature.tokens):
12            all_layers = []
13            for (j, layer_index) in enumerate(layer_indexes):
14                layer_output = all_encoder_layers[int(layer_index)].detach().cpu().numpy()
15                layer_output = layer_output[b]
16                layers = collections.OrderedDict()
17                layers["index"] = layer_index
18                layers["values"] = [
19                    round(x.item(), 6) for x in layer_output[i]
20                ]
21                all_layers.append(layers)
22                out_features = collections.OrderedDict()
23                out_features["token"] = token
24                out_features["layers"] = all_layers
25                all_out_features.append(out_features)
26                output_json["features"] = all_out_features
27                writer.write(json.dumps(output_json) + "\n")

19行得到的是一个list,长度为网络的层数,每个元素是[batch,sequence,embedding]的向量。

对于每个序列,序列中每个向量的token,分别获取它相应层(由参数arg.layers控制,本文中是最后四层)的编码。最后对于每个序列中的每个token会获取到[layer,dimension]大小的向量作为features。

 

分享到:
评论

相关推荐

    NER-BERT-pytorch-master_ner_

    "NER-BERT-pytorch-master"项目是基于BERT的NER模型实现,利用了PyTorch框架。PyTorch因其动态计算图和易于调试的特性,成为了深度学习研究者和开发者首选的工具之一。在该项目中,我们可以预期找到以下关键组成部分...

    bert-base-uncased-pytorch_model.bin

    标题中的"bert-base-uncased-pytorch_model.bin"是一个特定的文件名,它与BERT模型有关,BERT是Bidirectional Encoder Representations from Transformers的缩写,由Google在2018年提出,是自然语言处理领域的一个...

    BERT-NER-Pytorch-master

    BERT-NER-Pytorch-master

    Bert-Pytorch-TextClassification-master

    【标题】"Bert-Pytorch-TextClassification-master" 是一个基于PyTorch实现的BERT模型在文本分类任务上的应用项目。该项目的核心是利用Transformer架构中的预训练模型BERT(Bidirectional Encoder Representations ...

    Bert-Chinese-Text-Classification-Pytorch-master.zip.zip

    标题 "Bert-Chinese-Text-Classification-Pytorch-master.zip.zip" 暗示这是一个包含BERT(Bidirectional Encoder Representations from Transformers)模型的中文文本分类项目,基于PyTorch实现。这个压缩包提供了...

    百度云提取.bert-large-uncased-pytorch_model.bin

    bert-large-uncased-pytorch_model.bin 这是1024位的,资源过大,超过一个g,我放百度云上了 768位的看我的博客免费获取

    Chinese-Text-Classification-Pytorch-mas

    Chinese-Text-Classification-Pytorch-master。 数据齐全,说明文档详细。点击即用! # 训练并测试: # TextCNN python run.py --model TextCNN # TextRNN python run.py --model TextRNN # TextRNN_Att python ...

    Bert-BiLSTM-CRF-pytorch-master (1)_python_

    标题中的"Bert-BiLSTM-CRF-pytorch-master"是一个基于Python的自然语言处理(NLP)项目,它利用了BERT、双向长短期记忆网络(BiLSTM)和条件随机场(CRF)这三个技术。这个项目可能是为了实现命名实体识别(NER),...

    Bert-Chinese-Text-Classification-Pytorch:使用Bert,ERNIE,进行中文文本分类

    模型选择和准备:在中文文本分类任务中,Bert和ERNIE等预训练模型已经在自然语言处理领域显示出强大的性能。你可以选择合适的预训练模型,并下载相应的模型权重文件。通过使用Pytorch的模型加载和初始化功能,能够将...

    Google_AI_2018_BERT_pytorch_implementation_BERT-pytorch.zip

    Google_AI_2018_BERT_pytorch_implementation_BERT-pytorch

    基于Pytorch的BERT-IDCNN-BILSTM-CRF中文实体识别实现

    基于Pytorch的BERT-IDCNN-BILSTM-CRF中文实体识别实现 模型训练(可选) 下载pytorch_model.bin到data/bert 下载训练集和测试集到data/ 检查配置constants.py 执行train.py,命令为 python train.py 中文命名实体...

    人工智能-项目实践-意图识别-pytorch+bert实现的意图识别与槽位填充.zip

    使用的预训练模型:hugging face上的chinese-bert-wwm-ext 依赖: pytorch==1.6+ transformers==4.5.0 运行指令: python main.py 可在config.py里面修改相关的参数,训练、验证、测试、还有预测。

    bert-chinese-pytorch.rar

    标题中的"bert-chinese-pytorch.rar"是一个与自然语言处理(NLP)相关的压缩包文件,特别提及了BERT(Bidirectional Encoder Representations from Transformers)的中文预训练模型,并且是基于PyTorch框架实现的。...

    pytorch-pretrained-BERT-master_python_bert问答_BERT_

    PyTorch-pretrained-BERT-master是一个专注于使用PyTorch实现的BERT(Bidirectional Encoder Representations from Transformers)模型库,它为用户提供了预训练的BERT模型,可以用于各种自然语言处理任务,如语言...

    Deep-Learning-with-PyTorch.rar

    1. 预训练模型:PyTorch提供了许多预训练模型,如ResNet、VGG、BERT等,可以直接使用或作为基础模型进行迁移学习。 2. 微调:对预训练模型的某些层进行随机初始化,进行微调,可以快速适应新的任务,提高模型性能。...

    BERT手把手实现分类任务-Pytorch

    BERT 手把手实现分类任务-Pytorch 本资源摘要信息主要讲解了如何使用 Pytorch 实现 BERT 手把手分类任务。BERT 是一种基于 transformer 的语言模型,可以 fine-tune 来适应各种任务。 1. 什么是 BERT? BERT...

    chinese-bert-wwm-ext.rar

    《哈工大版Chinese-BERT-wwm-ext for PyTorch深度解析》 在自然语言处理(NLP)领域,预训练模型已经成为基石,而BERT(Bidirectional Encoder Representations from Transformers)模型更是其中的明星。本文将深入...

    PyPI 官网下载 | enformer-pytorch-0.2.14.tar.gz

    传统的Transformer模型,如BERT和GPT,主要针对序列数据,而Enformer则扩展了这一框架,不仅处理序列,还能处理网格状数据。它采用了混合注意力机制,结合了全局和局部的关注点,以适应复杂的数据结构。这种设计允许...

    自然语言处理-bert-base-chinese模型

    bert-base-chinese 是 BERT 模型的一种变体,它在中文语料库上进行预训练,以便更好地理解和处理中文文本。适用于自然语言处理工程师、数据科学家、机器学习研究者以及对中文文本处理感兴趣的开发者。bert-base-...

Global site tag (gtag.js) - Google Analytics