【发布时间】:2019-10-23 04:23:36
【问题描述】:
【问题讨论】:
标签: pytorch
【问题讨论】:
标签: pytorch
我想向您指出BertForSequenceClassification 的定义,您可以使用以下方法轻松避免丢失和分类器:
model = BertForSequenceClassification.from_pretrained("bert-base-uncased", num_labels=2)
model.bert() # this will give you the dense layer output
为什么你可以做到以上几点?如果你看一下 BertForSequenceClassification 的构造函数:
def __init__(self, config):
super(BertForSequenceClassification, self).__init__(config)
self.num_labels = config.num_labels
self.bert = BertModel(config)
self.dropout = nn.Dropout(config.hidden_dropout_prob)
self.classifier = nn.Linear(config.hidden_size, self.config.num_labels)
self.init_weights()
如您所见,您只想忽略 dropout 和 classifier 层。
还有一点,冻结图层和移除图层是两件不同的事情。在您的问题中,您提到要冻结分类器层,但冻结层不会帮助您避免它。冻结意味着,您不想训练图层。
【讨论】:
model = BertForSequenceClassification.from_pretrained("bert-base-uncased", num_labels=2) model.bert() # this will give you the dense layer output?
您已经有密集层作为输出 (Linear)。
没有必要冻结dropout,因为它只会在训练期间扩展激活。
您可以将其设置为evaluation 模式(基本上此层之后将不执行任何操作),通过发出:
model.dropout.eval()
虽然通过model.train()将整个模型设置为train会有所改变,但请注意这一点。
要冻结最后一层的权重,您可以发出:
model.classifier.weight.requires_grad_(False)
(或者bias,如果你是这样的话)
如果您想将最后一层更改为另一个形状而不是(768, 2),只需用另一个模块覆盖它,例如
model.classifier = torch.nn.Linear(768, 10)
对于大小为10 的输出张量(输入形状必须与模型中指定的形状完全相同,因此768)
【讨论】:
model.classifier.weight.requires_grad_(False)?