Commit
·
fa750e4
1
Parent(s):
95912a1
Update DistilBERT.py
Browse files- DistilBERT.py +69 -2
DistilBERT.py
CHANGED
|
@@ -11,6 +11,7 @@ import pandas as pd
|
|
| 11 |
import numpy as np
|
| 12 |
|
| 13 |
# Điều chỉnh các tham số
|
|
|
|
| 14 |
MAX_LEN = 100
|
| 15 |
TRAIN_BATCH_SIZE = 4
|
| 16 |
VALID_BATCH_SIZE = 4
|
|
@@ -19,7 +20,11 @@ LEARNING_RATE = 1e-05
|
|
| 19 |
tokenizer_DB = DistilBertTokenizer.from_pretrained('distilbert-base-uncased', truncation=True, do_lower_case=True)
|
| 20 |
|
| 21 |
# Tạo dataframe
|
| 22 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 23 |
|
| 24 |
# Tạo class
|
| 25 |
class BinaryLabel(Dataset):
|
|
@@ -72,4 +77,66 @@ training_set = BinaryLabel(train_df_DB, tokenizer, MAX_LEN)
|
|
| 72 |
testing_set = BinaryLabel(test_df_DB, tokenizer, MAX_LEN)
|
| 73 |
|
| 74 |
training_loader = DataLoader(training_set, **train_params)
|
| 75 |
-
testing_loader = DataLoader(testing_set, **test_params)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
import numpy as np
|
| 12 |
|
| 13 |
# Điều chỉnh các tham số
|
| 14 |
+
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
|
| 15 |
MAX_LEN = 100
|
| 16 |
TRAIN_BATCH_SIZE = 4
|
| 17 |
VALID_BATCH_SIZE = 4
|
|
|
|
| 20 |
tokenizer_DB = DistilBertTokenizer.from_pretrained('distilbert-base-uncased', truncation=True, do_lower_case=True)
|
| 21 |
|
| 22 |
# Tạo dataframe
|
| 23 |
+
train_df_DB = pd.read_csv('./data/train.csv')
|
| 24 |
+
train_df_DB['label'] = train_df_DB.iloc[:, 1:].values.tolist()
|
| 25 |
+
test_df_DB = pd.read_csv('./data/test.csv')
|
| 26 |
+
test_df_DB = test_df_DB[['text', 'preprocess_sentence', 'label']]
|
| 27 |
+
test_df_DB['label'] = test_df_DB.iloc[:, 2:].values.tolist()
|
| 28 |
|
| 29 |
# Tạo class
|
| 30 |
class BinaryLabel(Dataset):
|
|
|
|
| 77 |
testing_set = BinaryLabel(test_df_DB, tokenizer, MAX_LEN)
|
| 78 |
|
| 79 |
training_loader = DataLoader(training_set, **train_params)
|
| 80 |
+
testing_loader = DataLoader(testing_set, **test_params)
|
| 81 |
+
|
| 82 |
+
# Create model
|
| 83 |
+
class DistilBERTClass(torch.nn.Module):
|
| 84 |
+
def __init__(self):
|
| 85 |
+
super(DistilBERTClass, self).__init__()
|
| 86 |
+
self.l1 = DistilBertModel.from_pretrained("distilbert-base-uncased")
|
| 87 |
+
self.pre_classifier = torch.nn.Linear(768, 768)
|
| 88 |
+
self.dropout = torch.nn.Dropout(0.1)
|
| 89 |
+
self.classifier = torch.nn.Linear(768, 1)
|
| 90 |
+
|
| 91 |
+
def forward(self, input_ids, attention_mask, token_type_ids):
|
| 92 |
+
output_1 = self.l1(input_ids=input_ids, attention_mask=attention_mask)
|
| 93 |
+
hidden_state = output_1[0]
|
| 94 |
+
pooler = hidden_state[:, 0]
|
| 95 |
+
pooler = self.pre_classifier(pooler)
|
| 96 |
+
pooler = torch.nn.ReLU()(pooler)
|
| 97 |
+
pooler = self.dropout(pooler)
|
| 98 |
+
output = self.classifier(pooler)
|
| 99 |
+
return output
|
| 100 |
+
|
| 101 |
+
model_DB = DistilBERTClass()
|
| 102 |
+
model_DB.to(device)
|
| 103 |
+
|
| 104 |
+
# Validation function
|
| 105 |
+
def validation(testing_loader):
|
| 106 |
+
model_DB.eval()
|
| 107 |
+
fin_targets=[]
|
| 108 |
+
fin_outputs=[]
|
| 109 |
+
with torch.no_grad():
|
| 110 |
+
for _, data in tqdm(enumerate(testing_loader, 0)):
|
| 111 |
+
ids = data['ids'].to(device, dtype = torch.long)
|
| 112 |
+
mask = data['mask'].to(device, dtype = torch.long)
|
| 113 |
+
token_type_ids = data['token_type_ids'].to(device, dtype = torch.long)
|
| 114 |
+
targets = data['targets'].to(device, dtype = torch.float)
|
| 115 |
+
outputs = model_DB(ids, mask, token_type_ids)
|
| 116 |
+
fin_targets.extend(targets.cpu().detach().numpy().tolist())
|
| 117 |
+
fin_outputs.extend(torch.sigmoid(outputs).cpu().detach().numpy().tolist())
|
| 118 |
+
return fin_outputs, fin_targets
|
| 119 |
+
|
| 120 |
+
# Train function
|
| 121 |
+
def train(epoch):
|
| 122 |
+
model.train()
|
| 123 |
+
for _,data in tqdm(enumerate(training_loader, 0)):
|
| 124 |
+
ids = data['ids'].to(device, dtype = torch.long)
|
| 125 |
+
mask = data['mask'].to(device, dtype = torch.long)
|
| 126 |
+
token_type_ids = data['token_type_ids'].to(device, dtype = torch.long)
|
| 127 |
+
targets = data['targets'].to(device, dtype = torch.float)
|
| 128 |
+
|
| 129 |
+
outputs = model(ids, mask, token_type_ids)
|
| 130 |
+
|
| 131 |
+
optimizer.zero_grad()
|
| 132 |
+
loss = loss_fn(outputs, targets)
|
| 133 |
+
if _%50==0:
|
| 134 |
+
print(f'Epoch: {epoch}, Loss: {loss.item()}')
|
| 135 |
+
if loss.item() < 0.07:
|
| 136 |
+
print(f'Breaking the loop as loss is below 0.07: {loss.item()}')
|
| 137 |
+
break
|
| 138 |
+
loss.backward()
|
| 139 |
+
optimizer.step()
|
| 140 |
+
|
| 141 |
+
for epoch in range(3):
|
| 142 |
+
train(epoch)
|