module not found on ipython notebook

2019-03-24 16:21发布

I have an ipython notebook which starts with

import sklearn

When I run it, I get :

ImportError: No module named sklearn

indeed if I run the following snippet on the notebook, it's not showing scikit_learn:

import pip
installed_packages = pip.get_installed_distributions()
installed_packages_list = sorted(["%s==%s" % (i.key, i.version)
     for i in installed_packages])
print installed_packages_list

However when I run the snippet from command line, scikit_learn is in the list.

I thought of a version problem (module installed for one version and not on the other one), bur both on notebook and command line, sys.version give 2.7.5

Any idea about the issue here ?

Following cel's comments:

ipython -c "import sys; print(sys.executable)" 

outputs /usr/bin/python (and so does running import sys; print(sys.executable) directly in the notebook)

Then, /usr/bin/python -m pip install scikit-learn outputs: Requirement already satisfied (use --upgrade to upgrade): scikit-learn in /Users/MyUserName

2条回答
时光不老,我们不散
2楼-- · 2019-03-24 16:42

I was able to fix this error on Ubuntu by adding a cell to the top of the notebook appending the module directory to the path:

import sys
sys.path.append('/usr/lib/python2.7/dist-packages')

The path to add can be found when running pip install <something>, (such as numpy) and it tells you where each package is installed or already exists.

查看更多
唯我独甜
3楼-- · 2019-03-24 16:44

Is it possible that /usr/bin/python is actually a symlink?

The better solution is that you should be running your ipython notebook from a virtualenv that contains all the modules that you need.

查看更多
登录 后发表回答