谷歌-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博客

相关推荐
lqqjuly13 分钟前
Lidar调试记录Ⅳ之Ubuntu22.04+ROS2+Livox_SDK2环境下编译Livox ROS Driver 2
人工智能·机器人·自动驾驶
qq_4369621817 分钟前
数据中台:打破企业数据孤岛,实现全域资产化的关键一步
数据库·人工智能·信息可视化·数据挖掘·数据分析
宇若-凉凉42 分钟前
BERT 完整教程指南
人工智能·深度学习·bert
JD技术委员会1 小时前
如何在跨部门沟通失误后进行协调与澄清
人工智能
PcVue China1 小时前
PcVue X 工控——工厂数字化转型与落地巡回研讨会圆满举行
人工智能·软件工程·scada·监控平台·工控网
StarPrayers.2 小时前
自蒸馏学习方法
人工智能·算法·学习方法
咚咚王者2 小时前
人工智能之编程进阶 Python高级:第十一章 过渡项目
开发语言·人工智能·python
深度学习lover2 小时前
<数据集>yolo航拍斑马线识别数据集<目标检测>
人工智能·深度学习·yolo·目标检测·计算机视觉·数据集·航拍斑马线识别
大力财经2 小时前
百度开启AI新纪元,让智能从成本变成超级生产力
人工智能·百度
雍凉明月夜3 小时前
Ⅰ人工智能学习的核心概念概述+线性回归(1)
人工智能·学习