Need some help.
My code returns:
loss = tf.Tensor(527.2598, shape=(), dtype=float32)
but I think this is not correct, as I am not getting the “all tests passed” message.
My code:
# Step 1: Compute the (encoding) distance between the anchor and the positive pos_dist = tf.reduce_sum(tf.square(tf.subtract(anchor, positive)), axis=-1) # Step 2: Compute the (encoding) distance between the anchor and the negative neg_dist = tf.reduce_sum(tf.square(tf.subtract(anchor, negative)),axis=-1) # Step 3: subtract the two previous distances and add alpha. basic_loss = pos_dist - neg_dist + alpha # Step 4: Take the maximum of basic_loss and 0.0. Sum over the training examples. loss = tf.reduce_sum(tf.maximum(basic_loss,0), axis=None)
Here is the output of the next section
BEGIN UNIT TEST
tf.random.set_seed(1)
y_true = (None, None, None) # It is not used
y_pred = (tf.keras.backend.random_normal([3, 128], mean=6, stddev=0.1, seed = 1),
tf.keras.backend.random_normal([3, 128], mean=1, stddev=1, seed = 1), tf.keras.backend.random_normal([3, 128], mean=3, stddev=4, seed = 1))
loss = triplet_loss(y_true, y_pred)
assert type(loss) == tf.python.framework.ops.EagerTensor, “Use tensorflow functions”
print("loss = " + str(loss))
y_pred_perfect = ([1., 1.], [1., 1.], [1., 1.,])
loss = triplet_loss(y_true, y_pred_perfect, 5)
assert loss == 5, “Wrong value. Did you add the alpha to basic_loss?”
y_pred_perfect = ([1., 1.],[1., 1.], [0., 0.,])
loss = triplet_loss(y_true, y_pred_perfect, 3)
assert loss == 1., “Wrong value. Check that pos_dist = 0 and neg_dist = 2 in this example”
y_pred_perfect = ([1., 1.],[0., 0.], [1., 1.,])
loss = triplet_loss(y_true, y_pred_perfect, 0)
assert loss == 2., “Wrong value. Check that pos_dist = 2 and neg_dist = 0 in this example”
y_pred_perfect = ([0., 0.],[0., 0.], [0., 0.,])
loss = triplet_loss(y_true, y_pred_perfect, -2)
assert loss == 0, “Wrong value. Are you taking the maximum between basic_loss and 0?”
y_pred_perfect = ([[1., 0.], [1., 0.]],[[1., 0.], [1., 0.]], [[0., 1.], [0., 1.]])
loss = triplet_loss(y_true, y_pred_perfect, 3)
assert loss == 2., “Wrong value. Are you applying tf.reduce_sum to get the loss?”
y_pred_perfect = ([[1., 1.], [2., 0.]], [[0., 3.], [1., 1.]], [[1., 0.], [0., 1.,]])
loss = triplet_loss(y_true, y_pred_perfect, 1)
if (loss == 4.):
raise Exception('Perhaps you are not using axis=-1 in reduce_sum?')
assert loss == 5, “Wrong value. Check your implementation”
END UNIT TEST
loss = tf.Tensor(527.2598, shape=(), dtype=float32)
Expected Output:
loss 527.2598