问题描述:
在anaconda创建了虚拟环境my_tensorflow,并且安装了sklearn。
进入虚拟环境,可以成功导入sklearn:
python
>> import sklearn
但是,在 jupyter notebook 却无法导入,ImportError: No module named 'sklearn.__check_build._check_build':
---------------------------------------------------------------------------
ModuleNotFoundError Traceback (most recent call last)
D:\MY\Anaconda3\lib\site-packages\sklearn\__check_build\__init__.py in <module>
43 try:
---> 44 from ._check_build import check_build # noqa
45 except ImportError as e:
ModuleNotFoundError: No module named 'sklearn.__check_build._check_build'
During handling of the above exception, another exception occurred:
ImportError Traceback (most recent call last)
<ipython-input-2-47b27fd5bde7> in <module>
3 import matplotlib.pyplot as plt
4 # from testCases import *
----> 5 import sklearn
6 import sklearn.datasets
7 import sklearn.linear_model
D:\MY\Anaconda3\lib\site-packages\sklearn\__init__.py in <module>
131 # process, as it may not be compiled yet
132 else:
--> 133 from . import __check_build
134 from .base import clone
135 __check_build # avoid flakes unused variable error
D:\MY\Anaconda3\lib\site-packages\sklearn\__check_build\__init__.py in <module>
44 from ._check_build import check_build # noqa
45 except ImportError as e:
---> 46 raise_build_error(e)
D:\MY\Anaconda3\lib\site-packages\sklearn\__check_build\__init__.py in raise_build_error(e)
39 to build the package before using it: run `python setup.py install` or
40 `make` in the source directory.
---> 41 %s""" % (e, local_dir, ''.join(dir_content).strip(), msg))
42
43 try:
ImportError: No module named 'sklearn.__check_build._check_build'
___________________________________________________________________________
Contents of D:\MY\Anaconda3\lib\site-packages\sklearn\__check_build:
setup.py _check_build.cp37-win_amd64.pyd__init__.py
__pycache__
___________________________________________________________________________
It seems that scikit-learn has not been built correctly.
If you have installed scikit-learn from source, please do not forget
to build the package before using it: run `python setup.py install` or
`make` in the source directory.
If you have used an installer, please check that it is suited for your
Python version, your operating system and your platform.
在 jupyter notebook 中输入:
import sys
sys.excutable
我们发现,显示的python解释器是默认的解释器,并不是虚拟环境的解释器:
这下问题就清楚了,sklearn 安装在虚拟环境中,用默认环境的解释器当然会出错。
解决方法:
我们需要将虚拟环境的解释器添加到 jupyter notebook 中,在运行 jupyter notebook 文件的时候选择这个解释器就行了。
# 进入目标虚拟环境
conda activate env_name
# 安装 ipykernel
pip install ipykernel
# 通过 ipykernel 为 jupyter notebook 添加内核
python -m ipykernel install --name env_name
# 退出虚拟环境
deactivate
# 启动 jupyter notebook
jupyter notebook
这时,在 kernel -> change kernel 一栏里就可以选择我们新添加的环境了:
我们可以看到 C:\ProgramData\jupyter\kernels 下多了刚刚添加的 kernel:
里面的 kernel.json 文件里写入了刚刚添加的执行器: