Knowledge Base

Distance Between Vectors

Glossary

Class: a new data type with its own methods and attributes.

Euclidian distance: the between vectors a=(x1,x2,,xn)a=(x_1, x_2,\dots, x_n) and b=(y1,y2,,yn)b=(y_1, y_2,\dots,y_n) is the sum of squared differences of coordinates:

d2(a,b)=(x1y1)2+(x2y2)2++(xnyn)2=i=1n(xiyi)2\begin{aligned} d_2(a,b)&=\sqrt{(x_1-y_1)^2+(x_2-y_2)^2+\dots+(x_n-y_n)^2}\\ &=\sqrt{\sum_{i=1}^n(x_i-y_i)^2} \end{aligned}

Manhattan distance/city block distance: the sum of modules of coordinate differences of vectors a=(x1,x2,,xn)a=(x_1, x_2,\dots, x_n) and b=(y1,y2,,yn)b=(y_1, y_2,\dots,y_n):

d1(a,b)=x1y1+x2y2++xnyn=i=1nxiyi\begin{aligned} d_1(a,b)&=|x_1-y_1|+|x_2-y_2|+\dots+|x_n-y_n|\\&=\sum_{i=1}^n |x_i-y_i| \end{aligned}

Scalar product: an operation resulting in a number (scalar) that is equal to the sum of element-by-element products of two vectors' elements

Practice

1# Scalar product of vectors
2
3import numpy as np
4
5dot_value1 = np.dot(vector1, vector2)
6dot_value2 = vector1 @ vector2

1# Euclidean distance between vectors
2
3import numpy as np
4from scipy.spatial import distance
5
6d = distance.euclidean(a, b)

1# Manhattan distance between vectors
2
3import numpy as np
4from scipy.spatial import distance
5
6d = distance.cityblock(a, b)

1# Indices of minimum and maximum elements in array
2
3index = np.array(distances).argmin() # minimum element index
4index = np.array(distances).argmax() # maximum element index

1# Creating class
2
3class ClassName:
4 def fit(self, arg1, arg2, ...): # class method
5 # method content
Send Feedback
close
  • Bug
  • Improvement
  • Feature
Send Feedback
,