tensor와 유사도

J. Hwang·2024년 8월 7일

유사도 (Similarity) 는 두 벡터 (→ 1-D tensor) 가 얼마나 유사한지에 대한 측정값이다.
유사도는 군집화 (clustering) 알고리즘에서 데이터들이 얼마나 유사한지 판단하는 기준이 된다.
유사도를 계산하는 방법에는 맨해튼 유사도, 유클리드 유사도, 코사인 유사도가 있다.

맨해튼 유사도

  • 두 1-D tensor 사이의 맨해튼 거리 (Manhattan distance) 를 역수로 변환하여 계산한 값

  • 두 tensor 사이의 맨해튼 거리 값이 작을수록 맨해튼 유사도의 값이 커진다.

  • 맨해튼 유사도의 값이 1에 가까울수록 두 tensor가 유사하다고 판단한다.

    Manhattan distance = i=1n\sum_{i=1}^{n} xiyi|x_i -y_i|
    Manhattan similarity = 1 / (1+ Manhanttan distance)

  • torch.norm(a-b, p=1) 으로 tensor a와 b 사이의 manhattan distance를 구할 수 있다.

a = torch.tensor([1, 0, 2])
b = torch.tensor([0, 1, 2])

# Manhattan distance
m_d = torch.norm(a-b, p=1)
# Manhattan similarity
m_s = 1/(1+m_d)

유클리드 유사도

  • 두 1-D tensor 사이의 유클리드 거리를 역수로 변환하여 계산한 값
  • 두 tensor 사이의 유클리드 거리의 값이 작아질수록 유클리드 유사도의 값이 커진다.
  • 유클리드 유사도의 값이 1에 가까울수록 두 tensor가 유사하다고 판단한다.

    Euclidean distance = (i=1nxiyi2)\sqrt(\sum_{i=1}^{n} |x_i - y_i|^2)
    Euclidean similarity = 1 / (1 + Euclidean distance)

  • torch.(a-b, p=2)로 tensor a와 b 사이의 euclidean distance를 구할 수 있다.
a = torch.tensor([1, 0, 2])
b = torch.tensor([0, 1, 2])

# Euclidean distance
e_d = torch.norm(a-b, p=2)
# Euclid similarity
e_s = 1/(1+e_d)

코사인 유사도

  • 두 1-D tensor 사이의 각도를 측정하여 계산한 값
  • 코사인 유사도의 값이 1에 가까울수록 두 tensor가 유사하다고 판단한다. (cos0=1\because{cos 0 = 1})
  • 1-D tensor는 벡터이므로, 벡터의 내적을 통해 각도를 측정할 수 있음

AB\vec{A} \cdot \vec{B} = ABcosθ|A||B|cos\theta

  • torch.dot(a, b) 를 통해 tensor a와 b를 내적할 수 있다.
a = torch.tensor([1, 0, 2])
b = torch.tensor([0, 1, 2])

# dot product of a and b
c = torch.dot(a, b)

# norm of a and b
norm_a = torch.norm(a, p=2)
norm_b = torch.norm(b, p=2)

cos_similarity = c / (norm_a * norm_b)
profile
Let it code

0개의 댓글