Skip to content
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

Feature add cosine proximity loss #30

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
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
65 changes: 64 additions & 1 deletion neural_nets/losses/losses.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from abc import ABC, abstractmethod

import numpy as np
from tests import assert_is_binary, assert_is_stochastic
# from tests import assert_is_binary, assert_is_stochastic


class ObjectiveBase(ABC):
Expand Down Expand Up @@ -385,3 +385,66 @@ def grad(self, Y_fake, module, Y_real=None, gradInterp=None):
else:
raise ValueError("Unrecognized module: {}".format(module))
return grad


class Cosine(ObjectiveBase):
def __init__(self):
super().__init__()

def __call__(self, y, y_pred):
return self.loss(y, y_pred)

def __str__(self):
return "Cosine Proximity"

@staticmethod
def loss(y, y_pred):
"""
Compute the Cosine distance between 1-D arrays.

The Cosine distance between `u` and `v`, is defined as
.. math::
1 - \\frac{u \\cdot v}
{||u||_2 ||v||_2}.
where :math:`u \\cdot v` is the dot product of :math:`u` and
:math:`v`.

Parameters
----------
y : numpy array of shape (n, m)

y_pred : numpy array of shape (n, m)


Returns
-------
loss : float

"""
def l2_normalize(x, axis=-1):
y = np.max(np.sum(x ** 2, axis, keepdims=True), axis, keepdims=True)
return x / np.sqrt(y)

y_true = l2_normalize(y, axis=-1)
y_pred = l2_normalize(y_pred, axis=-1)
return 1. - np.sum(y_true * y_pred, axis=-1)
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I saw 2 different implementation. First one is

return -np.sum(y_true * y_pred, axis=-1)

or

return 1. - np.sum(y_true * y_pred, axis=-1)

Which one should we choose for our implementation? They are same in nature.

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I like the first since it ranges between -1 and 1, similar to the cosine distance itself.


@staticmethod
def grad(y, y_pred, z, act_fn):
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is there a sufficient way to do grad of cosine?

Copy link
Owner

@ddbourgin ddbourgin Jul 17, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Doing this from my phone, so please check for errors:

If f(x, y) = (x @ y) / (norm(x) * norm(y)), then we have

df/dy = x / (norm(x) * norm(y)) - (f(x, y) * y) / (norm(y) ** 2)

where norm is just the 2-norm

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Note that since cosine loss == negative cosine distance, you should multiply df/dy by -1

"""


Parameters
----------
y : numpy array of shape (n, m)

y_pred : numpy array of shape (n, m)


Returns
-------
grad : numpy array of shape (n, m)

"""
return 0.0

30 changes: 29 additions & 1 deletion neural_nets/tests/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,10 @@ def test_losses(N=50):
time.sleep(1)
test_WGAN_GP_loss(N)

print("Testing Cosine Loss")
time.sleep(1)
test_cosine_proximity(N)


def test_activations(N=50):
print("Testing Sigmoid activation")
Expand Down Expand Up @@ -397,6 +401,31 @@ def test_WGAN_GP_loss(N=None):
i += 1


def test_cosine_proximity(N=None):
from scipy.spatial.distance import cosine
from losses import Cosine

N = np.inf if N is None else N

mine = Cosine()
gold = cosine

i = 1
while i < N:
vector_length_max = 100

for j in range(2, vector_length_max):
x = np.random.uniform(0., 1., [j, ])
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

To generate random vector array, i set the bound from 0. to 1.

y = np.random.uniform(0., 1., [j, ])

dist = mine(x, y)
dist_true = gold(x, y)
# print(dist, dist_true - 1.)
assert_almost_equal(dist, dist_true)
print('PASSED.')
i += 1


#######################################################################
# Loss Function Gradients #
#######################################################################
Expand Down Expand Up @@ -565,7 +594,6 @@ def test_softsign_activation(N=None):
i += 1



#######################################################################
# Activation Gradients #
#######################################################################
Expand Down