Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.fit(samples)
neigh.predict([[1., 1., 1.]]) # this cause error

I've read the documentation and it has predict function: http://scikit-learn.org/stable/modules/generated/sklearn.neighbors.KNeighborsClassifier.html

How to do the predict?

like image 883
user25629298551 Avatar asked Apr 26 '16 15:04

user25629298551


1 Answers

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)
neigh.fit(X, y) 
print(neigh.predict([[1.1]]))
print(neigh.predict_proba([[0.9]]))

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

like image 167
sietschie Avatar answered Nov 03 '22 06:11

sietschie