iis服务器助手广告广告
返回顶部
首页 > 资讯 > 精选 >Pytorch中BertModel怎么用
  • 709
分享到

Pytorch中BertModel怎么用

2023-06-14 08:06:37 709人浏览 安东尼
摘要

小编给大家分享一下PyTorch中BertModel怎么用,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!基本介绍环境: python 3.5+, Pytorch

小编给大家分享一下PyTorch中BertModel怎么用,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!

基本介绍

环境: python 3.5+, Pytorch 0.4.1/1.0.0

安装:

pip install pytorch-pretrained-bert

必需参数:

--data_dir: "str": 数据根目录.目录下放着,train.xxx/dev.xxx/test.xxx三个数据文件.

--vocab_dir: "str": 词库文件地址.

--bert_model: "str": 存放着bert预训练好的模型. 需要是一个gz文件, 如"..x/xx/bert-base-chinese.tar.gz ", 里面包含一个bert_config.JSON和pytorch_model.bin文件.

--task_name: "str": 用来选择对应数据集的参数,如"cola",对应着数据集.

--output_dir: "str": 模型预测结果和模型参数存储目录.

简单例子:

导入所需包

import torchfrom pytorch_pretrained_bert import BertTokenizer, BertModel, BertFORMaskedLM

创建分词器

tokenizer = BertTokenizer.from_pretrained(--vocab_dir)

需要参数: --vocab_dir, 数据样式见此

拥有函数:

tokenize: 输入句子,根据--vocab_dir和贪心原则切词. 返回单词列表

convert_token_to_ids: 将切词后的列表转换为词库对应id列表.

convert_ids_to_tokens: 将id列表转换为单词列表.

text = '[CLS] 武松打老虎 [SEP] 你在哪 [SEP]'tokenized_text = tokenizer.tokenize(text)indexed_tokens = tokenizer.convert_tokens_to_ids(tokenized_text)segments_ids = [0, 0, 0, 0, 0, 0, 0,0,0,0, 1,1, 1, 1, 1, 1, 1, 1]tokens_tensor = torch.tensor([indexed_tokens])segments_tensors = torch.tensor([segments_ids])

这里对标记符号的切词似乎有问题([cls]/[sep]), 而且中文bert是基于字级别编码的,因此切出来的都是一个一个汉字:

['[', 'cl', '##s', ']', '武', '松', '打', '老', '虎', '[', 'sep', ']', '你', '在', '哪', '[', 'sep', ']']

创建bert模型并加载预训练模型:

model = BertModel.from_pretrained(--bert_model)

放入GPU:

tokens_tensor = tokens_tensor.cuda()segments_tensors = segments_tensors.cuda()model.cuda()

前向传播:

encoded_layers, pooled_output= model(tokens_tensor, segments_tensors)

参数:

input_ids: (batch_size, sqe_len)代表输入实例的Tensor

token_type_ids=None: (batch_size, sqe_len)一个实例可以含有两个句子,这个相当于句子标记.

attention_mask=None: (batch_size*): 传入每个实例的长度,用于attention的mask.

output_all_encoded_layers=True: 控制是否输出所有encoder层的结果.

返回值:

encoded_layer:长度为num_hidden_layers的(batch_size, sequence_length,hidden_size)的Tensor.列表

pooled_output: (batch_size, hidden_size), 最后一层encoder的第一个词[CLS]经过Linear层和激活函数Tanh()后的Tensor. 其代表了句子信息

补充:pytorch使用Bert

主要分为以下几个步骤:

下载模型放到目录中

使用transformers中的BertModel,BertTokenizer来加载模型与分词器

使用tokenizer的encode和decode 函数分别编码与解码,注意参数add_special_tokens和skip_special_tokens

forward的输入是一个[batch_size, seq_length]的tensor,再需要注意的是attention_mask参数。

输出是一个tuple,tuple的第一个值是bert的最后一个transformer层的hidden_state,size是[batch_size, seq_length, hidden_size],也就是bert最后的输出,再用于下游的任务。

