M
M
Mark Adams2015-12-12 16:58:41
Python
Mark Adams, 2015-12-12 16:58:41

What is the correct way to use Scikit-Learn's kNN algorithm?

I have a makeshift K-nearest neighbors algorithm, it finds the nearest for a particular (new) object 'x' and determines which class it belongs to. How to implement the same algorithm but using Scikit-Learn Nearest Neighbors?

def kNN(x, dataSet, labels, k):
    dataSetSize = dataSet.shape[0]
    diffMat = tile(x, (dataSetSize,1)) - dataSet
    sqDiffMat = diffMat ** 2
    sqDistances = sqDiffMat.sum(axis=1)
    distances = sqDistances ** 0.5
    sortedDistances = distances.argsort()
    classCount = {}
    for i in arange(k):
        votelabel = labels[sortedDistances[i]]
        classCount[votelabel] = classCount.get(votelabel,0) + 1
    sortedClassCount = sorted(classCount.iteritems(), key=operator.itemgetter(1), reverse=True)
    return sortedClassCount[0][0]

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question