Repository navigation
Expand file tree
/
Copy pathMSVTNet.py
More file actions
165 lines (141 loc) · 4.78 KB
/
Copy pathMSVTNet.py
File metadata and controls
165 lines (141 loc) · 4.78 KB
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
import torch
import torch.nn as nn
import torch.nn.functional as F
from einops.layers.torch import Rearrange
class TSConv(nn.Sequential):
def __init__(self, nCh, F, C1, C2, D, P1, P2, Pc) -> None:
super().__init__(
nn.Conv2d(1, F, (1, C1), padding='same', bias=False),
nn.BatchNorm2d(F),
nn.Conv2d(F, F * D, (nCh, 1), groups=F, bias=False),
nn.BatchNorm2d(F * D),
nn.ELU(),
nn.AvgPool2d((1, P1)),
nn.Dropout(Pc),
nn.Conv2d(F * D, F * D, (1, C2), padding='same', groups=F * D, bias=False),
nn.BatchNorm2d(F * D),
nn.ELU(),
nn.AvgPool2d((1, P2)),
nn.Dropout(Pc)
)
class PositionalEncoding(nn.Module):
def __init__(self, seq_len, d_model) -> None:
super().__init__()
self.seq_len = seq_len
self.d_model = d_model
self.pe = nn.Parameter(torch.zeros(1, seq_len, d_model))
def forward(self, x):
x += self.pe
return x
class Transformer(nn.Module):
def __init__(
self,
seq_len,
d_model,
nhead,
ff_ratio,
Pt = 0.5,
num_layers = 4,
) -> None:
super().__init__()
self.cls_embedding = nn.Parameter(torch.zeros(1, 1, d_model))
self.pos_embedding = PositionalEncoding(seq_len + 1, d_model)
dim_ff = d_model * ff_ratio
self.dropout = nn.Dropout(Pt)
self.trans = nn.TransformerEncoder(nn.TransformerEncoderLayer(
d_model, nhead, dim_ff, Pt, batch_first=True, norm_first=True
), num_layers, norm=nn.LayerNorm(d_model))
def forward(self, x):
b = x.shape[0]
x = torch.cat((self.cls_embedding.expand(b, -1, -1), x), dim=1)
x = self.pos_embedding(x)
x = self.dropout(x)
return self.trans(x)[:, 0]
class ClsHead(nn.Sequential):
def __init__(self, linear_in, cls):
super().__init__(
nn.Flatten(),
nn.Linear(linear_in, cls),
nn.LogSoftmax(dim=1)
)
class MSVTNet(nn.Module):
def __init__(
self,
nCh = 22,
nTime = 1000,
cls = 4,
F = [9, 9, 9, 9],
C1 = [15, 31, 63, 125],
C2 = 15,
D = 2,
P1 = 8,
P2 = 7,
Pc = 0.3,
nhead = 8,
ff_ratio = 1,
Pt = 0.5,
layers = 2,
b_preds = True,
) -> None:
super().__init__()
self.nCh = nCh
self.nTime = nTime
self.b_preds = b_preds
assert len(F) == len(C1), 'The length of F and C1 should be equal.'
self.mstsconv = nn.ModuleList([
nn.Sequential(
TSConv(nCh, F[b], C1[b], C2, D, P1, P2, Pc),
Rearrange('b d 1 t -> b t d')
)
for b in range(len(F))
])
branch_linear_in = self._forward_flatten(cat=False)
self.branch_head = nn.ModuleList([
ClsHead(branch_linear_in[b].shape[1], cls)
for b in range(len(F))
])
seq_len, d_model = self._forward_mstsconv().shape[1:3] # type: ignore
self.transformer = Transformer(seq_len, d_model, nhead, ff_ratio, Pt, layers)
linear_in = self._forward_flatten().shape[1] # type: ignore
self.last_head = ClsHead(linear_in, cls)
def _forward_mstsconv(self, cat = True):
x = torch.randn(1, 1, self.nCh, self.nTime)
x = [tsconv(x) for tsconv in self.mstsconv]
if cat:
x = torch.cat(x, dim=2)
return x
def _forward_flatten(self, cat = True):
x = self._forward_mstsconv(cat)
if cat:
x = self.transformer(x)
x = x.flatten(start_dim=1, end_dim=-1)
else:
x = [_.flatten(start_dim=1, end_dim=-1) for _ in x]
return x
def forward(self, x):
x = [tsconv(x) for tsconv in self.mstsconv]
bx = [branch(x[idx]) for idx, branch in enumerate(self.branch_head)]
x = torch.cat(x, dim=2)
x = self.transformer(x)
x = self.last_head(x)
if self.b_preds:
return x, bx
else:
return x
class JointCrossEntoryLoss(nn.Module):
def __init__(self, lamd : float = 0.6) -> None:
super().__init__()
self.lamd = lamd
def forward(self, out, label):
end_out = out[0]
branch_out = out[1]
end_loss = F.nll_loss(end_out, label)
branch_loss = [F.nll_loss(out, label).unsqueeze(0) for out in branch_out]
branch_loss = torch.cat(branch_loss)
loss = self.lamd * end_loss + (1 - self.lamd) * torch.sum(branch_loss)
return loss
if __name__ == '__main__':
from torchinfo import summary
net = MSVTNet(nCh=22, nTime=1000).cuda()
print(net)
summary(net, (64, 1, 22, 1000), depth=4)