-
Notifications
You must be signed in to change notification settings - Fork 0
/
pml_providers.py
66 lines (59 loc) · 1.53 KB
/
pml_providers.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
from pytorch_metric_learning import losses, samplers
contrastive_losses = [
'AngularLoss',
'ContrastiveLoss',
'CentroidTripletLoss',
'TripletMarginLoss',
'GeneralizedLiftedStructureLoss',
'IntraPairVarianceLoss',
'LiftedStructureLoss',
'MarginLoss',
'MultiSimilarityLoss',
'CentroidTripletLoss',
'TupletMarginLoss',
'CircleLoss',
'SignalToNoiseRatioContrastiveLoss',
'FastAPLoss',
'NCALoss',
'NTXentLoss',
'SupConLoss',
]
classification_losses = [
'LargeMarginSoftmaxLoss',
'ArcFaceLoss',
'CosFaceLoss',
'SphereFaceLoss',
'SoftTripleLoss',
'NormalizedSoftmaxLoss',
'SubCenterArcFaceLoss',
'ProxyNCALoss',
'ProxyAnchorLoss'
]
def loss_provider(
loss_name,
embedding_dim,
num_classes,
samples_per_class=1,
loss_kwargs=None
):
if loss_kwargs is None:
loss_kwargs = {}
clf_kwargs = dict(
num_classes=num_classes,
embedding_size=embedding_dim
)
loss_fn_class = getattr(losses, loss_name)
if loss_name in contrastive_losses:
loss_fn = loss_fn_class(**loss_kwargs)
elif loss_name in classification_losses:
loss_fn = loss_fn_class(**clf_kwargs, **loss_kwargs)
else:
raise ValueError(f'Unrecognized loss: {loss_name}')
return loss_fn
def sampler_provider(train_dataset, samples_per_class):
sampler = samplers.MPerClassSampler(
train_dataset.labels,
m=samples_per_class,
length_before_new_iter=len(train_dataset)
)
return sampler