매번 찾기 귀찮아서 모아두는 개발팁

[Pytorch] cosine similarity를 matrix 형태로 계산

archive-er 2023. 1. 13. 14:03

어째 점점 한국어 실력이 퇴화하는 기분이라 제목을 뭐라고 해야할지 모르겠는데 대충

a = torch.randn(3, 5)
b = a
res = (a와 b의 코사인 유사도 계산)
print(res)
>> tensor([[1.0000, 0.xxxx, 0.xxxx],
	[0.xxxx, 1.0000, 0.xxxx],
    	[0.xxxx, 0.xxxx, 1.0000]])

코사인 유사도가 이런식으로 매트릭스로 나왔으면 좋겠다

 

이건 아카이빙 안할라했는데 두달전에 썼다가 까먹었길래 그냥 해둠

https://stackoverflow.com/questions/50411191/how-to-compute-the-cosine-similarity-in-pytorch-for-all-rows-in-a-matrix-with-re

 

How to compute the cosine_similarity in pytorch for all rows in a matrix with respect to all rows in another matrix

In pytorch, given that I have 2 matrixes how would I compute cosine similarity of all rows in each with all rows in the other. For example Given the input = matrix_1 = [a b] [c d]

stackoverflow.com

 

요약:

a_norm = a / a.norm(dim=1)[:, None]
b_norm = b / b.norm(dim=1)[:, None]
res = torch.mm(a_norm, b_norm.transpose(0,1))