Bert使用之一_基本使用

这篇博客介绍了BERT模型的基本使用方法,包括加载预训练的词汇表和模型,以及前向传播过程中的参数解释。内容涵盖了词汇表的加载,模型加载,以及在前向传播中input_ids、token_type_ids和attention_mask的作用。还提到了预训练资源的下载选项。
摘要由CSDN通过智能技术生成

Bert使用参考:
https://blog.csdn.net/c991262331/article/details/89381972
https://zhuanlan.zhihu.com/p/50773178
https://www.jiqizhixin.com/articles/2018-11-01-9

一 Demo

注意:
BertTokenizer.from_pretrained中参数要指定到vocab的文件路径,而BertModel.from_pretrained中参数要指定到pytorch_model.bin和config.json所在的目录路径,不是要指定到pytorch_model.bin的文件路径

from pytorch_pretrained_bert import BertTokenizer,BertModel
import torch

# bert_tokenizer = BertTokenizer.from_pretrained("bert-base-chinese")
bert_tokenizer = BertTokenizer.from_pretrained(r'C:\XXX\bert-base-chinese-vocab.txt')
a = "张三和李四都住在村头"
a_token = bert_tokenizer.tokenize(a)
print(a_token)
a_seq_ids = bert_tokenizer.convert_tokens_to_ids(a_token)
print(a_seq_ids)

# bert_model = BertModel.from_pretrained("bert-base-chinese")
bert_model = BertModel.from_pretrained(r'C:\XXX\bert-base-chinese')
batch_data = torch.Tensor(a_seq_ids).long().view((1,-1))
out,_ = bert_model(batch_data)
print(out[0].shape)

['张', '三', '和', '李', '四', '都', '住', '在', '村', '头']
[2476, 676, 1469, 3330, 1724, 6963, 857, 1762, 3333, 1928]
torch.Size([1, 10, 768])
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值