啊啊啊,KNN好难啊
话说回来,这两个公式有没有把你绕晕呢
c o s ( θ ) = x 1 x 2 + y 1 y 2 x 1 2 + y 1 2 × x 2 2 + y 2 2 cos(\theta) = \frac{x_1x_2+y_1y_2}{\sqrt{x_1^2+y_1^2} \times {\sqrt{x_2^2+y_2^2}}} cos(θ)=x12+y12×x22+y22x1x2+y1y2
( x 1 − x 2 ) 2 + ( y 1 − y 2 ) 2 \sqrt{(x_1-x_2)^2 + (y_1-y_2)^2} (x1−x2)2+(y1−y2)2
没错,这就是余弦相似度以及距离公式
我在Github
上有一篇博客,把这个讲的清清楚楚(不过就是讲个案例贴个代码)博客链接
要是有个工具包那该多好啊~
别急,Wdata
就有!
而且是两个都有!!!
在哪呢,在这呢
余弦相似度距离公式工具包
下载:
pip3 install simplejson
pip3 install openpyxl
pip3 install matplotlib
pip3 install setuptools
pip3 install Wdatabase
使用方法:
from Wdata import mathfunc
Xy1=(2, 3) # First coordinate
Xy2=(3, 5) # Second coordinate
Result=mathfunc.similarity (Xy1, Xy2) # Cosine similarity
print(result)
这个是余弦相似度的
实现代码如下(供参考)
def similarity(xy1: tuple, xy2: tuple) -> float:
"""
This function can use the cosine similarity formula to calculate the similarity of the two coordinates and return
the similarity value
:param xy1: tuple
:param xy2: tuple
:return: float
"""
result = (xy1[0] * xy2[0] + xy1[1] * xy2[1]) / ((math.sqrt(xy1[0] ** 2 + xy1[1] ** 2)) * (math.sqrt(xy2[0] ** 2 + xy2[1] ** 2)))
return result
# From Github https://github.com/Wdataorg/Wdata/blob/main/Wdata/mathfunc.py
欧几里得距离公式代码:
from Wdata import mathfunc
xy1 = (2, 3)
xy2 = (3, 5)
Result=mathfunc.distance (xy1, xy2) # Distance formula
print(result)
实现代码(供参考)
def distance(xy1: tuple, xy2: tuple) -> float:
"""
This function can use Euclid distance formula to calculate the distance of 2 coordinates and return
the distance value
:param xy1: tuple
:param xy2: tuple
:return: float
"""
result = math.sqrt((xy1[0] - xy2[0])**2 + (xy1[1]-xy2[1])**2)
return result
# From Github https://github.com/Wdataorg/Wdata/blob/main/Wdata/mathfunc.py
除此之外,Wdata
还有一些没啥卵用的功能:比如,数据集访问,绘图,保存文件(支持xlsx
,csv
,json
)
想要了解更多,请看Wdata Github链接以及README
记得给个star(doge)
作者是Wdata的开发者