-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtrain.py
More file actions
152 lines (117 loc) · 4.1 KB
/
Copy pathtrain.py
File metadata and controls
152 lines (117 loc) · 4.1 KB
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
import os
import torch
import torch.nn as nn
from tqdm import tqdm
from torch.optim.adam import Adam
from torch.utils.data import DataLoader
from model import KhmerTagger
from dataset import TextDataset
from config import TAGS_PUNCT, TAGS_NUM
if __name__ == "__main__":
lr = 5e-6
n_epoch = 50
device = "cuda" if torch.cuda.is_available() else "cpu"
train_set = TextDataset("data/train.txt")
val_set = TextDataset("data/dev.txt")
train_loader = DataLoader(train_set, batch_size=32, shuffle=True, num_workers=1)
val_loader = DataLoader(
train_set, batch_size=32, shuffle=False, num_workers=1, drop_last=False
)
model = KhmerTagger(
n_punct_features=len(TAGS_PUNCT), n_num_features=len(TAGS_NUM)
).to(device)
criterion = nn.CrossEntropyLoss()
optimizer = Adam(model.parameters(), lr=lr)
best_val_acc = 0.0
# training
for epoch in range(n_epoch):
train_loss = 0.0
train_iteration = 0
correct = 0
total = 0
model.train()
for x, y_punct, y_num, att, y_mask in tqdm(train_loader, desc="train"):
x, y_punct, y_num, att, y_mask = (
x.to(device),
y_punct.to(device),
y_num.to(device),
att.to(device),
y_mask.to(device),
)
y_mask = y_mask.view(-1)
y_punct = y_punct.view(-1)
y_num = y_num.view(-1)
# forward
y_punct_predict, y_num_predict = model(x, att)
# reshape
y_punct_predict = y_punct_predict.view(-1, y_punct_predict.shape[2])
y_num_predict = y_num_predict.view(-1, y_num_predict.shape[2])
# compute loss
loss_punct = criterion(y_punct_predict, y_punct)
loss_num = criterion(y_num_predict, y_num)
# weight
w = 0.25
loss = loss_punct * (1 - w) + loss_num * w
# punct
y_punct_predict = torch.argmax(y_punct_predict, dim=1).view(-1)
correct += torch.sum(y_mask * (y_punct_predict == y_punct).long()).item()
# num
y_num_predict = torch.argmax(y_num_predict, dim=1).view(-1)
correct += torch.sum(y_mask * (y_num_predict == y_num).long()).item()
optimizer.zero_grad()
train_loss += loss.item()
train_iteration += 1
loss.backward()
optimizer.step()
y_mask = y_mask.view(-1)
total += torch.sum(y_mask).item() * 2
# print
train_loss /= train_iteration
print(
f"epoch: {epoch}, Train loss: {train_loss}, Train accuracy: {correct / total}"
)
# Evaluation
num_iteration = 0
correct = 0
total = 0
val_loss = 0
model.eval()
with torch.no_grad():
for x, y_punct, y_num, att, y_mask in tqdm(val_loader, desc="eval"):
x, y_punct, y_num, att, y_mask = (
x.to(device),
y_punct.to(device),
y_num.to(device),
att.to(device),
y_mask.to(device),
)
y_mask = y_mask.view(-1)
y_punct = y_punct.view(-1)
y_num = y_num.view(-1)
# forward
y_punct_predict, y_num_predict = model(x, att)
# reshape
y_punct_predict = y_punct_predict.view(-1, y_punct_predict.shape[2])
y_num_predict = y_num_predict.view(-1, y_num_predict.shape[2])
# compute loss
loss_punct = criterion(y_punct_predict, y_punct)
loss_num = criterion(y_num_predict, y_num)
# weight
w = 0.25
loss = loss_punct * (1 - w) + loss_num * w
# punct
y_punct_predict = torch.argmax(y_punct_predict, dim=1).view(-1)
correct += torch.sum(y_mask * (y_punct_predict == y_punct).long()).item()
# num
y_num_predict = torch.argmax(y_num_predict, dim=1).view(-1)
correct += torch.sum(y_mask * (y_num_predict == y_num).long()).item()
val_loss += loss.item()
num_iteration += 1
y_mask = y_mask.view(-1)
total += torch.sum(y_mask).item() * 2
val_acc, val_loss = correct / total, val_loss / num_iteration
print(f"epoch: {epoch}, Val loss: {val_loss}, Val accuracy: {val_acc}")
if val_acc > best_val_acc:
os.makedirs("logs", exist_ok=True)
torch.save(model.state_dict(), f"logs/checkpoint-{epoch}.pth")
best_val_acc = val_acc