"RuntimeWarning: invalid value encountered in arccos" in Cosine similarity
See original GitHub issueThe new added code has some issue:
# Distance based on cosine similarity
dot = np.sum(np.multiply(embeddings1, embeddings2), axis=1)
norm = np.linalg.norm(embeddings1, axis=1) * np.linalg.norm(embeddings2, axis=1)
similarity = dot / norm
dist = np.arccos(similarity) / math.pi
The valid range for arccos is [-1,1], I guess we need to clip the value before np.arccos.
Issue Analytics
- State:
- Created 5 years ago
- Reactions:1
- Comments:5 (1 by maintainers)
Top Results From Across the Web
RuntimeWarning: invalid value encountered in arccos
If you simplify to just np.arccos(90). (which is the first element in the array being passed to arccos), you'll get the same warning....
Read more >RuntimeWarning: invalid value encountered in arccos
When generating the precession SNR for certain configurations, there is sometimes a RuntimeWarning printed:
Read more >How to Fix: runtimewarning: invalid value encountered in ...
This error simply occurs when we performing a math operation and we encounter which is not valid as input.
Read more >runtimewarning: invalid value encountered in double_scalars
This error occurs when you attempt to perform some mathematical operation that involves extremely small or extremely large numbers and Python ...
Read more >numpy.arccos — NumPy v1.24 Manual
The inverse of cos so that, if y = cos(x) , then x = arccos(y) . Parameters: xarray_like ... Elsewhere, the out array...
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
after add np.minimum , the warning disappeared.
The similarity should already be in the range [-1, 1] (https://en.wikipedia.org/wiki/Cosine_similarity) so I’m not sure clipping would fix the issue. Could you print out the two embeddings for the case where you see the problem? It could be that they are the problem, e.g. containing NaNs, Infs etc. But if it turns out that the similarity goes out of the range due to some rounding effects clipping would make perfect sense. Thanks!