| 33 | |
| 34 | |
| 35 | class Model(nn.Module): |
| 36 | |
| 37 | def __init__(self, config): |
| 38 | super(Model, self).__init__() |
| 39 | self.bert = BertModel.from_pretrained(config.bert_path) |
| 40 | for param in self.bert.parameters(): |
| 41 | param.requires_grad = True |
| 42 | self.convs = nn.ModuleList( |
| 43 | [nn.Conv2d(1, config.num_filters, (k, config.hidden_size)) for k in config.filter_sizes]) |
| 44 | self.dropout = nn.Dropout(config.dropout) |
| 45 | |
| 46 | self.fc_cnn = nn.Linear(config.num_filters * len(config.filter_sizes), config.num_classes) |
| 47 | |
| 48 | def conv_and_pool(self, x, conv): |
| 49 | x = F.relu(conv(x)).squeeze(3) |
| 50 | x = F.max_pool1d(x, x.size(2)).squeeze(2) |
| 51 | return x |
| 52 | |
| 53 | def forward(self, x): |
| 54 | context = x[0] # 输入的句子 |
| 55 | mask = x[2] # 对padding部分进行mask,和句子一个size,padding部分用0表示,如:[1, 1, 1, 1, 0, 0] |
| 56 | encoder_out, text_cls = self.bert(context, attention_mask=mask, output_all_encoded_layers=False) |
| 57 | out = encoder_out.unsqueeze(1) |
| 58 | out = torch.cat([self.conv_and_pool(out, conv) for conv in self.convs], 1) |
| 59 | out = self.dropout(out) |
| 60 | out = self.fc_cnn(out) |
| 61 | return out |
nothing calls this directly
no outgoing calls
no test coverage detected