問題描述:
在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 文件裏寫入了剛剛添加的執行器: