<p>Modifying your class and using <code>BallTree</code> data structure (with build time <code>O(n.(log n)^2)</code>, refer to <a href="https://arxiv.org/ftp/arxiv/papers/1210/1210.6122.pdf" rel="nofollow noreferrer">https://arxiv.org/ftp/arxiv/papers/1210/1210.6122.pdf</a>) with custom <code>DistanceMetric</code> (since Callable functions in the metric parameter are NOT supported for <code>KDTree</code>, as mentioned here as a note: <a href="https://scikit-learn.org/stable/modules/generated/sklearn.neighbors.BallTree.html" rel="nofollow noreferrer">https://scikit-learn.org/stable/modules/generated/sklearn.neighbors.BallTree.html</a>), you can use the following code too (also removing the loop for prediction):</p>
<pre><code>from sklearn.neighbors import BallTree
from sklearn.neighbors import DistanceMetric
from scipy.stats import mode

class GlobalWeightedKNN:
    &quot;&quot;&quot;
    A k-NN classifier with feature weights

    Returns: predictions of k-NN.
    &quot;&quot;&quot;

    def __init__(self):
        self.X_train = None
        self.y_train = None
        self.k = None
        self.weights = None
        self.tree = None
        self.predictions = list()

    def fit(self, X_train, y_train, k, weights):        
        self.X_train = X_train
        self.y_train = y_train
        self.k = k
        self.weights = weights
        self.tree = BallTree(X_train, \
                             metric=DistanceMetric.get_metric('wminkowski', p=2, w=weights))

    def predict(self, testing_data):
        &quot;&quot;&quot;
        Takes a 2d array of query cases.

        Returns a list of predictions for k-NN classifier
        &quot;&quot;&quot;
        indexes = self.tree.query(testing_data, self.k, return_distance=False)
        y_answers = self.y_train[indexes]
        self.predictions = np.apply_along_axis(lambda x: mode(x)[0], 1, y_answers)
        return self.predictions
</code></pre>
<p>Training:</p>
<pre><code>from time import time
n, d = 10000, 2
begin = time()
cls = GlobalWeightedKNN()
X_train = np.random.rand(n,d)
y_train = np.random.choice(2,n, replace=True)
cls.fit(X_train, y_train, k=3, weights=np.random.rand(d))
end = time()
print('time taken to train {} instances = {} s'.format(n, end - begin))
# time taken to train 10000 instances = 0.01998615264892578 s
</code></pre>
<p>Testing / prediction:</p>
<pre><code>begin = time()
X_test = np.random.rand(n,d)
cls.predict(X_test)
end = time()
print('time taken to predict {} instances  = {} s'.format(n, end - begin))
#time taken to predict 10000 instances  = 3.732935905456543 s
</code></pre>
Faster kNN algorithm in Python
<p>I want to code my own kNN algorithm from scratch, the reason is that I need to weight the features. The problem is that my program is still really slow despite removing for loops and using built in numpy functionality.</p>

<p>Can anyone suggest a way to speed this up? I don't use <code>np.sqrt</code> for the L2 distance because it's unnecessary and actually slows it all up quite a bit.</p>

<pre><code>class GlobalWeightedKNN:
    """
    A k-NN classifier with feature weights

    Returns: predictions of k-NN.
    """

    def __init__(self):
        self.X_train = None
        self.y_train = None
        self.k = None
        self.weights = None
        self.predictions = list()

    def fit(self, X_train, y_train, k, weights):        
        self.X_train = X_train
        self.y_train = y_train
        self.k = k
        self.weights = weights

    def predict(self, testing_data):
        """
        Takes a 2d array of query cases.

        Returns a list of predictions for k-NN classifier
        """

        np.fromiter((self.__helper(qc) for qc in testing_data), float)  
        return self.predictions


    def __helper(self, qc):
        neighbours = np.fromiter((self.__weighted_euclidean(qc, x) for x in self.X_train), float)
        neighbours = np.array([neighbours]).T 
        indexes = np.array([range(len(self.X_train))]).T
        neighbours = np.append(indexes, neighbours, axis=1)

        # Sort by second column - distances
        neighbours = neighbours[neighbours[:,1].argsort()]  
        k_cases = neighbours[ :self.k]
        indexes = [x[0] for x in k_cases]

        y_answers = [self.y_train[int(x)] for x in indexes]
        answer = max(set(y_answers), key=y_answers.count)  # get most common value
        self.predictions.append(answer)


    def __weighted_euclidean(self, qc, other):
        """
        Custom weighted euclidean distance

        returns: floating point number
        """

        return np.sum( ((qc - other)**2) * self.weights )
</code></pre>