-
Notifications
You must be signed in to change notification settings - Fork 2
/
model.py
187 lines (165 loc) · 6.33 KB
/
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
"""
The SampleCNN class is implemented by https://github.com/Spijkervet/CLMR
"""
# Import the required libraries
import torch
import torch.nn as nn
import torch.optim as optim
import pytorch_lightning as pl
from criterion import TripletLoss, ContrastiveLoss
class Model(nn.Module):
def __init__(self):
super(Model, self).__init__()
def initialize(self, m):
if isinstance(m, (nn.Conv1d)):
nn.init.kaiming_uniform_(m.weight, mode="fan_in", nonlinearity="relu")
class SampleCNN(Model):
def __init__(self, strides, supervised, out_dim, device=None):
super(SampleCNN, self).__init__()
self.strides = strides
self.supervised = supervised
self.device = (
device
if device
else torch.device("cuda" if torch.cuda.is_available() else "cpu")
)
self.sequential = [
nn.Sequential(
nn.Conv1d(
in_channels=1, out_channels=128, kernel_size=3, stride=3, padding=0
),
nn.BatchNorm1d(128),
nn.ReLU(),
)
]
self.hidden = [
[128, 128],
[128, 128],
[128, 256],
[256, 256],
[256, 256],
[256, 256],
[256, 256],
[256, 256],
[256, 512],
]
assert len(self.hidden) == len(
self.strides
), "Number of hidden layers and strides are not equal"
for stride, (h_in, h_out) in zip(self.strides, self.hidden):
self.sequential.append(
nn.Sequential(
nn.Conv1d(
in_channels=h_in,
out_channels=h_out,
kernel_size=stride,
stride=1,
padding=1,
),
nn.BatchNorm1d(h_out),
nn.ReLU(),
nn.MaxPool1d(stride, stride=stride),
)
)
# 1 x 512
self.sequential.append(
nn.Sequential(
nn.Conv1d(
in_channels=512,
out_channels=512,
kernel_size=3,
stride=1,
padding=1,
),
nn.BatchNorm1d(512),
nn.ReLU(),
)
)
self.sequential = nn.Sequential(*self.sequential)
if self.supervised:
self.dropout = nn.Dropout(0.5)
self.fc = nn.Linear(512, out_dim)
def forward(self, x):
out = self.sequential(x)
if self.supervised:
out = self.dropout(out)
out = torch.mean(out, dim=2)
logit = self.fc(out)
return logit
class TripletNet(pl.LightningModule):
def __init__(
self, strides, supervised, out_dim, loss_type="triplet", *args, **kwargs
):
super().__init__()
# log hyperparameters
self.save_hyperparameters(ignore=["encoder"])
self.encoder = SampleCNN(strides, supervised, out_dim)
self.strides = self.encoder.strides
self.loss_type = loss_type
def forward(self, x):
return self.encoder(x)
def training_step(self, batch, batch_idx):
if self.loss_type == "triplet":
anchor, positive, negative = batch
anchor_embedding = self.encoder(anchor)
positive_embedding = self.encoder(positive)
negative_embedding = self.encoder(negative)
loss_function = self.get_loss_function()
train_loss = loss_function(
anchor_embedding, positive_embedding, negative_embedding
)
else: # self.loss_type == "contrastive":
sample1, sample2, label = batch
sample1_embedding = self.encoder(sample1)
sample2_embedding = self.encoder(sample2)
loss_function = self.get_loss_function()
train_loss = loss_function(sample1_embedding, sample2_embedding, label)
# Return the loss value for logging
self.log("train_loss", train_loss, sync_dist=True, rank_zero_only=True)
return train_loss
def validation_step(self, batch, batch_idx):
if self.loss_type == "triplet":
anchor, positive, negative = batch
anchor_embedding = self.encoder(anchor)
positive_embedding = self.encoder(positive)
negative_embedding = self.encoder(negative)
loss_function = self.get_loss_function()
val_loss = loss_function(
anchor_embedding, positive_embedding, negative_embedding
)
else: # self.loss_type == "contrastive":
sample1, sample2, label = batch
sample1_embedding = self.encoder(sample1)
sample2_embedding = self.encoder(sample2)
loss_function = self.get_loss_function()
val_loss = loss_function(sample1_embedding, sample2_embedding, label)
self.log("val_loss", val_loss, sync_dist=True, rank_zero_only=True)
return val_loss
def test_step(self, batch, batch_idx):
if self.loss_type == "triplet":
anchor, positive, negative = batch
anchor_embedding = self.encoder(anchor)
positive_embedding = self.encoder(positive)
negative_embedding = self.encoder(negative)
loss_function = self.get_loss_function()
test_loss = loss_function(
anchor_embedding, positive_embedding, negative_embedding
)
else: # self.loss_type == "contrastive":
sample1, sample2, label = batch
sample1_embedding = self.encoder(sample1)
sample2_embedding = self.encoder(sample2)
loss_function = self.get_loss_function()
test_loss = loss_function(sample1_embedding, sample2_embedding, label)
self.log("test_loss", test_loss, sync_dist=True, rank_zero_only=True)
return test_loss
def get_loss_function(self):
if self.loss_type == "triplet":
return TripletLoss()
elif self.loss_type == "contrastive":
return ContrastiveLoss()
else:
raise ValueError(f"Invalid loss type: {self.loss_type}")
def configure_optimizers(self):
optimizer = optim.AdamW(self.parameters(), lr=0.0003)
return optimizer