简体   繁体   中英

name 'KMeans' is not defined in Jupyter Notebook

在此处输入图片说明

I am unable to run KMeans() in my Jupyter Notebook. The same piece of code works correctly if I just use it in a Python script. I have already installed KMeans/Sklearn using.

!pip3 install KMeans

Then what's the issue?

The above two cells are not yet executed.

Please re-run all the cells. Probably you've restarted the kernel and forgot to run the cells where you've imported the KMeans from sklearn.cluster.

Straightforward answer: Write in a cell of the Jupyter notebook (in In[6] for example:

from sklearn.cluster import KMean
km=KMean(1)

And see if there is an error.

Long answer You have different cells in the Jupyter notebook. You need to execute all the cells if you have restarted Jupyter Notebook.

On your screenshots: It is written In[] in the two first pieces of code, and In[6] in the piece of code where you got the error. That might mean that you did not execute the two first cells (In[]) before the third (In[6]), thus the Kmean had not been imported.

What you can do: - Ensure you have executed the two first pieces of code ? - Ensure you did not clear the variables before executing In[6] ? (not sure if this function exists on Jupyter)

The idea behind cells in Jupyter is that you split the code in cell and when you change some part of your code you don't need to re-run all your code only parts of it.

ie you don't need to run the read input part of your code every time you change something.

What you did was to run the third cell first, so the import cell was not executed at all where you import KMeans from the sklearn module.

You should run the cells in order and if by any chance you get the an error regarding the KMeans class maybe you have not installed the sklearn module.

In order to install it, run pip install sklearn .

sklearn installation notes .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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