KNN算法

啊啊啊,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+y22 x1x2+y1y2

( x 1 − x 2 ) 2 + ( y 1 − y 2 ) 2 \sqrt{(x_1-x_2)^2 + (y_1-y_2)^2} (x1x2)2+(y1y2)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的开发者

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值