-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCNN_model.py
executable file
·266 lines (230 loc) · 8.6 KB
/
CNN_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
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
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 CCNNModel(pl.LightningModule):
r'''
Continuous Convolutional Neural Network (CCNN).
- Paper: Yang Y, Wu Q, Fu Y, et al. Continuous convolutional neural network with 3D input for EEG-based emotion recognition[C]//International Conference on Neural Information Processing. Springer, Cham, 2018: 433-443.
- URL: https://link.springer.com/chapter/10.1007/978-3-030-04239-4_39
- Related Project: https://github.com/ynulonger/DE_CNN
Args:
in_channels (int): The feature dimension of each electrode. (default: :obj:`4`)
grid_size (tuple): Spatial dimensions of grid-like EEG representation. (default: :obj:`(9, 9)`)
num_classes (int): The number of classes to predict. (default: :obj:`2`)
dropout (float): Probability of an element to be zeroed in the dropout layers. (default: :obj:`0.25`)
'''
def __init__(
self,
input_ch: Optional[int] = 4,
grid_size: Optional[Tuple[int, int]] = (9, 9),
num_classes: Optional[int] = 3,
output_ch: Optional[int] = 64,
kernel_size: Optional[int] = 4,
hidden_size: Optional[int] = 1024,
dropout_prob: Optional[float] = 0.5
):
super().__init__()
self.input_ch = input_ch
self.output_ch = output_ch
self.grid_size = grid_size
self.num_classes = num_classes
self.kernel_size = kernel_size
self.hidden_size = hidden_size
self.dropout = dropout_prob
self.conv1 = nn.Sequential(
# nn.ZeroPad2d((1, 2, 1, 2)),
nn.Conv2d(
in_channels=self.input_ch,
out_channels=self.output_ch,
kernel_size=kernel_size,
stride=1,
padding="same"
),
nn.ReLU()
)
self.conv2 = nn.Sequential(
# nn.ZeroPad2d((1, 2, 1, 2)),
nn.Conv2d(
in_channels=self.output_ch,
out_channels=self.output_ch * 2,
kernel_size=kernel_size,
stride=1,
padding="same"
),
nn.ReLU()
)
self.conv3 = nn.Sequential(
# nn.ZeroPad2d((1, 2, 1, 2)),
nn.Conv2d(
in_channels=self.output_ch * 2,
out_channels=self.output_ch * 4,
kernel_size=kernel_size,
stride=1,
padding="same"
),
nn.ReLU()
)
self.conv4 = nn.Sequential(
# nn.ZeroPad2d((1, 2, 1, 2)),
nn.Conv2d(
in_channels=self.output_ch * 4,
out_channels=self.output_ch,
kernel_size=kernel_size,
stride=1,
padding="same"
),
nn.ReLU()
)
self.lin1 = nn.Sequential(
nn.Linear(self.grid_size[0] * self.grid_size[1] * self.output_ch, self.hidden_size),
nn.SELU(), # Not mentioned in paper
nn.Dropout2d(self.dropout)
)
self.lin2 = nn.Linear(self.hidden_size, self.num_classes)
def forward(self, x: torch.Tensor) -> torch.Tensor:
r'''
Args:
x (torch.Tensor): EEG signal representation, the ideal input shape is :obj:`[n, 4, 9, 9]`. Here, :obj:`n` corresponds to the batch size, :obj:`4` corresponds to :obj:`in_channels`, and :obj:`(9, 9)` corresponds to :obj:`grid_size`.
Returns:
torch.Tensor[number of sample, number of classes]: the predicted probability that the samples belong to the classes.
'''
x = self.conv1(x)
x = self.conv2(x)
x = self.conv3(x)
x = self.conv4(x)
x = x.flatten(start_dim=1)
x = self.lin1(x)
x = self.lin2(x)
return x
#-------------------------------------------------------------------------------------------------------
#-------------------------------------------------------------------------------------------------------
class CCNN(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 = CCNNModel(**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}]
#----------------------------------------------------------------------------------------------------------------