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

相关推荐
白-胖-子1 小时前
深入剖析大模型在文本生成式 AI 产品架构中的核心地位
人工智能·架构
想要成为计算机高手2 小时前
11. isaacsim4.2教程-Transform 树与Odometry
人工智能·机器人·自动驾驶·ros·rviz·isaac sim·仿真环境
静心问道3 小时前
InstructBLIP:通过指令微调迈向通用视觉-语言模型
人工智能·多模态·ai技术应用
宇称不守恒4.03 小时前
2025暑期—06神经网络-常见网络2
网络·人工智能·神经网络
小楓12014 小时前
醫護行業在未來會被AI淘汰嗎?
人工智能·醫療·護理·職業
数据与人工智能律师4 小时前
数字迷雾中的安全锚点:解码匿名化与假名化的法律边界与商业价值
大数据·网络·人工智能·云计算·区块链
chenchihwen4 小时前
大模型应用班-第2课 DeepSeek使用与提示词工程课程重点 学习ollama 安装 用deepseek-r1:1.5b 分析PDF 内容
人工智能·学习
说私域4 小时前
公域流量向私域流量转化策略研究——基于开源AI智能客服、AI智能名片与S2B2C商城小程序的融合应用
人工智能·小程序
Java樱木4 小时前
AI 编程工具 Trae 重要的升级。。。
人工智能
码字的字节4 小时前
深度学习损失函数的设计哲学:从交叉熵到Huber损失的深入探索
深度学习·交叉熵·huber