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

相关推荐
小Q小Q44 分钟前
cmake编译LASzip和LAStools
人工智能·计算机视觉
yzx9910131 小时前
基于 Q-Learning 算法和 CNN 的强化学习实现方案
人工智能·算法·cnn
token-go1 小时前
[特殊字符] 革命性AI提示词优化平台正式开源!
人工智能·开源
cooldream20092 小时前
华为云Flexus+DeepSeek征文|基于华为云Flexus X和DeepSeek-R1打造个人知识库问答系统
人工智能·华为云·dify
Blossom.1185 小时前
使用Python和Scikit-Learn实现机器学习模型调优
开发语言·人工智能·python·深度学习·目标检测·机器学习·scikit-learn
scdifsn6 小时前
动手学深度学习12.7. 参数服务器-笔记&练习(PyTorch)
pytorch·笔记·深度学习·分布式计算·数据并行·参数服务器
DFminer6 小时前
【LLM】fast-api 流式生成测试
人工智能·机器人
郄堃Deep Traffic6 小时前
机器学习+城市规划第十四期:利用半参数地理加权回归来实现区域带宽不同的规划任务
人工智能·机器学习·回归·城市规划
海盗儿7 小时前
Attention Is All You Need (Transformer) 以及Transformer pytorch实现
pytorch·深度学习·transformer
GIS小天7 小时前
AI+预测3D新模型百十个定位预测+胆码预测+去和尾2025年6月7日第101弹
人工智能·算法·机器学习·彩票