-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmindTrain.py
170 lines (135 loc) · 5.33 KB
/
mindTrain.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
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
import os
import numpy as np
import sklearn
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import sys
from mlflow import log_metric, log_param, log_artifacts
# Specify a path
train_datapath = "dataset/train"
val_datapath= "dataset/val"
ACTION = ['go_still', 'none_still']
class ConvNet(nn.Module):
def __init__(self, output_size=3):
super(ConvNet, self).__init__()
self.conv1_1 = nn.Conv1d(8, 6, 2, stride=1)
self.maxpl_1 = nn.MaxPool1d(2, stride=1)
self.conv1_2 = nn.Conv1d(6, 6, 3, stride=1)
self.maxpl_2 = nn.MaxPool1d(2, stride=2)
self.o2s = nn.Linear(168, output_size)
self.softmax = nn.LogSoftmax(dim=1)
def forward(self, input_seq):
output = self.conv1_1(input_seq)
output = self.maxpl_1(output)
output = self.conv1_2(output)
output = self.maxpl_2(output)
output = output.reshape(-1, 168)
output = self.o2s(output)
output = self.softmax(output)
return output
def getData(datapath):
data = []
labels = []
for action in ACTION:
action_dir = os.path.join(datapath, action)
for session_file in os.listdir(action_dir):
filepath = os.path.join(action_dir, session_file)
file = np.load(filepath)
for idx, line in enumerate(file):
data.append(line)
if action == ACTION[0]:
labels.append(torch.tensor(0))
elif action == ACTION[1]:
labels.append(torch.tensor(1))
elif action == ACTION[2]:
labels.append(torch.tensor(2))
print('Data Loaded')
return data, labels
def get_num_correct(preds, labels):
if preds == labels:
return 1
return 0
def train(network, optimizer, train_set, train_labels, batch_size=1):
training_size = len(train_set)
network.train()
correct_in_episode = 0
episode_loss = 0
nbr = 1
for index, data in enumerate(train_set):
labels = train_labels[index]
data = torch.FloatTensor(data)
loss = 0
optimizer.zero_grad()
output = network(data.unsqueeze(0))
l = F.cross_entropy(output.float(), labels.unsqueeze(0).long())
loss += l
loss.backward()
optimizer.step()
episode_loss += loss.item()
correct_in_episode += get_num_correct(torch.argmax(output), labels)
nbr += 1
if nbr % 10 == 0:
print(f'advancement: {nbr * 100 / training_size:.2f} % ', ' || correct:', correct_in_episode * 100 / nbr)
return episode_loss, correct_in_episode * 100 / training_size
def test(network, test_set, test_labels, batch_size=1):
testing_size = len(test_set)
network.eval()
episode_loss = 0
correct_in_episode = 0
nbr = 0
with torch.no_grad():
for index, data in enumerate(test_set):
labels = test_labels[index]
data = torch.FloatTensor(data)
loss = 0
output = network(data.unsqueeze(0))
l = F.cross_entropy(output.float(), labels.unsqueeze(0).long())
loss += l
episode_loss += loss.item()
correct_in_episode += get_num_correct(torch.argmax(output), labels)
nbr += 1
if nbr % 100 == 0:
print(f'advancement: {nbr * 100 / testing_size:.2f} % ' ' || correct:', correct_in_episode * 100 / nbr)
return episode_loss, correct_in_episode * 100 / testing_size
data, labels = getData(train_datapath)
print('Train data Created')
print('Number of files:', len(data), len(labels), '\nShape:', data[0].shape, labels[0], '\n------\n')
val_data, val_labels = getData(val_datapath)
print('Validation data Created')
print('Number of files:', len(val_data), len(val_labels), '\nShape:', val_data[0].shape, labels[0], '\n------\n')
# Data Format:
# data[xxxx entries][16 electrodes][60 FFT data]
data, labels = sklearn.utils.shuffle(data, labels)
val_data, val_labels = sklearn.utils.shuffle(val_data, val_labels)
print('Data Successfully shuffled\n------\n')
epochs = 4
n_categories = 2
learing_rate = 0.0005
batch_size = 1
log_param("EPOCHS", epochs)
log_param("LR", learing_rate)
ConvNet = ConvNet(output_size=2)
optimizer = optim.Adam(ConvNet.parameters(), learing_rate)
print('Network initialized\n------\n')
training_losses = []
testing_losses = []
training_accuracies = []
testing_accuracies = []
for epoch in range(epochs):
print('EPOCH', epoch, ':\n')
training_loss, training_accuracy = train(ConvNet, optimizer, data, labels, batch_size=batch_size)
training_losses.append(training_loss)
training_accuracies.append(training_accuracy)
log_metric("train_acc", training_accuracy)
log_metric("train_loss", training_loss)
print('training loss:', f'{training_loss:.2f}', 'trainning accuracy:', f'{training_accuracy:.2f}')
testing_loss, testing_accuracy = test(ConvNet, val_data, val_labels, batch_size=batch_size)
print('testing loss:', f'{testing_loss:.2f}', 'testing accuracy:', f'{testing_accuracy:.2f}')
testing_losses.append(testing_loss)
testing_accuracies.append(testing_accuracy)
log_metric("test_acc", testing_accuracy)
log_metric("test_loss", testing_loss)
torch.save(ConvNet.state_dict(), f'models/still/{testing_accuracy:.2f}.pt')
print('DONE')