Skip to content

Moved test out of run_in_graph_and_eager_mode in contrastive_test.py #1445

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Mar 27, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 15 additions & 13 deletions tensorflow_addons/losses/contrastive_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@

import sys

import numpy as np
import pytest
import tensorflow as tf
from tensorflow_addons.losses import contrastive
Expand Down Expand Up @@ -132,21 +133,22 @@ def test_no_reduction(self):

self.assertAllClose(loss, [0.81, 0.49, 1.69, 0.49, 0.0, 0.25])

def test_sum_reduction(self):
cl_obj = contrastive.ContrastiveLoss(reduction=tf.keras.losses.Reduction.SUM)
y_true = tf.constant([0, 0, 1, 1, 0, 1], dtype=tf.dtypes.int64)
y_pred = tf.constant([0.1, 0.3, 1.3, 0.7, 1.1, 0.5], dtype=tf.dtypes.float32)
loss = cl_obj(y_true, y_pred)

# Loss = y * (y`)^2 + (1 - y) * (max(m - y`, 0))^2
# = [max(1 - 0.1, 0)^2, max(1 - 0.3, 0)^2,
# 1.3^2, 0.7^2, max(1 - 1.1, 0)^2, 0.5^2]
# = [0.9^2, 0.7^2, 1.3^2, 0.7^2, 0^2, 0.5^2]
# = [0.81, 0.49, 1.69, 0.49, 0, 0.25]
# Reduced loss = 0.81 + 0.49 + 1.69 + 0.49 + 0 + 0.25
# = 3.73
def test_sum_reduction():
cl_obj = contrastive.ContrastiveLoss(reduction=tf.keras.losses.Reduction.SUM)
y_true = tf.constant([0, 0, 1, 1, 0, 1], dtype=tf.dtypes.int64)
y_pred = tf.constant([0.1, 0.3, 1.3, 0.7, 1.1, 0.5], dtype=tf.dtypes.float32)
loss = cl_obj(y_true, y_pred)

self.assertAllClose(loss, 3.73)
# Loss = y * (y`)^2 + (1 - y) * (max(m - y`, 0))^2
# = [max(1 - 0.1, 0)^2, max(1 - 0.3, 0)^2,
# 1.3^2, 0.7^2, max(1 - 1.1, 0)^2, 0.5^2]
# = [0.9^2, 0.7^2, 1.3^2, 0.7^2, 0^2, 0.5^2]
# = [0.81, 0.49, 1.69, 0.49, 0, 0.25]
# Reduced loss = 0.81 + 0.49 + 1.69 + 0.49 + 0 + 0.25
# = 3.73

np.testing.assert_allclose(loss, 3.73)


if __name__ == "__main__":
Expand Down