forked from skull8888888/qia2020
-
Notifications
You must be signed in to change notification settings - Fork 0
/
fe.py
199 lines (133 loc) · 6 KB
/
fe.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
import os
import torch
from torch.nn import functional as F
from torch.utils.data import DataLoader
import torchvision.transforms as transforms
import pytorch_lightning.metrics.functional as plm
import torch.nn as nn
import torchvision.models as models
from pytorch_lightning.metrics.functional import accuracy
import pytorch_lightning as pl
from models.inception_resnet_v1 import InceptionResnetV1
from torch.optim.lr_scheduler import StepLR, ReduceLROnPlateau
class Flatten(nn.Module):
def __init__(self):
super(Flatten, self).__init__()
def forward(self, x):
x = x.view(x.size(0), -1)
return x
class normalize(nn.Module):
def __init__(self):
super(normalize, self).__init__()
def forward(self, x):
x = F.normalize(x, p=2, dim=1)
return x
class ResCNNEncoder(nn.Module):
def __init__(self):
super(ResCNNEncoder, self).__init__()
# self.resnet = InceptionResnetV1(pretrained='vggface2')
self.resnet = models.resnet18(pretrained=True)
self.resnet.fc = nn.Linear(512, 512)
self.linear = nn.Linear(512,7)
def forward(self, x):
x = self.resnet(x)
x = F.dropout(x, p=0.5, training=self.training)
x = self.linear(x)
return x
class FE(pl.LightningModule):
def __init__(self):
super(FE, self).__init__()
self.resnet = ResCNNEncoder()
# {'hap':0, 'sur':1, 'neu':2, 'fea':3, 'dis':4, 'ang':5, 'sad':6}
self.register_buffer("w", torch.Tensor([1.,1.,0.5,1.,1.,1.,1.]))
def forward(self, x):
return self.resnet(x)
def training_step(self, batch, batch_nb):
X, y = batch
y_hat = self.forward(X)
y = y.squeeze_()
loss = F.cross_entropy(y_hat, y, weight=self.w)
self.log('train_loss', loss)
return loss
def validation_step(self, batch, batch_nb):
X, y = batch
y_hat = self.forward(X)
y_pred = y_hat.max(1)[1]
y = y.squeeze_()
loss = F.cross_entropy(y_hat, y, weight=self.w)
return {'val_loss': loss, 'correct_count': (y_pred == y).sum(), 'all_count': y.size(0)}
def validation_epoch_end(self, outputs):
avg_loss = torch.stack([x['val_loss'] for x in outputs]).mean()
correct_count = 0
all_count = 0
for l in outputs:
correct_count += l['correct_count']
all_count += l['all_count']
self.log('val_loss', avg_loss,prog_bar=True)
self.log('val_acc', correct_count / all_count, prog_bar=True)
def configure_optimizers(self):
optimizer = torch.optim.SGD(self.parameters(), lr=1e-3, momentum=0.9, weight_decay=1e-4)
# optimizer = torch.optim.Adam(self.parameters(), lr=1e-4, weight_decay=1e-4)
scheduler = ReduceLROnPlateau(optimizer, 'max',verbose=True, patience=5, factor=0.5)
return {"optimizer": optimizer, "lr_scheduler": scheduler, "monitor": "val_acc"}
# optimizer = torch.optim.SGD(self.parameters(), lr=4e-6, momentum=0.9, weight_decay=1e-4)
# import os
# import torch
# from torch.nn import functional as F
# from torch.utils.data import DataLoader
# import torchvision.transforms as transforms
# import pytorch_lightning.metrics.functional as plm
# import torch.nn as nn
# import torchvision.models as models
# from pytorch_lightning.metrics.functional import accuracy
# import pytorch_lightning as pl
# from models.inception_resnet_v1 import InceptionResnetV1
# from torch.optim.lr_scheduler import StepLR
# class ResCNNEncoder(nn.Module):
# def __init__(self):
# super(ResCNNEncoder, self).__init__()
# # self.resnet = InceptionResnetV1(pretrained='vggface2')
# self.resnet = models.resnet18(pretrained=True)
# self.resnet.fc = nn.Linear(512, 512)
# self.linear = nn.Linear(512,7)
# def forward(self, x):
# x = self.resnet(x)
# x = F.dropout(x, p=0.5, training=self.training)
# x = self.linear(x)
# return x
# class FE(pl.LightningModule):
# def __init__(self):
# super(FE, self).__init__()
# self.resnet = ResCNNEncoder()
# # {'hap':0, 'sur':1, 'neu':2, 'fea':3, 'dis':4, 'ang':5, 'sad':6}
# self.register_buffer("w", torch.Tensor([1.,1.,0.5,1.,1.,1.,1.]))
# def forward(self, x):
# return self.resnet(x)
# def training_step(self, batch, batch_nb):
# X, y = batch
# y_hat = self.forward(X)
# loss = F.binary_cross_entropy_with_logits(y_hat, y, weight=self.w)
# self.log('train_loss', loss)
# return loss
# def validation_step(self, batch, batch_nb):
# X, y = batch
# y_hat = self.forward(X)
# y_pred = (torch.sigmoid(y_hat) > 0.5).to(torch.int)
# nc = (abs(y_pred - y.to(torch.int)).sum(dim=1) > 0).sum()
# loss = F.binary_cross_entropy_with_logits(y_hat, y, weight=self.w)
# return {'val_loss': loss, 'correct_count': y.size(0) - nc, 'all_count': y.size(0)}
# def validation_epoch_end(self, outputs):
# avg_loss = torch.stack([x['val_loss'] for x in outputs]).mean()
# correct_count = 0
# all_count = 0
# for l in outputs:
# correct_count += l['correct_count']
# all_count += l['all_count']
# self.log('val_loss', avg_loss,prog_bar=True)
# self.log('val_acc', correct_count / all_count, prog_bar=True)
# def configure_optimizers(self):
# optimizer = torch.optim.SGD(self.parameters(), lr=1e-4, momentum=0.9, weight_decay=1e-4)
# scheduler = StepLR(optimizer, step_size=30, gamma=0.1)
# return [optimizer], [scheduler]
# # optimizer = torch.optim.SGD(self.parameters(), lr=5e-4, momentum=0.9)
# # return optimizer