-
Notifications
You must be signed in to change notification settings - Fork 0
/
algorithms.py
143 lines (117 loc) · 5.56 KB
/
algorithms.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
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
from models import SemisupervisedModel
class CrossEntropy(SemisupervisedModel):
def __init__(self, augmenter, encoder):
super().__init__(augmenter, encoder)
self.num_classes = 10
self.classifier_head = keras.Sequential(
[
layers.Input(shape=encoder.output_shape[1]),
layers.ReLU(), # activation on the output of the encoder
layers.Dense(self.num_classes),
],
name="classifier_head",
)
def semisupervised_loss(
self, labels, labeled_features, unlabeled_features_1, unlabeled_features_2
):
# supervised baseline: uses only labeled images
# features -> logits -> softmax + cross-entropy
class_logits = self.classifier_head(labeled_features)
return keras.losses.sparse_categorical_crossentropy(
labels, class_logits, from_logits=True
)
class InfoNCE(SemisupervisedModel):
def __init__(self, augmenter, encoder, temperature):
super().__init__(augmenter, encoder)
self.temperature = temperature
def semisupervised_loss(
self, labels, labeled_features, unlabeled_features_1, unlabeled_features_2
):
# self-supervised baseline: uses only unlabeled images
# 2 x features -> pairwise similarity -> temperature scaling + softmax + cross-entropy
# labels = the pairs of features from the same image should be most similar
batch_size = tf.shape(unlabeled_features_1)[0]
unlabeled_features_1 = tf.math.l2_normalize(unlabeled_features_1, axis=1)
unlabeled_features_2 = tf.math.l2_normalize(unlabeled_features_2, axis=1)
similarities = (
unlabeled_features_1 @ tf.transpose(unlabeled_features_2) / self.temperature
)
nn_labels = tf.range(batch_size)
loss = keras.losses.sparse_categorical_crossentropy(
nn_labels, similarities, from_logits=True
)
return loss
class SuNCEt(InfoNCE):
def __init__(self, augmenter, encoder, temperature, supervised_loss_weight):
super().__init__(augmenter, encoder, temperature)
self.supervised_loss_weight = supervised_loss_weight
self.num_classes = 10
def semisupervised_loss(
self, labels, labeled_features, unlabeled_features_1, unlabeled_features_2
):
# self-supervised contrastive loss (InfoNCE) + supervised contrastive loss (SuNCEt)
self_supervised_loss = super().semisupervised_loss(
labels, labeled_features, unlabeled_features_1, unlabeled_features_2
)
labeled_batch_size = tf.shape(labeled_features)[0]
labeled_features = tf.math.l2_normalize(labeled_features, axis=1)
similarities = (
labeled_features @ tf.transpose(labeled_features) - 1.0
) / self.temperature
nn_scores = tf.exp(similarities) * (1.0 - tf.eye(labeled_batch_size))
nn_probabilities = nn_scores / tf.reduce_sum(nn_scores, axis=1, keepdims=True)
class_probabilities = nn_probabilities @ tf.one_hot(labels, self.num_classes)
supervised_loss = keras.losses.sparse_categorical_crossentropy(
labels, class_probabilities
)
return self_supervised_loss + self.supervised_loss_weight * supervised_loss
class PAWS(SemisupervisedModel):
def __init__(self, augmenter, encoder, temperature, sharpening):
super().__init__(augmenter, encoder)
self.temperature = temperature
self.sharpening = sharpening
self.num_classes = 10
def soft_nn_predict(self, labels, labeled_features, unlabeled_features):
labeled_features = tf.math.l2_normalize(labeled_features, axis=1)
unlabeled_features = tf.math.l2_normalize(unlabeled_features, axis=1)
similarities = unlabeled_features @ tf.transpose(labeled_features)
nn_probabilities = keras.activations.softmax(similarities / self.temperature)
class_probabilities = nn_probabilities @ tf.one_hot(labels, self.num_classes)
return class_probabilities
def sharpen(self, probabilities):
probabilities = probabilities ** (1 / self.sharpening) # sharpening
probabilities /= tf.reduce_sum(
probabilities, axis=1, keepdims=True
) # renormalization
return probabilities
def semisupervised_loss(
self, labels, labeled_features, unlabeled_features_1, unlabeled_features_2
):
# self-labeling with a soft-nn classifier using the labeled batch
pred_probabilities_1 = self.soft_nn_predict(
labels, labeled_features, unlabeled_features_1
)
pred_probabilities_2 = self.soft_nn_predict(
labels, labeled_features, unlabeled_features_2
)
pred_probabilities = tf.concat(
[pred_probabilities_2, pred_probabilities_1], axis=0
)
target_probabilities = tf.concat(
[self.sharpen(pred_probabilities_1), self.sharpen(pred_probabilities_2)],
axis=0,
)
mean_target_probabilities = tf.reduce_mean(target_probabilities, axis=0)
# the predicted label distribution should be close to its sharper version
# the average predicted label distribution should be uniform
loss = keras.losses.categorical_crossentropy(
tf.stop_gradient(target_probabilities),
pred_probabilities,
) - keras.losses.categorical_crossentropy(
mean_target_probabilities,
mean_target_probabilities,
)
return loss