roywei commented on a change in pull request #12750: [MXNET -1030] Cosine 
Embedding Loss
URL: https://github.com/apache/incubator-mxnet/pull/12750#discussion_r224233205
 
 

 ##########
 File path: tests/python/unittest/test_loss.py
 ##########
 @@ -348,7 +348,35 @@ def test_triplet_loss():
             optimizer='adam')
     assert mod.score(data_iter, eval_metric=mx.metric.Loss())[0][1] < 0.05
 
-
+@with_seed()
+def test_cosine_loss():
+    #For similarity check
+    label = mx.nd.array([1])
+    pred = mx.nd.array([[1, 1, 1, 1],
+                        [1, 2, 3, 4]])
+    target = mx.nd.array([[1, 1, 1, 1],
+                          [1, 2, 3, 4]])
+    Loss = gluon.loss.CosineEmbeddingLoss()
+    loss = Loss(pred, target, label)
+
+    #computing numpy way
+    numerator = mx.nd.sum(pred * target, keepdims=True, axis=1)
+    denominator = mx.nd.sqrt(mx.nd.sum(pred**2, axis=1, keepdims=True)) \
+    * mx.nd.sqrt(mx.nd.sum(target**2, axis=1, keepdims=True))
+    assert_almost_equal(loss.asnumpy(), (1-numerator/denominator).asnumpy())
+
+    # Label == -1
 
 Review comment:
   Please refer to pytorch unit test: 
https://github.com/pytorch/pytorch/blob/master/test/test_nn.py#L4986
   Create random input1 input2 and labels, labels can be randomly 1 or -1, so 
you can test them at once. No need to repeat with just label = -1 on fixed 
inputs.

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
[email protected]


With regards,
Apache Git Services

Reply via email to