Skip to content

Commit a7b071b

Browse files
authored
Add files via upload
1 parent f7523e5 commit a7b071b

File tree

1 file changed

+20
-0
lines changed

1 file changed

+20
-0
lines changed

losses.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
from keras import backend as K
2+
import tensorflow as tf
3+
4+
def triplet_loss(y_true, y_pred, cosine = True, alpha = 0.2, embedding_size = 128):
5+
ind = int(embedding_size * 2)
6+
a_pred = y_pred[:, :embedding_size]
7+
p_pred = y_pred[:, embedding_size:ind]
8+
n_pred = y_pred[:, ind:]
9+
if cosine:
10+
positive_distance = 1 - K.sum((a_pred * p_pred), axis=-1)
11+
negative_distance = 1 - K.sum((a_pred * n_pred), axis=-1)
12+
else:
13+
positive_distance = K.sqrt(K.sum(K.square(a_pred - p_pred), axis=-1))
14+
negative_distance = K.sqrt(K.sum(K.square(a_pred - n_pred), axis=-1))
15+
loss = K.maximum(0.0, positive_distance - negative_distance + alpha)
16+
return loss
17+
18+
def attribute_crossentropy(y_true, y_pred):
19+
y_true = tf.gather(labels, tf.to_int32(y_true[0]))
20+
return K.mean(K.binary_crossentropy(y_true, y_pred), axis=-1)

0 commit comments

Comments
 (0)