基于Pytorch框架的Bert模型中文文本分类,输出结果是如下图所示的张量Tensor([151])等,我的分类类别是0、1,一直到6这样的数字标签,请问怎么从输出的张量结果看对应的预测类别标签?
这样输出的结果是正确的吗?
谢谢回答的大家!
部分模型引用代码如下:
with open('data_for_classify.txt','r',encoding='utf-8') as f:
for line in f.readlines():
new_sentences = line.strip()
input_ids, seq_len, attention_mask = preprocess(new_sentences)
preprocessed_sentences = preprocess(new_sentences)
logits = bert_model.forward(preprocessed_sentences[0], attention_mask=preprocessed_sentences[2])[1]
#preprocessed_sentences = preprocess(new_sentences)
#logits = bert_model.forward()
probabilities = torch.nn.functional.softmax(logits, dim=-1)
predicted_classes = torch.argmax(probabilities, dim=-1)
print(predicted_classes)
不知道你这个问题是否已经解决, 如果还没有解决的话:Bert的输入要有三个向量:(1)input_ids (2)token_type_ids (3)attention_mask。这三个向量可以通过一行代码获得:
sentenceA = '等潮水退去,就知道谁没穿裤子'
text_dict = tokenizer.encode_plus(sentenceA, add_special_tokens=True, return_attention_mask=True)
针对问题中的张量输出结果,可以使用PyTorch中的item()方法获取张量中的值,并使用近似函数进行取整操作得到最终的预测类别标签。
具体实现步骤如下:
将输出的张量中的值取出,用item()方法将其转换为标量。
对取出的标量进行四舍五入的操作,使用Python内置的round()函数实现。
将四舍五入后的结果转换为整数类型,使用Python内置的int()函数实现。
将整数类型的结果作为最终的预测类别标签返回。
代码实现如下:
# 模型预测
with torch.no_grad():
output = model(input_ids, attention_mask, token_type_ids)
logits = output[0]
preds = torch.argmax(logits, dim=1)
pred_label = int(round(preds.item()))
print("预测类别标签为:", pred_label)
其中,preds.item()用于获取张量中的值,int()函数用于将四舍五入后的标量转换为整数类型,round()函数用于实现四舍五入操作。