Cannot import torch inside Jupyter Notebook (conda virtual env)

一般來說,透過conda相關指令啟用虛擬環境後,並安裝相關套件、於CMD中輸入jupyter notebook,就可以開啟Jupyter。再進行後續的import。

只是今天突然遇見一個問題:

明明已經在虛擬環境下安裝了torch

conda install pytorch torchvision cudatoolkit=10.2 -c pytorch

接著輸入

jupyter notebook

並且在cell中

import torch

卻顯示No module named”torch”,相當的奇怪。

經過實測的狀況下,我找出了一個解決方案如下:

conda install jupyter

我個人猜測是原本conda虛擬環境中叫出的jupyter可能不是屬於conda虛擬環境的版本,而是在其他地方抓進來的,所以安裝torch後並無法讓jupyter正常讀取到torch。

透過在虛擬環境中安裝jupyter後,並再度import torch,就可以正常運作了。

(base)  $ conda create --name myenv python=3.5
(base) $ activate myenv
(myenv) $conda install pytorch torchvision cudatoolkit=10.2 -c pytorch
(myenv) $ conda install jupyter
(myenv) $ jupyter notebook
(在jupyter notebook的cell):
import torch
torch.__version__

Machine Learning / Deep Learning / Python / Flutter cakeresume.com/yanwei-liu

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store