Issue defining KneighborsClassifier in Jupyter Notebooks
12,812
Had same issue. running the following worked for me:
model = sklearn.neighbors.KNeighborsClassifier(n_neighbors=5)
ran in:
Python 3.6.9
Comments
-
StormsEdge almost 2 years
I am attempting to utilize KNN on the Iris data set as a "Hello World" of Machine Learning. I am using a Jupyter Notebook from Anaconda and have been clearly documenting each step. A "NameError: name 'knn' is not defined" exception is currently being thrown when I attempt to use
knn.fit(X,Y)
What am I missing here? I attempted to test the definition of knn by callingprint(knn)
and I get the following output:KNeighborsClassifier(algorithm='auto', leaf_size=30, metric='minkowski', metric_params=None, n_jobs=1, n_neighbors=1, p=2, weights='uniform')
Code below:
#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)
-
Mohammad Athar over 6 yearswhat version of python and sklearn are you using?
-
Mohammad Athar over 6 yearsthis works fine for me, can you try restarting jupyter?
-
MaxPowers over 6 yearsPlease consider posting a minimal, complete and verifyable example of your problem. Lines 6 to 29 are unnecessary for your question. Besides that, your code runs flawlessly on my maschine (Python 3.6)
-
StormsEdge over 6 yearsI am running Python 3.6.3. It is potentially an issue with my Jupyter Notebook? I have tried restarting the notebook several times and it does not remedy the issue. I initially had an issue with creating a new notebook, but once i moved into the anaconda projects file i had no issue creating a new notebook.
-
MaxPowers over 6 yearsCould you please include the Error Message in your question?
-
StormsEdge over 6 yearsit's a NameError, which is listed above. "name 'knn' is not defined." I will add that more clearly to the above
-
MaxPowers over 6 yearsDid you execute the code exactly the same way you've posted it here? If not, please copy the listing form above and execute it in a single cell.
-
StormsEdge over 6 years@MaxPowers That is copy and pasted aside from the edits you've made
-
StormsEdge over 6 years@MaxPowers This is also code that runs in a Jupyter notebook as also mentioned.
-
MaxPowers over 6 yearsLet us continue this discussion in chat.
-
-
Mighty Diffy over 3 yearsor just:
from sklearn.neighbors import KNeighborsClassifier