计算N个点和M个点之间的距离

KNN中,训练样本有train_count个,测试样本有test_count个,每个样本有attr_count个属性。现在需要快速计算test_count个测试样本和train_count个样本之间的距离,距离表示为一个test_count行、train_count列的矩阵。
这个问题可以转化为矩阵乘法,而矩阵乘法可以使用GPU进行加速。

import numpy as np

train_count = 3
test_count = 2
attr_count = 4
train = np.random.randint(0, 10, (train_count, attr_count))
test = np.random.randint(0, 10, (test_count, attr_count))


def one():
    c = np.empty((test_count, train_count), dtype=np.float32)
    for i in range(c.shape[0]):
        for j in range(c.shape[1]):
            c[i, j] = np.linalg.norm(test[i] - train[j])
    return c


def two():
    c = np.empty((test_count, train_count), dtype=np.float32)
    for i in range(c.shape[0]):
        c[i] = np.linalg.norm(test[i] - train, axis=1)
    return c


def three():
    d1 = np.linalg.norm(test, axis=1)
    d2 = np.linalg.norm(train, axis=1)
    d3 = np.matmul(test, train.T)
    d12 = (d1 ** 2).reshape(test_count, 1)
    d22 = (d2 ** 2).reshape(1, train_count)
    ans = np.sqrt(d12 + d22 - 2 * d3)
    return ans


print(one())
print(two())
print(three())

转载于:https://www.cnblogs.com/weiyinfu/p/10441191.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值