简体   繁体   English

使用 Python scikit sklearn 为最近邻 (knn) 分类器调用预测函数

[英]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我已经阅读了文档并且它具有预测功能: http : //scikit-learn.org/stable/modules/generated/sklearn.neighbors.KNeighborsClassifier.html

How to do the predict?怎么做预测?

Your are confusing the NearestNeighbors class and the KNeighborsClassifier class.您正在混淆NearestNeighbors类和KNeighborsClassifier类。 Only the second one has the predict function.只有第二个具有predict功能。

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. NearestNeighbors类是无监督的,不能用于分类,只能用于最近邻搜索。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM