# Cosine similarity between 2 vectors

I am really suprised that pytorch function nn.CosineSimilarity is not able to calculate simple cosine similarity between 2 vectors. How do I fix that?

vector: tensor([ 6.3014e-03, -2.3874e-04, 8.8004e-03, …, -9.2866e-09,
-3.9112e-05, 2.2280e-03])
vector1: tensor([ 6.3014e-03, -2.3874e-04, 8.8004e-03, …, -9.2866e-09,
-3.9112e-05, 2.2280e-03])

cos = nn.CosineSimilarity()
print (cos(vector,vector1))

I get error:
Traceback (most recent call last):
File “I:\software1\SpellChecker\Bert_embeding.py”, line 188, in
print (cos(vector,vector1))
File “C:\Users\pera\AppData\Local\Programs\Python\Python36\lib\site-packages\torch\nn\modules\module.py”, line 489, in call
result = self.forward(*input, **kwargs)
File “C:\Users\pera\AppData\Local\Programs\Python\Python36\lib\site-packages\torch\nn\modules\distance.py”, line 80, in forward
return F.cosine_similarity(x1, x2, self.dim, self.eps)
RuntimeError: The size of tensor a (1024) must match the size of tensor b (0) at non-singleton dimension 0

It works when i put cos = nn.CosineSimilarity(dim=0)

I think you figured out the answer yourself.

The documentation ( https://pytorch.org/docs/master/nn.html#cosinesimilarity ) makes it clear that the default dim is 1.