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
| import torch from datasets import load_dataset from torch.utils.data import Dataset from torch.utils.data import DataLoader import torch.nn as nn from transformers import BertTokenizer, BertModel import torch.optim as optim from torch.nn.functional import one_hot import pytorch_lightning as pl from pytorch_lightning import Trainer from torchmetrics.functional import accuracy, recall, precision, f1_score from pytorch_lightning.callbacks.early_stopping import EarlyStopping from pytorch_lightning.callbacks import ModelCheckpoint
class MydataSet(Dataset): def __init__(self, path, split): self.dataset = load_dataset('csv', data_files=path, split=split)
def __getitem__(self, item): text = self.dataset[item]['text'] label = self.dataset[item]['label'] return text, label
def __len__(self): return len(self.dataset)
def collate_fn(data): sents = [i[0] for i in data] labels = [i[1] for i in data]
data = token.batch_encode_plus( batch_text_or_text_pairs=sents, truncation=True, padding='max_length', max_length=200, return_tensors='pt', return_length=True, )
input_ids = data['input_ids'] attention_mask = data['attention_mask'] token_type_ids = data['token_type_ids'] labels = torch.LongTensor(labels)
return input_ids, attention_mask, token_type_ids, labels
class BiLSTMClassifier(nn.Module): def __init__(self, drop, hidden_dim, output_dim): super(BiLSTMClassifier, self).__init__() self.drop = drop self.hidden_dim = hidden_dim self.output_dim = output_dim
self.embedding = BertModel.from_pretrained('bert-base-chinese') for param in self.embedding.parameters(): param.requires_grad_(False) self.lstm = nn.LSTM(input_size=768, hidden_size=self.hidden_dim, num_layers=2, batch_first=True, bidirectional=True, dropout=self.drop) self.fc = nn.Linear(self.hidden_dim * 2, self.output_dim)
def forward(self, input_ids, attention_mask, token_type_ids): embedded = self.embedding(input_ids=input_ids, attention_mask=attention_mask, token_type_ids=token_type_ids) embedded = embedded.last_hidden_state out, (h_n, c_n) = self.lstm(embedded) output = torch.cat((h_n[-2, :, :], h_n[-1, :, :]), dim=1) output = self.fc(output) return output
class BiLSTMLighting(pl.LightningModule): def __init__(self, drop, hidden_dim, output_dim): super(BiLSTMLighting, self).__init__() self.model = BiLSTMClassifier(drop, hidden_dim, output_dim) self.criterion = nn.CrossEntropyLoss() self.train_dataset = MydataSet('./data/archive/train_clean.csv', 'train') self.val_dataset = MydataSet('./data/archive/val_clean.csv', 'train') self.test_dataset = MydataSet('./data/archive/test_clean.csv', 'train')
def configure_optimizers(self): optimizer = optim.AdamW(self.parameters(), lr=lr) return optimizer
def forward(self, input_ids, attention_mask, token_type_ids): return self.model(input_ids, attention_mask, token_type_ids)
def train_dataloader(self): train_loader = DataLoader(dataset=self.train_dataset, batch_size=batch_size, collate_fn=collate_fn, shuffle=True) return train_loader
def training_step(self, batch, batch_idx): input_ids, attention_mask, token_type_ids, labels = batch y = one_hot(labels + 1, num_classes=3) y = y.to(dtype=torch.float) y_hat = self.model(input_ids, attention_mask, token_type_ids) y_hat = y_hat.squeeze() loss = self.criterion(y_hat, y) self.log('train_loss', loss, prog_bar=True, logger=True, on_step=True, on_epoch=True) return loss
def val_dataloader(self): val_loader = DataLoader(dataset=self.val_dataset, batch_size=batch_size, collate_fn=collate_fn, shuffle=False) return val_loader
def validation_step(self, batch, batch_idx): input_ids, attention_mask, token_type_ids, labels = batch y = one_hot(labels + 1, num_classes=3) y = y.to(dtype=torch.float) y_hat = self.model(input_ids, attention_mask, token_type_ids) y_hat = y_hat.squeeze() loss = self.criterion(y_hat, y) self.log('val_loss', loss, prog_bar=False, logger=True, on_step=True, on_epoch=True) return loss
def test_dataloader(self): test_loader = DataLoader(dataset=self.test_dataset, batch_size=batch_size, collate_fn=collate_fn, shuffle=False) return test_loader
def test_step(self, batch, batch_idx): input_ids, attention_mask, token_type_ids, labels = batch target = labels + 1 y = one_hot(target, num_classes=3) y = y.to(dtype=torch.float) y_hat = self.model(input_ids, attention_mask, token_type_ids) y_hat = y_hat.squeeze() pred = torch.argmax(y_hat, dim=1) acc = (pred == target).float().mean()
loss = self.criterion(y_hat, y) self.log('loss', loss) re = recall(pred, target, task="multiclass", num_classes=class_num, average=None) pre = precision(pred, target, task="multiclass", num_classes=class_num, average=None) f1 = f1_score(pred, target, task="multiclass", num_classes=class_num, average=None)
def log_score(name, scores): for i, score_class in enumerate(scores): self.log(f"{name}_class{i}", score_class)
log_score("recall", re) log_score("precision", pre) log_score("f1", f1) self.log('acc', accuracy(pred, target, task="multiclass", num_classes=class_num)) self.log('avg_recall', recall(pred, target, task="multiclass", num_classes=class_num, average="weighted")) self.log('avg_precision', precision(pred, target, task="multiclass", num_classes=class_num, average="weighted")) self.log('avg_f1', f1_score(pred, target, task="multiclass", num_classes=class_num, average="weighted"))
def test(): model = BiLSTMLighting.load_from_checkpoint(checkpoint_path=PATH, drop=dropout, hidden_dim=rnn_hidden, output_dim=class_num) trainer = Trainer(fast_dev_run=False) result = trainer.test(model) print(result)
|