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