-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFFNN_model.py
executable file
·223 lines (190 loc) · 7.03 KB
/
FFNN_model.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
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
import torch
import torch.nn as nn
import pytorch_lightning as pl
from torcheval.metrics.functional import (
multiclass_accuracy,
multiclass_f1_score
)
from torch import optim
from typing import Tuple, Optional, Dict, Iterable, Literal
#----------------------------------------------------------------------------------------------------------------
class EEGFeedForwardNetModel(pl.LightningModule):
def __init__(
self,
input_size: Optional[int] = 248,
num_classes: Optional[int] = 3,
hidden_size: Optional[int] = 64,
norm_method: Optional[Literal["batch", "stratified"]] = "batch",
dropout_prob: Optional[float] = 0.5,
):
super().__init__()
self.input_size = input_size
self.num_classes = num_classes
self.hidden_size = hidden_size
self.norm_method = norm_method
self.dropout_prob = dropout_prob
assert self.norm_method in ["batch", "stratified"], f"\
The chosen normalization method {norm_method} is not available. Please choose one from ['batch', 'stratified']."
if self.norm_method == "batch":
self.norm_layer = nn.BatchNorm1d
elif self.norm_method == "stratified":
NotImplementedError
# self.norm_layer = StratifiedNorm
self.input_norm = self.norm_layer(self.input_size)
self.fc1 = nn.Sequential(
nn.Linear(in_features=self.input_size, out_features=self.hidden_size),
self.norm_layer(num_features=self.hidden_size),
nn.ReLU(True)
)
self.drop1 = nn.Dropout(self.dropout_prob)
self.fc2 = nn.Sequential(
nn.Linear(in_features=self.hidden_size, out_features=self.hidden_size),
self.norm_layer(num_features=self.hidden_size),
nn.ReLU(True)
)
self.drop2 = nn.Dropout(self.dropout_prob)
self.fc3 = nn.Sequential(
nn.Linear(in_features=self.hidden_size, out_features=self.hidden_size),
self.norm_layer(num_features=self.hidden_size),
nn.ReLU(True)
)
self.drop3 = nn.Dropout(self.dropout_prob)
self.fc4 = nn.Sequential(
nn.Linear(in_features=self.hidden_size, out_features=self.num_classes),
nn.ReLU(True)
)
def forward(self, x):
x = self.input_norm(x)
x = self.fc1(x)
x = self.drop1(x)
x = self.fc2(x)
x = self.drop2(x)
x = self.fc3(x)
x = self.drop3(x)
x = self.fc4(x)
return x
#-------------------------------------------------------------------------------------------------------
#-------------------------------------------------------------------------------------------------------
class EEGFeedForwardNet(pl.LightningModule):
def __init__(
self,
model_parameters: Dict,
lr: Optional[float] = 1e-4,
betas: Optional[Iterable[float]] = [0.9, 0.99],
weight_decay: Optional[float] = 1e-6,
epochs: Optional[int] = 100,
lr_patience: Optional[int] = 20,
):
super().__init__()
self.save_hyperparameters()
self.loss_fun = nn.CrossEntropyLoss()
self.model = EEGFeedForwardNetModel(**model_parameters)
self.lr = lr
self.betas = betas
self.weight_decay = weight_decay
self.epochs = epochs
self.lr_patience = lr_patience
def forward(
self,
input: Tuple[torch.Tensor, int]
):
'''
Parameters:
-----------
input: Tuple[torch.Tensor, int, int]
Tensor of size (B, M), plus an integer label, plus integer for trial_id
Returns:
--------
x: (torch.Tensor)
Tensor of size (B, 3)
'''
x, y, z = input
x = self.model(x)
return x
def training_step(
self,
train_batch: Tuple[torch.Tensor, torch.Tensor],
batch_idx: int
):
'''
Parameters:
-----------
train_batch: Tuple[torch.Tensor, int, int]
Tensor of size (B, M), plus an integer label, plus integer for trial_id
'''
# extract input (x signal, y label)
x, y, z = train_batch
# network output
out = self.model(x)
# compute loss & log it
loss = self.loss_fun(out, y)
# compute metrics & log them
accuracy = multiclass_accuracy(input=out, target=y)
f1_score = multiclass_f1_score(input=out, target=y, num_classes=out.shape[-1])
# log loss and metrics
self.log_dict(
{'train_loss': loss, "train_accuracy": accuracy, "train_f1_score": f1_score},
on_step=False,
on_epoch=True,
prog_bar=True,
logger=True
)
return loss
def validation_step(
self,
val_batch: Tuple[torch.Tensor, torch.Tensor],
batch_idx: int
):
'''
Parameters:
-----------
val_batch: Tuple[torch.Tensor, int, int]
Tensor of size (B, M), plus an integer label, plus integer for trial_id
'''
# extract input (x signal, y label)
x, y, z = val_batch
# network output
out = self.model(x)
# compute loss
loss = self.loss_fun(out, y)
# compute metrics & log them
accuracy = multiclass_accuracy(input=out, target=y)
f1_score = multiclass_f1_score(input=out, target=y, num_classes=out.shape[-1])
# log loss and metrics
self.log_dict(
{"val_loss": loss, "val_accuracy": accuracy, "val_f1_score": f1_score},
on_step=False,
on_epoch=True,
prog_bar=True,
logger=True
)
return loss
def test_step(
self,
test_batch: Tuple[torch.Tensor, torch.Tensor],
batch_idx: int
):
'''
Parameters:
-----------
test_batch: Tuple[torch.Tensor, int, int]
Tensor of size (B, M), plus an integer label, plus integer for trial_id
'''
# extract input (x signal, y label)
x, y, z = test_batch
# network output
out = self.model(x)
return self.loss_fun(out, y)
def configure_optimizers(self):
optimizer = optim.Adam(
self.parameters(), lr=self.lr, betas=self.betas, weight_decay=self.weight_decay
)
scheduler = optim.lr_scheduler.ReduceLROnPlateau(
optimizer=optimizer,
mode='min',
factor=0.1,
patience=self.lr_patience,
min_lr=1e-7
)
return [optimizer], [{"scheduler": scheduler,"monitor": "val_loss", "interval": "epoch", "frequency": 1}]
#----------------------------------------------------------------------------------------------------------------