user25629298551 user25629298551 - 7 months ago 82
Python Question

Call predict function for nearest neighbor (knn) classifier with Python scikit sklearn

I've tried to call predict function of nearest neighbor and got the following error:

AttributeError: 'NearestNeighbors' object has no attribute 'predict'

The code is:

from sklearn.neighbors import NearestNeighbors
samples = [[0., 0., 0.], [0., .5, 0.], [1., 1., .5]]
neigh = NearestNeighbors()
neigh.predict([[1., 1., 1.]]) # this cause error

I've read the documentation and it has predict function:

How to do the predict?


Your are confusing the NearestNeighbors class and the KNeighborsClassifier class. Only the second one has the predict function.

Note the example from the link you posted:

X = [[0], [1], [2], [3]]
y = [0, 0, 1, 1]
from sklearn.neighbors import KNeighborsClassifier
neigh = KNeighborsClassifier(n_neighbors=3), y) 

The NearestNeighbors class is unsupervised and can not be used for classification but only for nearest neighbour searches.