I was implementing cosine similarity loss with my custom python script but it gives me a very different answer than TensorFlow. First see TensorFlow's answer:-
y_true = [[0., 1.], [1., 1.]]
y_pred = [[0., 1.], [0., 1.]]
loss = tf.keras.losses.CosineSimilarity()
print(loss(y_true, y_pred).numpy())
Output:
>>> -0.8535534
According to the TensorFlow documentation, the formula to compute the loss is this:-
I implemented the same with plain python as this:-
def cosine_similarity(y_true, y_pred):
loss = -np.sum(np.linalg.norm(y_true) * np.linalg.norm(y_pred))
return loss
print(cosine_similarity(y_true, y_pred))
Output:
>>> -2.4494897427831783
I don't why I am getting -2.45 and TensorFlow is outputting -0.85. Any solution so my answer can match with TensorFlow's?
