어째 점점 한국어 실력이 퇴화하는 기분이라 제목을 뭐라고 해야할지 모르겠는데 대충
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]])
코사인 유사도가 이런식으로 매트릭스로 나왔으면 좋겠다
이건 아카이빙 안할라했는데 두달전에 썼다가 까먹었길래 그냥 해둠
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))
'매번 찾기 귀찮아서 모아두는 개발팁' 카테고리의 다른 글
[Python] 특수문자 제거 (0) | 2023.01.31 |
---|---|
[Python] List Comprehension + if ~ else (0) | 2023.01.26 |
[Python] dictionary/json 예쁘게 출력하기 (0) | 2023.01.17 |
[Python/Pandas] nan 데이터(결측값)가 있는 행/열 제거 (0) | 2023.01.16 |
[Python] 코드 내에서 argparse와 유사한 기능을 제공하는 구조체 만들기 (0) | 2023.01.13 |