# -*- encoding: utf-8 -*-import warningswarnings.filterwarnings('ignore')from transformers import BertModel, BertTokenizer, BertConfigimport osfrom os.path import dirname, abspathroot_dir = dirname(dirname(dirname(abspath(__file__))))import torch# 把预训练的模型从官网下载下来放到目录中pretrained_path = os.path.join(root_dir, 'pretrained/bert_zh')# 从文件中加载bert模型model = BertModel.from_pretrained(pretrained_path)# 从bert目录中加载词典tokenizer = BertTokenizer.from_pretrained(pretrained_path)print(f'vocab size :{tokenizer.vocab_size}')# 把'[PAD]'编码print(tokenizer.encode('[PAD]'))print(tokenizer.encode('[SEP]'))# 把中文句子编码,默认加入了special tokens了,也就是句子开头加入了[CLS] 句子结尾加入了[SEP]ids = tokenizer.encode("我是中国人", add_special_tokens=True)# 从结果中看,101是[CLS]的id,而2769是"我"的id# [101, 2769, 3221, 704, 1744, 782, 102]print(ids)# 把ids解码为中文,默认是没有跳过特殊字符的print(tokenizer.decode([101, 2769, 3221, 704, 1744, 782, 102], skip_special_tokens=False))# print(model)inputs = torch.tensor(ids).unsqueeze(0)# forward,result是一个tuple,第一个tensor是最后的hidden-stateresult = model(torch.tensor(inputs))# [1, 5, 768]print(result[0].size())# [1, 768]print(result[1].size())for name, parameter in model.named_parameters():  # 打印每一层,及每一层的参数  print(name)  # 每一层的参数默认都requires_grad=True的,参数是可以学习的  print(parameter.requires_grad)  # 如果只想训练第11层transformer的参数的话:  if '11' in name:    parameter.requires_grad = True  else:    parameter.requires_grad = Falseprint([p.requires_grad for name, p in model.named_parameters()])

添加atten_mask的方法:

其中101是[CLS],102是[SEP],0是[PAD]

>>> atensor([[101,  3,  4, 23, 11,  1, 102,  0,  0,  0]])>>> notpad = a!=0>>> notpadtensor([[ True, True, True, True, True, True, True, False, False, False]])>>> notcls = a!=101>>> notclstensor([[False, True, True, True, True, True, True, True, True, True]])>>> notsep = a!=102>>> notseptensor([[ True, True, True, True, True, True, False, True, True, True]])>>> mask = notpad & notcls & notsep>>> masktensor([[False, True, True, True, True, True, False, False, False, False]])>>>

以上是“Pytorch中BertModel怎么用”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注编程网精选频道!

--结束END--

本文标题: Pytorch中BertModel怎么用

