Luisgust commited on
Commit
580612d
·
verified ·
1 Parent(s): ea725cc

Create vtoonify/model/encoder/criteria/id_loss.py

Browse files
vtoonify/model/encoder/criteria/id_loss.py ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import torch
3
+ from torch import nn
4
+ from model.encoder.encoders.model_irse import Backbone
5
+
6
+
7
+ class IDLoss(nn.Module):
8
+ def __init__(self, model_paths):
9
+ super(IDLoss, self).__init__()
10
+ print('Loading ResNet ArcFace')
11
+ self.facenet = Backbone(input_size=112, num_layers=50, drop_ratio=0.6, mode='ir_se')
12
+ self.facenet.load_state_dict(torch.load(model_paths))
13
+ self.face_pool = torch.nn.AdaptiveAvgPool2d((112, 112))
14
+ self.facenet.eval()
15
+
16
+ def extract_feats(self, x):
17
+ x = x[:, :, 35:223, 32:220] # Crop interesting region
18
+ x = self.face_pool(x)
19
+ x_feats = self.facenet(x)
20
+ return x_feats
21
+
22
+ def forward(self, y_hat, y):
23
+ n_samples = y_hat.shape[0]
24
+ y_feats = self.extract_feats(y) # Otherwise use the feature from there
25
+ y_hat_feats = self.extract_feats(y_hat)
26
+ y_feats = y_feats.detach()
27
+ loss = 0
28
+ count = 0
29
+ for i in range(n_samples):
30
+ diff_target = y_hat_feats[i].dot(y_feats[i])
31
+ loss += 1 - diff_target
32
+ count += 1
33
+
34
+ return loss / count