【问题标题】:improve linear search for KNN efficiency w/ NumPY使用 NumPY 提高 KNN 效率的线性搜索
【发布时间】:2016-09-13 07:24:36
【问题描述】:

我正在尝试计算测试集中每个点到训练集中每个点的距离:

这就是我的循环现在的样子:

 for x in testingSet
    for y in trainingSet
        print numpy.linalg.norm(x-y)

其中 testingSet 和 trainingSet 是 numpy 数组,其中两组的每一行都保存一个示例的特征数据。

但是,由于我的数据集较大(测试集为 3000,训练集约为 10,000),它的运行速度非常慢,需要 10 多分钟。这与我的方法有关还是我错误地使用了 numPY?

【问题讨论】:

    标签: python numpy machine-learning


    【解决方案1】:

    这是因为您天真地迭代数据,并且循环在 python 中很慢。相反,使用 sklearn pairwise distance functions,甚至更好 - 使用 sklearn efficient nearest neighbour 搜索(如 BallTree 或 KDTree)。如果你不想使用sklearn,还有一个module in scipy。最后,您可以使用“矩阵技巧”来计算它,因为

    || x - y ||^2 = <x-y, x-y> = <x,x> + <y,y> - 2<x,y>
    

    你可以这样做(假设你的数据是矩阵形式,如 X 和 Y):

    X2 = (X**2).sum(axis=1).reshape((-1, 1))
    Y2 = (Y**2).sum(axis=1).reshape((1, -1))
    distances = np.sqrt(X2 + Y2 - 2*X.dot(Y.T))
    

    【讨论】:

    • 非常棒的答案。 +1
    猜你喜欢
    • 2016-01-19
    • 1970-01-01
    • 1970-01-01
    • 2020-03-11
    • 2019-12-20
    • 2012-05-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多