本文链接: https://www.lsjlt.com/news/269288.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • Pytorch中BertModel怎么用
    小编给大家分享一下Pytorch中BertModel怎么用,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!基本介绍环境: Python 3.5+, Pytorch ...
    99+
    2023-06-14
  • Pytorch BertModel的使用说明
    基本介绍 环境: Python 3.5+, Pytorch 0.4.1/1.0.0 安装: pip install pytorch-pretrained-bert 必需参数: ...
    99+
    2024-04-02
  • Pytorch中怎么使用TensorBoard
    本文小编为大家详细介绍“Pytorch中怎么使用TensorBoard”,内容详细,步骤清晰,细节处理妥当,希望这篇“Pytorch中怎么使用TensorBoard”文章能帮助大家解决疑惑,下面跟着小编的思路慢慢深入,一起来学习新知识吧。一...
    99+
    2023-07-02
  • pytorch中nn.Dropout怎么使用
    小编给大家分享一下pytorch中nn.Dropout怎么使用,希望大家阅读完这篇文章之后都有所收获,下面让我们一起去探讨吧!看代码吧~Class USeDropout(nn.Module):   &...
    99+
    2023-06-15
  • pytorch中[..., 0]怎么使用
    这篇文章将为大家详细讲解有关pytorch中[..., 0]怎么使用,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。在看程序的时候看到了x[…, 0]的语句不是很理解,后来自己做实验略微了解,以此记录方便自...
    99+
    2023-06-15
  • PyTorch中torch.utils.data.DataLoader怎么使用
    这篇文章主要介绍“PyTorch中torch.utils.data.DataLoader怎么使用”,在日常操作中,相信很多人在PyTorch中torch.utils.data.DataLoader怎么使用问题上存在疑惑,小编查阅了各式资料,...
    99+
    2023-07-02
  • PyTorch中的torch.cat怎么用
    这篇文章主要介绍PyTorch中的torch.cat怎么用,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!1.toych简单介绍包torch包含了多维疑是的数据结构及基于其上的多种数学操作。torch包含了多维张量的数...
    99+
    2023-06-29
  • Python中Pytorch怎么使用
    这篇文章将为大家详细讲解有关Python中Pytorch怎么使用,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。一、TensorTensor(张量是一个统称,其中包括很多类型):0阶张量:标量、常数、0-D...
    99+
    2023-06-15
  • pytorch中model=model.to怎么用
    这篇文章给大家分享的是有关pytorch中model=model.to怎么用的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。这代表将模型加载到指定设备上。其中,device=torch.device("c...
    99+
    2023-06-15
  • pytorch中nn.RNN()怎么使用
    这篇文章主要介绍“pytorch中nn.RNN()怎么使用”,在日常操作中,相信很多人在pytorch中nn.RNN()怎么使用问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”pytorch中nn.RNN()怎...
    99+
    2023-07-04
  • Pytorch中torch.flatten()和torch.nn.Flatten()怎么用
    本文小编为大家详细介绍“Pytorch中torch.flatten()和torch.nn.Flatten()怎么用”,内容详细,步骤清晰,细节处理妥当,希望这篇“Pytorch中torch.flatten()和torch.nn.Flatte...
    99+
    2023-06-29
  • Pytorch中net.train 和 net.eval怎么用
    这篇文章主要介绍Pytorch中net.train 和 net.eval怎么用,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!在训练模型时会在前面加上:model.train()在测试模型时在前面使用:model.ev...
    99+
    2023-06-15
  • pytorch中with torch.no_grad()怎么使用
    本篇内容主要讲解“pytorch中with torch.no_grad()怎么使用”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“pytorch中with torch.no_g...
    99+
    2023-06-29
  • PyTorch中的nn.Embedding怎么使用
    这篇“PyTorch中的nn.Embedding怎么使用”文章的知识点大部分人都不太理解,所以小编给大家总结了以下内容,内容详细,步骤清晰,具有一定的借鉴价值,希望大家阅读完这篇文章能有所收获,下面我们一起来看看这篇“PyTorch中的nn...
    99+
    2023-07-02
  • pytorch中torch.topk()函数怎么用
    这篇文章主要介绍“pytorch中torch.topk()函数怎么用”,在日常操作中,相信很多人在pytorch中torch.topk()函数怎么用问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”pytorch...
    99+
    2023-06-29
  • pytorch中Parameter函数怎么使用
    这篇文章主要介绍了pytorch中Parameter函数怎么使用的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇pytorch中Parameter函数怎么使用文章都会有所收获,下面我们一起来看看吧。用法介绍pyt...
    99+
    2023-06-29
  • Pytorch中的torch.distributions库怎么使用
    本文小编为大家详细介绍“Pytorch中的torch.distributions库怎么使用”,内容详细,步骤清晰,细节处理妥当,希望这篇“Pytorch中的torch.distributions库怎么使用”文章能帮助大家解决疑惑,下面跟着小...
    99+
    2023-07-05
  • PyTorch中的nn.Module类怎么使用
    这篇文章主要讲解了“PyTorch中的nn.Module类怎么使用”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“PyTorch中的nn.Module类怎么使用”吧!PyTorch nn.Mo...
    99+
    2023-07-05
  • PyTorch中torch.matmul()函数怎么使用
    这篇文章主要介绍了PyTorch中torch.matmul()函数怎么使用的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇PyTorch中torch.matmul()函数怎么使用文章都会有所收获,下面我们一起来看...
    99+
    2023-07-06
  • Pytorch中的torch.gather()函数怎么用
    这篇文章将为大家详细讲解有关Pytorch中的torch.gather()函数怎么用,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。参数说明以官方说明为例,gather()函数需要三个参数,输入input,...
    99+
    2023-06-25
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作