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]])

相关推荐
用户1917291270834 分钟前
Agent 工具面裁剪:动态暴露与渐进披露(附 Python 代码)
人工智能
AI前端工程狮6 分钟前
我给 MCP 长任务加进度条,五步只显示了一步
javascript·人工智能·程序员
TsingtaoAI7 分钟前
VeyForge:构建具身智能的AI 3D资产与Sim-to-Real数据引擎
人工智能·机器学习
yiangL_25 分钟前
1、Python 输入输出实验|print 与 input 人机交互实践
开发语言·python·人机交互
螺丝钉tina30 分钟前
[Playwright] [21][AI] 千问生成测试的完整 mini demo
人工智能
高洁011 小时前
世界模型的因果内核:从预测表象到理解机制
人工智能·python·深度学习·transformer·迁移学习
Forget the Dream1 小时前
Spring AI 2.0 系列(三):ChatClient 与 ChatModel:Spring AI 2.0 的两层职责
java·人工智能·spring·springai
syso_稻草人1 小时前
qwen-image-2.1 姿态控制拆解:SDPose 提骨架 + Fun-ControlNet-Union 锁姿势,换人换景不换姿势
人工智能·stable diffusion·prompt·提示词优化·qwen-image
Baihai_IDP1 小时前
大模型 API 真的在赔本赚吆喝吗?聊聊 Token 背后的真实成本
人工智能·llm·aigc
数字融合1 小时前
透明化视频动态三维重建空间数据零核心技术
人工智能·python·virtualenv