Bert中文预训练模型(Bert-base-chinese)

介绍

Bert-base-chinese模型是一个在简体和繁体中文文本上训练得到的预训练模型,具有以下特点:

  • 12个隐层
  • 输出768维张量
  • 12个自注意力头
  • 110M参数量

该模型的主要作用是获取每个汉字的向量表示,后续通过微调可应用于各种简体和繁体中文任务。

使用

python 复制代码
import torch
from transformers import BertTokenizer, BertModel

# 第一步:离线下载
# from transformers import BertModel, BertTokenizer
# model_name = "bert-base-chinese"
# # 下载模型和分词器
# model = BertModel.from_pretrained(model_name)
# tokenizer = BertTokenizer.from_pretrained(model_name)
# # 保存模型和分词器到本地路径
# model.save_pretrained("./bert-base-chinese")
# tokenizer.save_pretrained("./bert-base-chinese")

# 第二步:加载模型和分词器
model_path = "./bert-base-chinese"
tokenizer = BertTokenizer.from_pretrained(model_path)
model = BertModel.from_pretrained(model_path)


def encode_text_with_bert(text):
    """
    使用bert-base-chinese模型对文本进行编码
    :param text: 输入的文本
    :return: 编码后的张量
    """
    # 使用tokenizer对文本进行编码,并去掉起始和结束标志
    encoded_text = tokenizer.encode(text)[1: -1]
    # 把列表转成张量
    encoded_tensor = torch.LongTensor([encoded_text])

    # 不自动进行梯度计算
    with torch.no_grad():
        output = model(encoded_tensor)

    # 返回编码后的张量(取last_hidden_state)
    return output[0]


if __name__ == '__main__':
    text1 = "你好,美丽中国"
    result = encode_text_with_bert(text1)
    print('text1编码的形状:', result.size())
    print('text1编码:\n', result)

text1编码的形状: torch.Size([1, 7, 768])

text1编码:

tensor([[[ 0.0781, -0.7386, -0.5120, ..., 1.0695, -0.4252, -0.3970],

0.3118, -0.2283, -0.2513, ..., -0.0618, 0.8715, -0.0833\], \[ 0.0287, -0.4937, -0.5554, ..., 0.1643, 0.8771, 0.0019\], ..., \[-0.3068, -0.3406, 0.0525, ..., 0.5506, 0.8915, -0.3713\], \[-0.1079, -0.0951, -0.1549, ..., 0.8432, 0.7255, -0.5235\], \[-0.0414, -0.3786, 0.1590, ..., 0.3844, 0.7464, -0.4266\]\]\])

相关推荐
hef2882 小时前
如何生成特定SQL的AWR报告_@awrsqrpt.sql深度剖析单条语句性能
jvm·数据库·python
小程故事多_802 小时前
Agent+Milvus,告别静态知识库,打造具备动态记忆的智能AI助手
人工智能·深度学习·ai编程·milvus
code_pgf2 小时前
Llama 3详解
人工智能·llama
ComputerInBook2 小时前
数字图像处理(4版)——第 3 章——(图像的)强度变换和空间滤波(Rafael C.Gonzalez&Richard E. Woods)
图像处理·人工智能·计算机视觉·强度变换和空间滤波
爱写代码的小朋友2 小时前
生成式人工智能(AIGC)在开放式教育问答系统中的知识表征与推理机制研究
人工智能·aigc
Jinkxs2 小时前
从语法纠错到项目重构:Python+Copilot 的全流程开发效率提升指南
python·重构·copilot
技术专家2 小时前
Stable Diffusion系列的详细讨论 / Detailed Discussion of the Stable Diffusion Series
人工智能·python·算法·推荐算法·1024程序员节
m0_488913012 小时前
万字长文带你梳理Llama开源家族:从Llama-1到Llama-3,看这一篇就够了!
人工智能·学习·机器学习·大模型·产品经理·llama·uml
helpme流水2 小时前
LLaMA Factory 从入门到精通,一篇讲完
人工智能·ai·语言模型·llama
段一凡-华北理工大学2 小时前
【大模型+知识图谱+工业智能体技术架构】~系列文章01:快速了解与初学入门!!!
人工智能·python·架构·知识图谱·工业智能体