Create model.py
Browse files
model.py
ADDED
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from torch import nn
|
2 |
+
from transformers import BertModel
|
3 |
+
import logging
|
4 |
+
from transformers.modeling_outputs import TokenClassifierOutput
|
5 |
+
|
6 |
+
|
7 |
+
class BertClassifier(nn.Module):
|
8 |
+
def __init__(self, bert_model="Sifal/dzarabert", num_labels=2, dropout=0.1):
|
9 |
+
super().__init__()
|
10 |
+
self.bert = BertModel.from_pretrained(bert_model)
|
11 |
+
self.num_labels = num_labels
|
12 |
+
self.classifier = nn.Sequential(
|
13 |
+
nn.Linear(self.bert.config.hidden_size, self.bert.config.hidden_size),
|
14 |
+
nn.ReLU(),
|
15 |
+
nn.Dropout(dropout),
|
16 |
+
nn.Linear(self.bert.config.hidden_size, num_labels))
|
17 |
+
|
18 |
+
def forward(self, input_ids=None, attention_mask=None,labels=None):
|
19 |
+
output = self.bert(input_ids, attention_mask=attention_mask)
|
20 |
+
logits = self.classifier(output.pooler_output)
|
21 |
+
loss = None
|
22 |
+
if labels is not None:
|
23 |
+
loss_fct = nn.CrossEntropyLoss()
|
24 |
+
loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
|
25 |
+
return TokenClassifierOutput(loss=loss, logits=logits, hidden_states=output.hidden_states,attentions=output.attentions)
|