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 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188
| import torch from torch.utils.data import Dataset, DataLoader import torch.nn.functional as F from transformers import BertTokenizer, BertModel import pandas as pd import time import numpy as np
device = torch.device("cuda" if torch.cuda.is_available() else "cpu") print("当前运行设备为: {} ".format(device))
tokenizer = BertTokenizer.from_pretrained('../bert-base-uncased')
class MyData(Dataset): def __init__(self, fp): xy = pd.read_csv(fp) self.len = len(xy) self.x_data = tokenizer(xy.text.values.tolist(), padding='max_length', max_length=102, truncation=True) self.x_input_ids = torch.Tensor(self.x_data['input_ids']) self.x_token_type_ids = torch.Tensor(self.x_data['token_type_ids']) self.x_attention_mask = torch.Tensor(self.x_data['attention_mask']) self.y_data = torch.Tensor(xy.label.values.tolist())
def __getitem__(self, index): return self.x_input_ids[index], self.x_token_type_ids[index], self.x_attention_mask[index], self.y_data[index]
def __len__(self): return self.len
train_data = MyData('imdbsTrain.csv') test_data = MyData('imdbsTest.csv')
train_loader = DataLoader(dataset=train_data, batch_size=16, shuffle=True) test_loader = DataLoader(dataset=test_data, batch_size=16)
class MyModel(torch.nn.Module): def __init__(self): super(MyModel, self).__init__() self.bert = BertModel.from_pretrained('../bert-base-uncased') self.linear1 = torch.nn.Linear(768, 192) self.linear2 = torch.nn.Linear(192, 96) self.linear3 = torch.nn.Linear(96, 1) self.dropout = torch.nn.Dropout(0.2)
def forward(self, input_ids, token_type_ids, attention_mask): input_ids = input_ids.long() token_type_ids = token_type_ids.long() attention_mask = attention_mask.long() output = self.bert(input_ids=input_ids, attention_mask=attention_mask, token_type_ids=token_type_ids) output = output['pooler_output'] output = F.relu(self.linear1(output)) output = F.relu(self.linear2(output)) output = self.dropout(output) output = F.sigmoid(self.linear3(output)) return output
seed = 100 if device == 'cuda': torch.cuda.manual_seed(seed) else: torch.manual_seed(seed)
model = MyModel() model.to(device)
lr = 0.01 epoch = 60
criterion = torch.nn.BCELoss(reduction='mean')
optimizer = torch.optim.SGD(model.parameters(), lr=lr)
if __name__ == '__main__': for i in range(epoch): model.train() losses = [] accuracy = [] start_time = time.time()
for batch, data in enumerate(train_loader, 0): input_ids, token_type_ids, attention_mask, labels = data input_ids, token_type_ids, attention_mask, labels = input_ids.to(device), token_type_ids.to( device), attention_mask.to(device), labels.to(device)
y_pred = model(input_ids, token_type_ids, attention_mask) labels = labels.unsqueeze(1)
loss = criterion(y_pred, labels) losses.append(loss.item())
pred_labels = [] for p in y_pred: if p.item() > 0.5: pred_labels.append(1) else: pred_labels.append(0) pred_labels = torch.Tensor(pred_labels).unsqueeze(1) pred_labels = pred_labels.to(device) acc = torch.sum(pred_labels == labels).item() / len(pred_labels) accuracy.append(acc)
optimizer.zero_grad() loss.backward() optimizer.step()
elapsed_time = time.time() - start_time print("\nEpoch: {}/{}: ".format(i + 1, epoch), "Loss: {:.6f}; ".format(np.mean(losses)), "Accuracy: {:.6f}; ".format(np.mean(accuracy)), 'Time: {:.2f}s'.format(elapsed_time))
with torch.no_grad(): model.eval() eval_losses = [] eval_acc = [] eval_start_time = time.time() for batch, data in enumerate(test_loader, 0): input_ids, token_type_ids, attention_mask, labels = data input_ids, token_type_ids, attention_mask, labels = input_ids.to(device), token_type_ids.to( device), attention_mask.to(device), labels.to(device)
y_pred = model(input_ids, token_type_ids, attention_mask) labels = labels.unsqueeze(1)
loss = criterion(y_pred, labels) eval_losses.append(loss.item())
pred_labels = [] for p in y_pred: if p.item() > 0.5: pred_labels.append(1) else: pred_labels.append(0) pred_labels = torch.Tensor(pred_labels).unsqueeze(1) pred_labels = pred_labels.to(device) acc = torch.sum(pred_labels == labels).item() / len(pred_labels) eval_acc.append(acc)
elapsed_time = time.time() - eval_start_time print("\nEval_loss: {:.6f}; ".format(np.mean(eval_losses)), "Accuracy: {:.6f}; ".format(np.mean(eval_acc)), 'Time: {:.2f}s'.format(elapsed_time))
|