0

我可以用自己的数据冻结预训练的 bert 模型的所有层,只训练分类器层。

但我不只是训练分类器,而是想在 bert 的输出中添加一个 bilstm 层。我将冻结其他层,并且只训练这个 bi-lstm 层。所以这里bert实际上只是提供词嵌入。

不幸的是,我对 bilstm 架构有点不熟悉,所以训练期间张量大小不匹配,我遇到了错误。

这是模型类:

class PosTaggingModel(nn.Module):
    def __init__(self, num_pos_tag):
        super(PosTaggingModel, self).__init__()
        self.num_pos_tag = num_pos_tag
        self.model = AutoModel.from_pretrained("dbmdz/bert-base-turkish-cased")
        for name, param in self.model.named_parameters():
            if 'classifier' not in name: # classifier layer
                param.requires_grad = False
        self.lstm = nn.LSTM(768,256, bidirectional=True)
        self.linear = nn.Linear(256*2, self.num_pos_tag) 
    
    def forward(self, ids, mask, token_type_ids, target_pos_tag):
        o1, _ = self.model(ids, attention_mask = mask, token_type_ids = token_type_ids)
    
        lstm_output, _ = self.lstm(o1)
        hidden = torch.cat((lstm_output[:,-1, :256],lstm_output[:,0, 256:]),dim =-1)
        linear_output = self.linear(hidden.view(-1,256*2))
        loss = loss_fn(linear_output, target_pos_tag, mask, self.num_pos_tag)

我遇到的错误:

“预期输入 batch_size ({}) 与目标 batch_size ({}) 匹配。”.format(input.size(0), target.size(0)) ValueError:预期输入 batch_size (32) 与目标 batch_size (4096) 匹配.

我实际上可以将错误解释如下:由于这是一项较弱的任务,因此有必要进行与样本中的 max_len 数一样多的预测。因此,发送到损失函数的张量的尺寸应该是 [batch_size,max_len, num_of_layer] 但在我的代码中,张量的返回类似于 [batch_size,num_of_layer] ,即它只适用于分类任务。

但我想让它适合 ner 任务。我认为该错误将通过更改 cat 或 view 方法来解决,但不幸的是我找不到解决方案。

最后,如何保存我训练的 lstm 层的权重?(但只是 lstm 不是所有层,因为内存问题)也许我可以自己找到这个保存问题,但如果你知道并写,我将非常感激。

您还可以分享有关该主题的其他经验或建议。提前感谢那些花时间回复的人。

4

0 回答 0