-
Notifications
You must be signed in to change notification settings - Fork 0
/
train.py
95 lines (64 loc) · 2.29 KB
/
train.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
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
import numpy as np
import torch
import torch.optim as optim
from model import GestureClassifier
from data_loader import Dataset
from torch.utils.data import DataLoader
import torch.nn.functional as F
import matplotlib.pyplot as plt
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
losses = []
PATH = 'model.pth'
def train(model, train_loader, optimizer):
model.train()
train_loss = 0
for batch, data in enumerate(train_loader, 1):
(accel, gyro) = data['input']
label = data['label']
label = label.to(device)
out = model(accel.to(device), gyro.to(device))
optimizer.zero_grad()
loss = F.cross_entropy(out, label)
loss.backward()
optimizer.step()
train_loss += loss.item()
train_loss /= len(train_loader.dataset)
return train_loss
def evaluate(model, test_loader):
model.eval()
correct = 0
with torch.no_grad():
for batch, data in enumerate(test_loader, 1):
(accel, gyro) = data['input']
label = data['label']
label = label.to(device)
out = model(accel.to(device), gyro.to(device))
pred = out.max(1, keepdim=True)[1]
correct += pred.eq(label.view_as(pred)).sum().item()
test_accuracy = 100. * correct / len(test_loader.dataset)
return test_accuracy
def main():
model = GestureClassifier(15 * 3).to(device)
optimizer = optim.Adam(model.parameters(), lr=1e-4)
dataset_train = Dataset(data_dir='data/train', transform=None)
loader_train = DataLoader(dataset_train, batch_size=1000, shuffle=False, num_workers=0)
dataset_test = Dataset(data_dir='data/val', transform=None)
loader_test = DataLoader(dataset_test, batch_size=1000, shuffle=False, num_workers=0)
accuracies = []
print('학습 시작')
for i in range(300):
loss = train(model, loader_train, optimizer)
losses.append(loss)
accuracy = evaluate(model, loader_test)
accuracies.append(accuracy)
print('epoch : ', i)
torch.save(model, PATH)
plt.title('loss')
plt.plot(range(len(losses)), losses)
plt.show()
plt.title('accuracy')
plt.plot(range(len(accuracies)), accuracies)
plt.ylim(0, 100)
plt.show()
if __name__ == "__main__":
main()