简体   繁体   中英

can't import torch in vscode despite having anaconda interpreter and torch installed

I have both python38,37 and anaconda installed, OS - win10,x64.

I could not install torch in py38,37 - but installed it in anaconda.

system env var 'Path' has:

  • C:\python38\Scripts\
  • C:\python38\
  • C:\python37\Scripts\
  • C:\python37\
  • C:\anaconda3\
  • C:\anaconda3\Scripts

In vscode, despite that i have selected interpreter as Python 3.8.3 base-conda

在此处输入图像描述

I still can't import torch. But when using jupyter notebook, I can import torch:

import torch
print(torch.__path__)

['C:\\anaconda3\\lib\\site-packages\\torch']

How to import torch in vs code and choose the right interpreter?

When we import the module, we need to install the required module in the currently selected environment.( Python environments .)

I installed it in the base conda environment using the following statement:

conda install pytorch torchvision -c pytorch

在此处输入图像描述

We need to pay attention to the selected kernel in Jupyter Notebook:

在此处输入图像描述

what worked for me: uninstall py37,38. Only have anaconda as a source of all python libs. After import torch - you may get error from numpy lib:

from numpy.core._multiarray_umath import (
ImportError: DLL load failed: The specified module could not be found.

to fix it, add another system var:

C:\anaconda3\Library\bin

Actually maybe i did not need to delete other python versions. but after all, importing torch worked in vs code:

from platform import python_version
print(python_version())
import torch
import torchvision
import numpy as np
print(torch.__path__)
print(np.__version__)

output:

3.8.3
['C:\\anaconda3\\lib\\site-packages\\torch']
1.18.5

Install pytorch using the pip command shown below :

pip3 install torch torchvision torchaudio --extra-index-url https://download.pytorch.org/whl/cu113

Do this and then reload your vscode. If the error still exists, check if you install the module in your selected interpreter environment. This seemed to do the trick for me.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM