谷歌-BERT-第二步:模型使用

1 需求

需求1:基于pipeline使用预训练模型

需求2:基于BertTokenizer/BertForSequenceClassification使用预训练模型

  • 第一步,Raw text
  • 第二步,Input IDs
  • 第三步,Logits
  • 第四步,Predictions

2 接口


3.1 基于pipeline使用预训练模型

示例1:使用在线预训练模型

复制代码
from transformers import pipeline
 
# 创建一个pipeline,指定模型名称和任务类型
# 这里以'bert-base-uncased'模型的'fill-mask'任务为例
fill_mask_pipeline = pipeline(
    "fill-mask",
    model="bert-base-uncased",
    tokenizer="bert-base-uncased"
)
 
# 使用pipeline进行推理
# 例如,填充句子中的[MASK]标记
result = fill_mask_pipeline("Hello I'm a [MASK] model.")
 
# 打印结果
print(result)

示例2:使用本地已下载的预训练模型

复制代码
from transformers import pipeline
 
# 设定本地模型文件的存储路径
local_model_path = './my_local_bert_model'
 
# 创建一个pipeline,用于执行特定的任务,例如'fill-mask'
# 在此过程中,我们指定了本地模型的路径
fill_mask_pipeline = pipeline(
    "fill-mask",
    model=local_model_path,
    tokenizer=local_model_path  # 假设分词器文件也存放在同一目录下
)
 
# 使用pipeline进行推理
# 例如,填充句子中的[MASK]部分
result = fill_mask_pipeline("Hello, I'm a [MASK] model.")
 
# 输出结果
print(result)

3.2

复制代码
import torch
from transformers import BertTokenizer, BertForSequenceClassification

# 加载预训练模型和 tokenizer
tokenizer = BertTokenizer.from_pretrained('./model')
model = BertForSequenceClassification.from_pretrained('./model')

# 示例文本
text = "这是一个非常有趣的电影。"

# 对文本进行编码
inputs = tokenizer(text, return_tensors='pt', padding=True, truncation=True)

# 进行预测
with torch.no_grad():
    outputs = model(**inputs)

# 获取预测结果
logits = outputs.logits
predicted_class = torch.argmax(logits, dim=-1).item()

print(f"预测的类别为:{predicted_class}")

# 定义输入文本列表,包含"高兴"和"伤心"两个文本
input = ['高兴', '伤心']

# 从指定路径加载预训练的自动分词器
from transformers import AutoTokenizer
tokenizer = AutoTokenizer.from_pretrained("./model")
# 使用分词器对输入文本进行处理,包括填充、截断并转换为 PyTorch 张量格式
input = tokenizer(input, padding=True, truncation=True, return_tensors='pt')

# 从指定路径加载预训练的序列分类模型
from transformers import AutoModelForSequenceClassification
model = AutoModelForSequenceClassification.from_pretrained("./model")
# 打印加载的模型信息
print(model)

# 将处理后的输入传递给模型,得到输出结果
output = model(**input)
# 打印输出的 logits 的形状
print(output.logits.shape)

# 导入 PyTorch 库
import torch
# 使用 softmax 函数对 logits 进行处理,得到预测的概率分布
predictions = torch.nn.functional.softmax(output.logits, dim=1)
# 打印预测的概率分布
print(predictions)
# 打印模型的类别标签映射
print(model.config.id2label)

4 参考资料

transformers库的使用【一】------pipeline的简单使用_transformer pipeline-CSDN博客

【人工智能】Transformers之Pipeline(十七):文本分类(text-classification)_文本分类模型排名-CSDN博客

【人工智能】Transformers之Pipeline(十八):文本生成(text-generation)_pipeline('text2text-generation')-CSDN博客

相关推荐
马踏岛国赏樱花4 分钟前
Mamba: Linear-Time Sequence Modeling with Selective State Spaces
深度学习
子春一18 分钟前
Flutter 与 AI 融合开发实战:在移动端集成大模型、智能推荐与生成式 UI
人工智能·flutter·ui
whitelbwwww43 分钟前
Python图像处理入门指南--opencv
人工智能·opencv·计算机视觉
Peter11467178501 小时前
华中科技大学研究生课程《数字图像处理I》期末考试(2025-回忆版/电子信息与通信学院)
图像处理·人工智能·计算机视觉
颜颜yan_1 小时前
在openEuler上搞个云原生AI模型商店:像点外卖一样部署模型
人工智能·云原生
lomocode1 小时前
Dify 自建部署完全指南:从上手到放弃到真香
人工智能
aaaa_a1332 小时前
李宏毅——self-attention Transformer
人工智能·深度学习·transformer
Coovally AI模型快速验证2 小时前
MAR-YOLOv9:革新农业检测,YOLOv9的“低调”逆袭
人工智能·神经网络·yolo·计算机视觉·cnn
云和数据.ChenGuang2 小时前
AI运维工程师技术教程之Linux环境下部署Deepseek
linux·运维·人工智能
cvyoutian2 小时前
解决 PyTorch 大型 wheel 下载慢、超时和反复重下的问题
人工智能·pytorch·python