如何在BERT中输出输出图层的输出权重?

问题描述 投票:0回答:1

我想在BERT中打印输出矢量/张量,但不确定如何执行。我一直在使用以下示例逐步介绍它:

https://colab.research.google.com/drive/1pTuQhug6Dhl9XalKB0zUGf4FIdYFlpcX

这是一个简单的分类问题,但是我希望能够在对训练示例进行分类之前获得输出向量。有人可以指出我可以在代码中的何处以及如何执行此操作吗?

nlp stanford-nlp bert
1个回答
0
投票

您想要权重到输出层还是logit?我认为您想要logit,从长远来看,这是更多的工作,但从长远来看更好,因此您可以自己使用它。在这里,我做了子类的一部分,我想要辍学和更多控制。我将其包括在此处,您可以在其中访问模型的所有部分

class MyBert(BertPreTrainedModel):
    def __init__(self, config, dropout_prob):
        super().__init__(config)
        self.num_labels = 2

        self.bert = BertModel(config)
        self.dropout = torch.nn.Dropout(dropout_prob)
        self.classifier = torch.nn.Linear(config.hidden_size, self.num_labels)

        self.init_weights()

    def forward(self,
        input_ids=None,
        attention_mask=None,
        token_type_ids=None,
        position_ids=None,
        head_mask=None,
        inputs_embeds=None,
        labels=None,):

        outputs = self.bert(
            input_ids,
            attention_mask=attention_mask,
            token_type_ids=token_type_ids,
            position_ids=position_ids,
            head_mask=head_mask,
            inputs_embeds=inputs_embeds,
        )

        pooled_output = outputs[1]

        pooled_output = self.dropout(pooled_output)
        logits = self.classifier(pooled_output)

        outputs = (logits,) + outputs[2:]  # add hidden states and attention if they are here
        if labels is not None:
            loss_fct = torch.nn.CrossEntropyLoss()
            loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
            outputs = (loss,) + outputs

        return outputs  # (loss), logits, (hidden_states), (attentions)
© www.soinside.com 2019 - 2024. All rights reserved.