Cosine similarity for a loss function

Ingrid_Bernal: <p>Hello,</p>
<p>I’m trying to include in my loss function the cosine similarity between the embeddings of the words of the sentences, so the distance between words will be less and my model can predict similar words.</p>
<p>but usually a loss fonction gives as result just one value, and with cosine similarity I have as many results as words in the sentence. I tried to mutliply the cosine similarity result by -1 to obtain not the maximum similarity but the minimum and then I got the mean of the values of the sentence. But this gives me a non sense word result, so actually the model still dont get how to find a close embedding.</p>
<p>Hope I was clear, I would appreciate any comments or ideas.</p>
<p>Ingrid.</p>

avinash_m: <p>Hi,<br>
Can you provide an example?</p>

Ingrid_Bernal: <p>sure !<br>
this is part of the code in my train function</p>
<p>for i in range(sentence_prime.size()[0]):<br>
embedding_prime.append(weights_matrix2[int(sentence_prime[i])])<br>
embedding_target.append(weights_matrix2[int(word_targets[i])])</p>
<p>loss2 = loss(torch.stack(embedding_prime),torch.stack(embedding_target))</p>
<p>total_loss = loss + loss2</p>
<p>total_loss.backward()</p>
<p>optimizer.step()</p>
<p>taking into account that</p>
<p>loss = nn.CosineSimilarity()</p>

avinash_m: <p>Hi, Please try this and let me know if it works:</p>
<p>Instead of multiplying the values by -1, calculate 1-cosine similarity which gives maximum similarity and then calculate mean.</p>

Ingrid_Bernal: <p>Hi !<br>
So I tried this;</p>
<p>loss2 = 1-(my_loss(torch.stack(embedding_prime),torch.stack(embedding_target)))</p>
<p>and still     loss = nn.CosineSimilarity()</p>
<p>but the result is still so innacurate… As a previous test we used the NLLLoss() between the entry phrase and the generated phrase so we obtained the same phrases with a 95% accuracy. but what we actually need is to obtain a sentence with words the closer possible .</p>
<p>Do you have any idea what I may be missing ?</p>
<p>Thanks.</p>

jackparrySG: <p>Hi, it looks as though you should be using nn.CosineEmbeddingLoss() not nn.CosineSimilarity(). Have you tried this?</p>
<p>Edit: Actually I now understand that you’re trying to compute the cosine similarity of a sequence of word embeddings with another sequence of word embeddings. I believe the above suggestion of taking the mean could be useful.</p>
<p>loss2 = 1-(my_loss(torch.mean(torch.stack(embedding_prime), 0), torch.mean(torch.stack(embedding_target), 0))).</p>
<p>To break this down a bit, you’ve got n-dimensional word embeddings, and the sentence is length T. That means once you append the embeddings to your list and call torch.stack(), you have a [T, n] shape matrix. Calling torch.mean(matrix, 0) will average across the T timesteps, resulting in one single embedding vector of shape [n]. Here you could use nn.CosineEmbeddingLoss() I believe</p>

Ingrid_Bernal: <p>Thanks !</p>
<p>Now I’m executing the train of the model with the recommendations you made, so now my loss is CosineEmbeddingLoss() and when I use it, actually I had to change it a bit…</p>
<p><div class="lightbox-wrapper"><a class="lightbox" href="https://discuss.pytorch.org/uploads/default/original/2X/8/8d776bb9f30aaa08e218be6d9ab2605d9c74a5eb.jpeg" data-download-href="https://discuss.pytorch.org/uploads/default/8d776bb9f30aaa08e218be6d9ab2605d9c74a5eb" title="Capture"><img src="https://discuss.pytorch.org/uploads/default/optimized/2X/8/8d776bb9f30aaa08e218be6d9ab2605d9c74a5eb_2_690x61.jpeg" alt="Capture" data-base62-sha1="kbtbeEhpbGZ84XvxO72V9WXuSMP" width="690" height="61" srcset="https://discuss.pytorch.org/uploads/default/optimized/2X/8/8d776bb9f30aaa08e218be6d9ab2605d9c74a5eb_2_690x61.jpeg, https://discuss.pytorch.org/uploads/default/optimized/2X/8/8d776bb9f30aaa08e218be6d9ab2605d9c74a5eb_2_1035x91.jpeg 1.5x, https://discuss.pytorch.org/uploads/default/original/2X/8/8d776bb9f30aaa08e218be6d9ab2605d9c74a5eb.jpeg 2x" data-dominant-color="292828"><div class="meta"><svg class="fa d-icon d-icon-far-image svg-icon" aria-hidden="true"><use href="#far-image"></use></svg><span class="filename">Capture</span><span class="informations">1192×106 20.2 KB</span><svg class="fa d-icon d-icon-discourse-expand svg-icon" aria-hidden="true"><use href="#discourse-expand"></use></svg></div></a></div></p>
<p>first I had to add a parameter “y”, which I’m not sure what is it for, but apparently its mandatory, so I sent</p>
<p>y = torch.empty(len(sentence)).bernoulli_().mul_(2).sub_(1)</p>
<p>which gives me a tensor of 1 et -1 …</p>
<p>and second I had to remove the mean, as long as I see it as a way to reduce the matrix, the shape of the function seem to be; the two input tensors of same size and the additional parameter “y” one dimension smaller, so my “y” tensor is already dimension 1 (it’s the size of the sentence T) and the two input tensors x1 and x2 are, as you said, size (T , embedding(500)). If I reduce my input vectors with a mean I would have a tensor of dimension 1, with size 500, and the expected “y” needs then to be smaller.</p>
<p>Hope it was clear, I will let you know the results when I have them.</p>

Ingrid_Bernal: <p>I already obtained the results and they actually don’t change at all, it’s like this loss is not affecting the evaluation of the words, or as if the evaluation accepts the fact that the words are already different but it doesn’t try to close them. I don’t perceive the closeness of the entry word and the predicted one. They are just as far as if we haven’t trained the model yet.</p>

cappelletto: <p>Hi <a class="mention" href="/u/ingrid_bernal">@Ingrid_Bernal</a></p>
<p>Maybe this reply is a bit late, but I think there is a problem when using a randomly generated <code>y=torch.bernoulli()</code> vector. According to the <a href="https://pytorch.org/docs/stable/generated/torch.nn.CosineEmbeddingLoss.html#torch.nn.CosineEmbeddingLoss" rel="noopener nofollow ugc">nn.CosineEmbeddingLoss</a> documentation, <code>y</code> vector is used to define which version of the loss function will be used.</p>
<p>Based on the previous comments, as you are trying to minimize the difference measured as the angle between both <code>input1</code> and <code>input2</code> latent representations, you should fix <code>y</code> as:</p>
<p><code>y = torch.ones(x1.shape[0], device=torch.device("cuda"))</code></p>
<p>Where <code>y</code> equals the <code>target</code> tensor expected by <code>torch.CosineEmbeddingLoss</code> as in <code>torch.cosine_embedding_loss(input1, input2, target, margin, reduction_enum)</code></p>
<p>By having a random <code>y=target</code> vector you had conflicting (opposing) loss criteria.</p>
<p>I hope this may help someone else in the future.<br>
Cheers,<br>
Jose</p>