-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbert.py
68 lines (47 loc) · 2.34 KB
/
bert.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import numpy as np
import torch
import torch.nn as nn
from torch.optim import lr_scheduler
from torch.utils.data import Dataset, DataLoader
from pytorch_pretrained_bert import BertTokenizer, BertModel
tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
class BertForSequenceClassification(nn.Module):
def __init__(self, config, num_labels=2):
super(BertForSequenceClassification, self).__init__()
self.num_labels = num_labels
self.config = config
self.bert = BertModel.from_pretrained('bert-base-uncased')
self.dropout = nn.Dropout(config.hidden_dropout_prob)
self.classifier = nn.Linear(config.hidden_size, num_labels)
nn.init.xavier_normal_(self.classifier.weight)
def forward(self, input_ids, token_type_ids=None, attention_mask=None, labels=None):
_, pooled_output = self.bert(input_ids, token_type_ids, attention_mask, output_all_encoded_layers=False)
pooled_output = self.dropout(pooled_output)
logits = self.classifier(pooled_output)
return logits
def freeze_bert_encoder(self):
for param in self.bert.parameters():
param.requires_grad = False
def unfreeze_bert_encoder(self):
for param in self.bert.parameters():
param.requires_grad = True
class text_dataset(Dataset):
def __init__(self, x_y_list, max_seq_length, transform=None):
self.x_y_list = x_y_list
self.transform = transform
self.max_seq_length = max_seq_length
def __getitem__(self,index):
tokenized_review = tokenizer.tokenize(self.x_y_list[0][index])
if len(tokenized_review) > self.max_seq_length:
tokenized_review = tokenized_review[:self.max_seq_length]
ids_review = tokenizer.convert_tokens_to_ids(tokenized_review)
padding = [0] * (self.max_seq_length - len(ids_review))
ids_review += padding
assert len(ids_review) == self.max_seq_length
#print(ids_review)
ids_review = torch.tensor(ids_review)
sentiment = self.x_y_list[1][index] # color
list_of_labels = [torch.from_numpy(np.array(sentiment))]
return ids_review, list_of_labels[0]
def __len__(self):
return len(self.x_y_list[0])