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

相关推荐
倔强青铜三5 分钟前
苦练Python第60天:json模块——让Python和JSON“无缝互译”的神兵利器
人工智能·python·面试
Ivanqhz1 小时前
LR算法中反向最右推导(Reverse RightMost Derivation)
人工智能·算法
whltaoin1 小时前
AI 超级智能体全栈项目阶段四:学术分析 AI 项目 RAG 落地指南:基于 Spring AI 的本地与阿里云知识库实践
人工智能·spring·阿里云·向量数据库·rag
sheji34161 小时前
【开题答辩全过程】以 Web数据挖掘在电子商务中的应用研究为例,包含答辩的问题和答案
前端·人工智能·数据挖掘
진영_1 小时前
Transformer(一)---背景介绍及架构介绍
人工智能·深度学习·transformer
zzywxc7872 小时前
AI赋能千行百业:金融、医疗、教育、制造业的落地实践与未来展望
java·人工智能·python·microsoft·金融·golang·prompt
星楠_0012 小时前
logits和softmax分布
人工智能·python·深度学习
大千AI助手2 小时前
二元锦标赛:进化算法中的选择机制及其应用
人工智能·算法·优化·进化算法·二元锦标赛·选择机制·适应生存
IT_陈寒2 小时前
Python开发者必坑指南:3个看似聪明实则致命的‘优化’让我损失了50%性能
前端·人工智能·后端
落羽的落羽2 小时前
【Linux系统】快速入门一些常用的基础指令
linux·服务器·人工智能·学习·机器学习·aigc