pythonscikit-learnvirtualenvjupyter-notebook

Running Jupyter notebook in a virtualenv: installed sklearn module not available


I have installed a created a virtualenv machinelearn and installed a few python modules (pandas, scipy and sklearn) in that environment.

When I run jupyter notebook, I can import pandas and scipy in my notebooks - however, when I try to import sklearn, I get the following error message:

import sklearn

---------------------------------------------------------------------------
ImportError                               Traceback (most recent call last)
<ipython-input-1-8fd979e02004> in <module>()
----> 1 import sklearn

ImportError: No module named 'sklearn'

I am able to import all modules, at the command line - so I know they have been successfully installed:

(machinelearn) me@yourbox:~/path/to/machinelearn$ python -c "import pandas, scipy, sklearn"
(machinelearn) me@yourbox:~/path/to/machinelearn$ 

How can I import sklearn in my jupyter notebook running in a virtualenv?


Solution

  • You probably have not installed jupyter / IPython in your virtualenv. Try the following:

    python -c "import IPython"
    

    and check that the jupyter command found in your $PATH is the one from the bin folder of your venv:

    which jupyter
    

    For windows users in a powershell console, you can use the following to check that the jupyter command in your $env:Path is the one from the Scripts folder of you venv:

    get-command jupyter
    

    Edit: if this is the problem, just run python -m pip install jupyter in your venv.

    Edit 2: actually you might also need:

    python -m ipykernel install --user --name=my-virtualenv-name
    

    and then switch the kernel named "my-virtualenv-name" in the jupyter user interface.

    Edit 3: maybe the --user flag in the last command is a bad idea:

    python -m ipykernel install --name=my-virtualenv-name