在虛擬環境tf中安裝完tensorflow后,在虛擬環境tf打開的jupyter里發現只有一個kernel-python3,新建一個文件,
import tensorflow as tf ,發現報錯,沒有tf這個模塊。
一開始還以為是tf的問題安裝失敗,后來才意識到是jupyter的問題。因為在虛擬環境tf中,雖然有jupyter(或者自己再安裝pip install jupyter,他會提示說已存在),但這個jupyter還是原python環境中的jupyter。在虛擬環境tf中用命令 (tf) treamy ~ $ which jupyter 得/usr/local/bin/jupyter 再用 (tf) treamy ~ $ find ~/code/pydir/env -name "jupyter*" 發現虛擬環境中無jupyter 。故虛擬環境中的jupyter還是原python環境中的jupyter,kernel為python3,而我的原python3並沒有安裝tensorflow,所以報錯了。
一開始還以為是tf的問題安裝失敗,后來才意識到是jupyter的問題。因為在虛擬環境tf中,雖然有jupyter(或者自己再安裝pip install jupyter,他會提示說已存在),但這個jupyter還是原python環境中的jupyter。在虛擬環境tf中用命令 (tf) treamy ~ $ which jupyter 得/usr/local/bin/jupyter 再用 (tf) treamy ~ $ find ~/code/pydir/env -name "jupyter*" 發現虛擬環境中無jupyter 。故虛擬環境中的jupyter還是原python環境中的jupyter,kernel為python3,而我的原python3並沒有安裝tensorflow,所以報錯了。
之前查網上按這個方法解決:(但無效)
(tf) treamy ~ $ ipython kernelspec install-self --user
[TerminalIPythonApp] WARNING | Subcommand `ipython kernelspec` is deprecated and will be removed in future versions.
[TerminalIPythonApp] WARNING | You likely want to use `jupyter kernelspec` in the future
[InstallNativeKernelSpec] WARNING | `jupyter kernelspec install-self` is DEPRECATED as of 4.0. You probably want `ipython kernel install` to install the IPython kernelspec.
[InstallNativeKernelSpec] Installed kernelspec python3 in /Users/treamy/Library/Jupyter/kernels/python3
(tf) treamy ~ $ mkdir -p ~/.ipython/kernels (tf) treamy ~ $ mv /Users/treamy/Library/Jupyter/kernels/python3 ~/.ipython/kernels/tfkernel
打開kernel.json文件,然后將display_name 后面的內容修改為tfkernel
(tf) treamy ~ $ vim ~/.ipython/kernels/tfkernel/kernel.json
但這樣並無效果,因為創建的kernel相當於只是原kernel的復制品即python3,從上面那個json文件就可以看出來。
解決方案:
(tf) treamy ~ $ python3 -m ipykernel install --user --name tf --display-name "Python3(tf)"
# Installed kernelspec tf in /Users/treamy/Library/Jupyter/kernels/tf
cd 到 /Users/treamy/Library/Jupyter/kernels/tf
里面含
kernel.json logo-32x32.png logo-64x64.png
查看這個json文件:
cat kernel.json
{
"argv": [
"/Users/treamy/code/pydir/env/tf/bin/python3",
"-m",
"ipykernel_launcher",
"-f",
"{connection_file}"
],
"display_name": "Python3(tf)",
"language": "python"
}
然后也不用移動它,就這樣就OK了。刷新jupyter后就可以看到Python3(tf)這個選項。
詳細官方文檔:
