【问题标题】:Improving performance (speed) of kNN classifier提高 kNN 分类器的性能(速度)
【发布时间】:2017-03-19 08:21:54
【问题描述】:

作为一项任务,我必须创建自己的 kNN 分类器,而不使用 for 循环。我设法使用scipy.spatial.KDTree 找到测试集中每个向量的最近邻,然后我使用scipy.stats.mode 返回预测类的列表。但是,当集合的大小非常大时,这需要很长时间。例如,我创建了以下受this page启发的示例

import numpy as np
from sklearn.model_selection import train_test_split
from scipy import spatial
from scipy.stats import mode

def predict(X_test):
    X = Y_train[tree.query(X_test, k=k)[1]]
    Y = mode(X, axis=-1)[0].T[0]
    return Y

def load_data():
    x1 = 1.5 * np.random.randn(100) + 1
    y1 = 1.5 * np.random.randn(100) + 2
    x2 = 1.5 * np.random.randn(100) + 3
    y2 = 1.5 * np.random.randn(100) + 4
    X  = np.vstack((np.hstack((x1,x2)),np.hstack((y1,y2)))).T
    y  = 1.0*np.hstack((np.zeros(100), np.ones(100)))
    return X, y

if __name__ == '__main__':
    X, y = load_data()
    X_train, X_test, Y_train, Y_test = train_test_split(X, y)

    k = 7
    Z = predict(np.c_[xx.ravel(), yy.ravel()])
    Z = Z.reshape(xx.shape)

由于X = Y_train[tree.query(X_test, k=k)[1]] 部分,这需要很长时间(40-60 秒!)。有什么方法可以提高 this 特定实现的速度,还是我应该考虑另一种方法来做到这一点?例如,sklearn 的实现只需要 0.4 秒,与我的实现相比,这快得离谱。

【问题讨论】:

    标签: python numpy scipy knn


    【解决方案1】:

    不得不阅读您的代码几次,但后来我看到您使用的是KDTree,而不是cKDTree。后者是在 Cython 中实现的(而不是普通的 python 和 numpy),应该会给你一个不错的加速。

    【讨论】:

      猜你喜欢
      • 2016-06-16
      • 1970-01-01
      • 2014-07-27
      • 1970-01-01
      • 2022-07-13
      • 2020-08-16
      • 2017-10-15
      • 1970-01-01
      • 2012-06-30
      相关资源
      最近更新 更多