-
Notifications
You must be signed in to change notification settings - Fork 2
/
EEGNet_training_ELU.py
172 lines (134 loc) · 5.89 KB
/
EEGNet_training_ELU.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
170
171
172
# -*- coding: utf-8 -*-
"""
Created on Fri Jul 9 17:01:35 2021
@author: haoyuan
"""
import torch
from torch.autograd import Variable
import torch.nn.functional as F
import torch.nn as nn
from dataloader import read_bci_data
import matplotlib.pyplot as plt
from torch.utils.data import TensorDataset,DataLoader
import numpy as np
import torch.optim as optim
from torchsummary import summary
import pandas as pd
import os
import argparse
def testing(x_test,y_test,model,device,filepath):
# model.load_state_dict(torch.load(filepath))
model.eval()
with torch.no_grad():
model.cuda(0)
n = x_test.shape[0]
x_test = x_test.astype("float32")
y_test = y_test.astype("float32").reshape(y_test.shape[0],)
x_test, y_test = Variable(torch.from_numpy(x_test)),Variable(torch.from_numpy(y_test))
x_test,y_test = x_test.to(device),y_test.to(device)
y_pred_test = model(x_test)
correct_test = (torch.max(y_pred_test,1)[1]==y_test).sum().item()
test_accuracy = correct_test/n
# print("testing accuracy:",correct/n)
return test_accuracy
parser = argparse.ArgumentParser()
parser.add_argument('--epochs', type=int, default='700', help='training epochs')
parser.add_argument('--learning_rate', type=float, default='1e-3', help='learning rate')
parser.add_argument('--save_model', action='store_true', help='check if you want to save the model.')
parser.add_argument('--save_csv', action='store_true', help='check if you want to save the training history.')
opt = parser.parse_args()
torch.manual_seed(1) # reproducible
epochs = 700
lr = 1e-3
filepath = os.path.abspath(os.path.dirname(__file__))+"\checkpoint\EEGNet_checkpoint_ELU.rar"
filepath_csv = os.path.abspath(os.path.dirname(__file__))+"\history_csv\EEGNet_ELU.csv"
min_loss=1
max_accuracy = 0
device = torch.device("cuda:0")
train_data, train_label, test_data, test_label = read_bci_data()
n = train_data.shape[0]
train_data = train_data.astype("float32")
train_label = train_label.astype("float32").reshape(train_label.shape[0],)
# train_data.shape = (1080,1,2,750)
# train_label.shape = (1080,)
# loader = DataLoader(TensorDataset(train_data,train_label),batch_size=8)
x, y = Variable(torch.from_numpy(train_data)),Variable(torch.from_numpy(train_label))
y=torch.tensor(y, dtype=torch.long)
class EEGNet_ELU(torch.nn.Module):
def __init__(self, n_output):
super(EEGNet_ELU, self).__init__()
self.firstConv = nn.Sequential(
nn.Conv2d(1, 16, kernel_size=(1,51), stride=(1,1), padding=(0,25),bias=False),
nn.BatchNorm2d(16, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
)
self.depthwiseConv = nn.Sequential(
nn.Conv2d(16, 32, kernel_size=(2,1), stride=(1,1), groups=8,bias=False),
nn.BatchNorm2d(32, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True),
nn.ELU(alpha=0.1),
nn.AvgPool2d(kernel_size=(1,4), stride=(1,4),padding=0),
nn.Dropout(p=0.35)
)
self.separableConv = nn.Sequential(
nn.Conv2d(32, 32, kernel_size=(1,15), stride=(1,1), padding=(0,7),bias=False),
nn.BatchNorm2d(32, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True),
nn.ELU(alpha=0.1),
nn.AvgPool2d(kernel_size=(1,8), stride=(1,8),padding=0),
nn.Dropout(p=0.35)
)
self.classify = nn.Sequential(
nn.Flatten(),
nn.Linear(736,n_output,bias=True)
)
def forward(self, x):
out = self.firstConv(x)
out = self.depthwiseConv(out)
out = self.separableConv(out)
out = self.classify(out)
return out
model = EEGNet_ELU(n_output=2)
print(model)
criterion = nn.CrossEntropyLoss()
# optimizer = optim.Adam(model.parameters(),lr = lr)
optimizer = optim.RMSprop(model.parameters(),lr = lr, momentum = 0.6)
scheduler = optim.lr_scheduler.MultiStepLR(optimizer, milestones=[100,300,500], gamma=0.1)
model.cuda(0)
summary(model.cuda(),(1,2,750))
loss_history = []
train_accuracy_history = []
test_accuracy_history = []
for epoch in range(epochs):
# for idx,(data,target) in enumerate(loader):
model.train()
x,y = x.to(device),y.to(device)
y_pred = model(x)
# print(y_pred.shape)
# print(y.shape)
# loss = F.mse_loss(y_pred, y)
loss = criterion(y_pred, y)
train_loss = loss.item()
loss_history.append(train_loss)
optimizer.zero_grad()
loss.backward()
optimizer.step()
# scheduler.step()
if epoch%1==0:
# correct= (y_pred.ge(0.5) == y).sum().item()
n = y.shape[0]
correct = (torch.max(y_pred,1)[1]==y).sum().item()
train_accuracy = correct / n
train_accuracy_history.append(train_accuracy)
# print("epochs:",epoch,"loss:",loss.item(),"Accuracy:",(correct / n),"Learning rate:",scheduler.get_last_lr()[0])
test_accuracy = testing(test_data,test_label,model,device,filepath)
test_accuracy_history.append(test_accuracy)
print("epochs:",epoch,"loss:",train_loss,"Training Accuracy:",train_accuracy,"Testing Accuracy:",test_accuracy,"Learning rate:",scheduler.get_last_lr()[0])
if train_loss<min_loss:
min_loss = train_loss
# torch.save(model.state_dict(), filepath)
if train_accuracy>max_accuracy:
max_accuracy = train_accuracy
if opt.save_model:
torch.save(model.state_dict(), filepath)
print("最大的Accuracy為:",max_accuracy,"最小的Loss值為:",min_loss)
df = pd.DataFrame({"loss":loss_history,"train_accuracy_history":train_accuracy_history,"test_accuracy_history":test_accuracy_history})
if opt.save_csv:
df.to_csv(filepath_csv,encoding="utf-8-sig")