预训练bert模型导入与字符串表征

#coding=utf-8
##预训练bert模型导入与字符串表征(单句)
#import torch
#from transformers import BertModel, BertTokenizer

#model_name = 'bert_pretrain'#模型目录
##注意文件名:下载的文件预训练模型config.json, pytorch_model.bin, vocab.txt
#tokenizer = BertTokenizer.from_pretrained(model_name)

#model = BertModel.from_pretrained(model_name)

#input_text = '今天天气很不错,阳光明媚。'
##input_text = ['今天天气很不错,阳光明媚。','今天的天气很不错,阳光明媚。','今天天气很不错,是吗,阳光明媚。','今天天气很不错,阳光明媚,不会吧。']

#input_ids = tokenizer.encode(input_text, add_special_tokens=True)#id化,可以编码多个作为batchsize

#input_ids = torch.tensor([input_ids])#id转换tensor
##input_ids = torch.tensor([input_ids,input_ids,input_ids])#batchsize方式:id转换tensor,结果[3, 6, 768]

#with torch.no_grad():
    #last_hidden_states = model(input_ids)[0]#表征,与12层transformer特征提取,输出cls的特征用于分类
    #print(last_hidden_states.shape)
    


#临时的batchsize方式
#coding=utf-8
#预训练bert模型导入与字符串表征
import torch
from transformers import BertModel, BertTokenizer

model_name = 'bert_pretrain'#模型目录
#注意文件名:下载的文件预训练模型config.json, pytorch_model.bin, vocab.txt
tokenizer = BertTokenizer.from_pretrained(model_name)

model = BertModel.from_pretrained(model_name)

##方法1 手动控长:这样的方法需要控制长度,否则转换tensor报错。
#input_text = ['今天天气很不错,阳光明媚。','今天天气很不错,阳光明媚。','今天天气很不错,阳光明媚。','今天天气很不错,阳光明媚。']
#input_ids = [tokenizer.encode(text, add_special_tokens=True, max_length=32, padding=True) for text in input_text]
#input_ids = torch.tensor(input_ids)

##方法2 自动控长(推荐):直接控制max_length方式,总长padding 0
input_texts = ['今天天气很不错,阳光明媚。','今天的天气很不错,阳光明媚。','今天天气很不错,是吗,阳光明媚。','今天天气很不错,阳光明媚,不会吧。']
input_ids = [tokenizer.encode(text, add_special_tokens=True, max_length = 32,padding='max_length', truncation=True) for text in input_texts]
input_ids = torch.tensor(input_ids)    

with torch.no_grad():
    last_hidden_states = model(input_ids)[0]#表征,与12层transformer特征提取,输出cls的特征用于分类
    print(last_hidden_states.shape)

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值