【发布时间】:2020-05-09 01:34:50
【问题描述】:
我试图在 huggingface bert 转换器之后添加一个额外的层,所以我在我的 nn.Module 网络中使用了 BertForSequenceClassification。但是,与直接加载模型相比,我发现模型给了我随机输出。
模型 1:
from transformers import BertForSequenceClassification
model = BertForSequenceClassification.from_pretrained('bert-base-uncased', num_labels = 5) # as we have 5 classes
import torch
from transformers import BertTokenizer
tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
input_ids = torch.tensor(tokenizer.encode(texts[0], add_special_tokens=True, max_length = 512)).unsqueeze(0) # Batch size 1
print(model(input_ids))
输出:
(tensor([[ 0.3610, -0.0193, -0.1881, -0.1375, -0.3208]],
grad_fn=<AddmmBackward>),)
模型 2:
import torch
from torch import nn
class BertClassifier(nn.Module):
def __init__(self):
super(BertClassifier, self).__init__()
self.bert = BertForSequenceClassification.from_pretrained('bert-base-uncased', num_labels = 5)
# as we have 5 classes
# we want our output as probability so, in the evaluation mode, we'll pass the logits to a softmax layer
self.softmax = torch.nn.Softmax(dim = 1) # last dimension
def forward(self, x):
print(x.shape)
x = self.bert(x)
if self.training == False: # in evaluation mode
pass
#x = self.softmax(x)
return x
# create our model
bertclassifier = BertClassifier()
print(bertclassifier(input_ids))
torch.Size([1, 512])
torch.Size([1, 5])
(tensor([[-0.3729, -0.2192, 0.1183, 0.0778, -0.2820]],
grad_fn=<AddmmBackward>),)
它们应该是相同的型号,对吧。我在这里发现了类似的问题,但没有合理的解释https://github.com/huggingface/transformers/issues/2770
Bert 是否有一些随机化的参数,如果有,如何获得可重现的输出?
为什么这两个模型给我不同的输出?是不是我做错了什么?
【问题讨论】:
标签: python-3.x pytorch huggingface-transformers bert-language-model