我试图将Iris数据集上的KNN用作机器学习的“ Hello World”。我正在使用Anaconda的Jupyter Notebook,并且清楚地记录了每个步骤。尝试使用knn.fit(X,Y)时,当前会引发“ NameError:未定义名称'knn'”异常。我试图通过调用print(knn)来测试knn的定义,并且得到以下输出:

KNeighborsClassifier(algorithm='auto', leaf_size=30, metric='minkowski',
           metric_params=None, n_jobs=1, n_neighbors=1, p=2,
           weights='uniform')


代码如下:

#import the load_iris dataset
from sklearn.datasets import load_iris
#save "bunch" object containing iris dataset and its attributes
iris = load_iris()
X = iris.data
Y = iris.target

#import class you plan to use
from sklearn.neighbors import KNeighborsClassifier
knn = KNeighborsClassifier(n_neighbors = 1)

#Fit the model with data (aka "model training")
knn.fit(X,Y)

最佳答案

有同样的问题。
运行以下内容对我有用:

model = sklearn.neighbors.KNeighborsClassifier(n_neighbors=5)


跑进去:


  的Python 3.6.9

关于python - 在Jupyter Notebook中定义KneighborsClassifier的问题,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48190843/

10-13 22:17