python - numpy knn 与向量化嵌套矩阵

标签 python numpy knn array-broadcasting

我正在尝试使用 numpy 及其向量化来实现 KNN 算法。

import numpy as np

A = np.array([[11,12,13], [21,22,23], [31,32,33]])
B = np.array([[41,42,43], [51,52,53], [61,62,63]])
C = np.array([[71,72,73], [81,82,83], [91,92,93]])

X = np.array([A, B, C])

f = lambda a,b: (a-b)**2
np.sqrt(np.vectorize(f)(A, X).reshape(3,9).sum(axis=1))
# array([   0.,   90.,  180.])

如果我这样使用它,我会得到一个 3x1 矩阵,其中包含所有向量到 A 的距离。

要获得所有向量彼此之间的所有距离,我需要一个结果矩阵,如下所示:

array([[   0.,   90.,  180.],
       [  90.,    0.,   90.],
       [ 180.,   90.,    0.]])

如何改进操作以获得所需的结果?

最佳答案

In [843]: np.sqrt(f(X[:,None],X).reshape(3,3,9).sum(axis=-1))
Out[843]: 
array([[   0.,   90.,  180.],
       [  90.,    0.,   90.],
       [ 180.,   90.,    0.]])

您不需要矢量化f 直接使用数组。

但是看看

In [841]: f(X[:,None],X).reshape(3,3,9)
Out[841]: 
array([[[   0,    0,    0,    0,    0,    0,    0,    0,    0],
        [ 900,  900,  900,  900,  900,  900,  900,  900,  900],
        [3600, 3600, 3600, 3600, 3600, 3600, 3600, 3600, 3600]],

       [[ 900,  900,  900,  900,  900,  900,  900,  900,  900],
        [   0,    0,    0,    0,    0,    0,    0,    0,    0],
        [ 900,  900,  900,  900,  900,  900,  900,  900,  900]],

       [[3600, 3600, 3600, 3600, 3600, 3600, 3600, 3600, 3600],
        [ 900,  900,  900,  900,  900,  900,  900,  900,  900],
        [   0,    0,    0,    0,    0,    0,    0,    0,    0]]], dtype=int32)

让我怀疑您计算的值超出了需要的值。但我没有尝试着眼于大局。

关于python - numpy knn 与向量化嵌套矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47166650/

相关文章:

python - Flask + Gunicorn + Nginx,使用来自非根位置 block 的 proxy_pass 出现 404 错误

python - 使用 Flask-SQLAlchemy 连接到 MSSQL 数据库

python - 从 Pandas DataFrame 快速填充大型 Numpy 矩阵

python - 将日期/时间拆分为句点的 If 语句

python - knn 的 y 轴样本不匹配

python - C++ 中超出了内存限制,但 Python 中未超出内存限制

python - numpy:沿新轴扩展数组?

python - 从记录中用 Pandas 索引几个 csv 文件?

python - sklearn : Nearest Neightbour with String-Values and Custom Metric

c# - 如何在 C# 中针对大量维度最好地实现 K 最近邻?