Меню

Pytorch ошибка при установке

When using Python, a common error you may encounter is modulenotfounderror: no module named ‘torch’. This error occurs when Python cannot detect the PyTorch library in your current environment. This tutorial goes through the exact steps to troubleshoot this error for the Windows, Mac and Linux operating systems.


Table of contents

  • ModuleNotFoundError: no module named ‘torch’
    • What is PyTorch?
    • How to Install PyTorch on Windows Operating System
      • PyTorch installation with Pip on Windows for CPU
      • PyTorch installation with Pip on Windows for CUDA 10.2
      • PyTorch installation with Pip on Windows for CUDA 11.3
    • How to Install PyTorch on Mac Operating System
    • How to Install PyTorch on Linux Operating Systems
      • Installing pip for Ubuntu, Debian, and Linux Mint
      • Installing pip for CentOS 8 (and newer), Fedora, and Red Hat
      • Installing pip for CentOS 6 and 7, and older versions of Red Hat
      • Installing pip for Arch Linux and Manjaro
      • Installing pip for OpenSUSE
      • PyTorch installation on Linux with Pip for CPU
      • PyTorch installation on Linux with Pip for CUDA 10.2
      • PyTorch installation on Linux with Pip for CUDA 11.3
  • Installing PyTorch Using Anaconda
    • Installing PyTorch Using Anaconda for CPU
    • Installing PyTorch Using Anaconda for CUDA 10.2
    • Installing PyTorch Using Anaconda for CUDA 11.3
    • Check PyTorch Version
  • Summary

ModuleNotFoundError: no module named ‘torch’

What is PyTorch?

PyTorch is an open-source deep learning framework developed by Facebook’s AI Research lab. PyTorch provides a beginner-friendly and Pythonic API for building complex models for research and industrial applications.

The simplest way to install PyTorch is to use the package manager for Python called pip. The following installation instructions are for the major Python version 3.

When you want to install PyTorch using pip, the packages to install together are torch, torchvision, and torchaudio.

How to Install PyTorch on Windows Operating System

First, you need to download and install Python on your PC. Ensure you select the install launcher for all users and Add Python to PATH checkboxes. The latter ensures the interpreter is in the execution path. Pip is automatically on Windows for Python versions 2.7.9+ and 3.4+.

You can check your Python version with the following command:

python3 --version

You can install pip on Windows by downloading the installation package, opening the command line and launching the installer. You can install pip via the CMD prompt by running the following command.

python get-pip.py

You may need to run the command prompt as administrator. Check whether the installation has been successful by typing.

pip --version

PyTorch installation with Pip on Windows for CPU

To install PyTorch for CPU, run the following command from the command prompt.

pip3 install torch torchvision torchaudio

PyTorch installation with Pip on Windows for CUDA 10.2

To install PyTorch for CUDA 10.2, run the following command from the command prompt.

pip3 install torch==1.10.0+cu102 torchvision==0.11.1+cu102 torchaudio===0.10.0+cu102 -f https://download.pytorch.org/whl/cu102/torch_stable.html

PyTorch installation with Pip on Windows for CUDA 11.3

To install PyTorch for CUDA 11.3, run the following command from the command prompt.

pip3 install torch==1.10.0+cu113 torchvision==0.11.1+cu113 torchaudio===0.10.0+cu113 -f https://download.pytorch.org/whl/cu113/torch_stable.html

How to Install PyTorch on Mac Operating System

Open a terminal by pressing command (⌘) + Space Bar to open the Spotlight search. Type in terminal and press enter. To get pip, first ensure you have installed Python3:

python3 --version
Python 3.8.8

Download pip by running the following curl command:

curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py

The curl command allows you to specify a direct download link. Using the -o option sets the name of the downloaded file.

Install pip by running:

python3 get-pip.py

From the terminal, use pip3 to install PyTorch:

pip3 install torch torchvision torchaudio

Note that this is the only way to install PyTorch using pip on the Mac operating system because the macOS binaries do not support CUDA. You can install from the source if you need CUDA.

How to Install PyTorch on Linux Operating Systems

All major Linux distributions have Python installed by default. However, you will need to install pip. You can install pip from the terminal, but the installation instructions depend on the Linux distribution you are using. You will need root privileges to install pip. Open a terminal and use the commands relevant to your Linux distribution to install pip.

Installing pip for Ubuntu, Debian, and Linux Mint

sudo apt install python-pip3

Installing pip for CentOS 8 (and newer), Fedora, and Red Hat

sudo dnf install python-pip3

Installing pip for CentOS 6 and 7, and older versions of Red Hat

sudo yum install epel-release

sudo yum install python-pip3

Installing pip for Arch Linux and Manjaro

sudo pacman -S python-pip

Installing pip for OpenSUSE

sudo zypper python3-pip

PyTorch installation on Linux with Pip for CPU

Once you have installed pip, you can install PyTorch using:

pip3 install torch==1.10.0+cpu torchvision==0.11.1+cpu torchaudio==0.10.0+cpu -f https://download.pytorch.org/whl/cpu/torch_stable.html

PyTorch installation on Linux with Pip for CUDA 10.2

Once you have installed pip, you can install PyTorch using:

pip3 install torch torchvision torchaudio

PyTorch installation on Linux with Pip for CUDA 11.3

Once you have installed pip, you can install PyTorch using:

pip3 install torch==1.10.0+cu113 torchvision==0.11.1+cu113 torchaudio==0.10.0+cu113 -f https://download.pytorch.org/whl/cu113/torch_stable.html

Installing PyTorch Using Anaconda

First, to create a conda environment to install PyTorch.

conda create -n pytorch python=3.6 numpy=1.13.3 scipy

Then activate the PyTorch container. You will see “pytorch” in parentheses next to the command line prompt.

source activate pytorch

Now you’re ready to install PyTorch using conda. The command will change based on the operating system and whether or not you need CUDA.

Installing PyTorch Using Anaconda for CPU

Anaconda is a distribution of Python and R for scientific computing and data science. You can install Anaconda by going to the installation instructions. Once you have installed Anaconda and created your conda environment, you can install PyTorch using the following command:

conda install pytorch torchvision torchaudio cpuonly -c pytorch

Note that this is the only way to install PyTorch using conda on the Mac operating system because the macOS binaries do not support CUDA. You can install from the source if you need CUDA.

Installing PyTorch Using Anaconda for CUDA 10.2

Anaconda is a distribution of Python and R for scientific computing and data science. You can install Anaconda by going to the installation instructions. Once you have installed Anaconda, you can install PyTorch using the following command:

conda install pytorch torchvision torchaudio cudatoolkit=10.2 -c pytorch

Installing PyTorch Using Anaconda for CUDA 11.3

Anaconda is a distribution of Python and R for scientific computing and data science. You can install Anaconda by going to the installation instructions. Once you have installed Anaconda, you can install PyTorch using the following command:

conda install pytorch torchvision torchaudio cudatoolkit=11.3 -c pytorch

Check PyTorch Version

Once you have successfully installed PyTorch, you can use two methods to check the version of PyTorch. First, you can use pip show from your terminal. Remember that the name of the PyTorch package is torch.

pip show torch
Name: torch
Version: 1.10.0+cu102
Summary: Tensors and Dynamic neural networks in Python with strong GPU acceleration
Home-page: https://pytorch.org/
Author: PyTorch Team
Author-email: [email protected]
License: BSD-3
Location: /home/ubuntu/anaconda3/envs/tensorflow2_latest_p37/lib/python3.7/site-packages
Requires: typing-extensions
Required-by: torchaudio, torchvision

Second, within your python program, you can import torch and then reference the __version__ attribute:

import torch

print(torch.__version__)
1.10.0+cu102

If you used conda to install PyTorch, you could check the version using the following command:

conda list -f pytorch

Summary

Congratulations on reading to the end of this tutorial. The modulenotfounderror occurs if you misspell the module name, incorrectly point to the module path or do not have the module installed in your Python environment. If you do not have the module installed in your Python environment, you can use pip to install the package. However, you must ensure you have pip installed on your system. You can also install Anaconda on your system and use the conda install command to install PyTorch.

For further reading on operations with PyTorch, go to the article: How to Convert NumPy Array to PyTorch Tensor.

Go to the online courses page on Python to learn more about Python for data science and machine learning.

For further reading on missing modules, go to the articles:

  • How to Solve Python ModuleNotFoundError: no module named ‘pil’.
  • How to Solve ModuleNotFoundError: No module named ‘tensorflow.contrib’.

Have fun and happy researching!

Building from source¶

Include optional components¶

There are two supported components for Windows PyTorch:
MKL and MAGMA. Here are the steps to build with them.

REM Make sure you have 7z and curl installed.

REM Download MKL files
curl https://s3.amazonaws.com/ossci-windows/mkl_2020.2.254.7z -k -O
7z x -aoa mkl_2020.2.254.7z -omkl

REM Download MAGMA files
REM version available:
REM 2.5.4 (CUDA 10.1 10.2 11.0 11.1) x (Debug Release)
REM 2.5.3 (CUDA 10.1 10.2 11.0) x (Debug Release)
REM 2.5.2 (CUDA 9.2 10.0 10.1 10.2) x (Debug Release)
REM 2.5.1 (CUDA 9.2 10.0 10.1 10.2) x (Debug Release)
set CUDA_PREFIX=cuda102
set CONFIG=release
curl -k https://s3.amazonaws.com/ossci-windows/magma_2.5.4_%CUDA_PREFIX%_%CONFIG%.7z -o magma.7z
7z x -aoa magma.7z -omagma

REM Setting essential environment variables
set "CMAKE_INCLUDE_PATH=%cd%mklinclude"
set "LIB=%cd%mkllib;%LIB%"
set "MAGMA_HOME=%cd%magma"

Speeding CUDA build for Windows¶

Visual Studio doesn’t support parallel custom task currently.
As an alternative, we can use Ninja to parallelize CUDA
build tasks. It can be used by typing only a few lines of code.

REM Let's install ninja first.
pip install ninja

REM Set it as the cmake generator
set CMAKE_GENERATOR=Ninja

One key install script¶

You can take a look at this set of scripts.
It will lead the way for you.

Extension¶

CFFI Extension¶

The support for CFFI Extension is very experimental. You must specify
additional libraries in Extension object to make it build on
Windows.

ffi = create_extension(
    '_ext.my_lib',
    headers=headers,
    sources=sources,
    define_macros=defines,
    relative_to=__file__,
    with_cuda=with_cuda,
    extra_compile_args=["-std=c99"],
    libraries=['ATen', '_C'] # Append cuda libraries when necessary, like cudart
)

Cpp Extension¶

This type of extension has better support compared with
the previous one. However, it still needs some manual
configuration. First, you should open the
x86_x64 Cross Tools Command Prompt for VS 2017.
And then, you can start your compiling process.

Installation¶

Package not found in win-32 channel.¶

Solving environment: failed

PackagesNotFoundError: The following packages are not available from current channels:

- pytorch

Current channels:
- https://conda.anaconda.org/pytorch/win-32
- https://conda.anaconda.org/pytorch/noarch
- https://repo.continuum.io/pkgs/main/win-32
- https://repo.continuum.io/pkgs/main/noarch
- https://repo.continuum.io/pkgs/free/win-32
- https://repo.continuum.io/pkgs/free/noarch
- https://repo.continuum.io/pkgs/r/win-32
- https://repo.continuum.io/pkgs/r/noarch
- https://repo.continuum.io/pkgs/pro/win-32
- https://repo.continuum.io/pkgs/pro/noarch
- https://repo.continuum.io/pkgs/msys2/win-32
- https://repo.continuum.io/pkgs/msys2/noarch

PyTorch doesn’t work on 32-bit system. Please use Windows and
Python 64-bit version.

Import error¶

from torch._C import *

ImportError: DLL load failed: The specified module could not be found.

The problem is caused by the missing of the essential files. Actually,
we include almost all the essential files that PyTorch need for the conda
package except VC2017 redistributable and some mkl libraries.
You can resolve this by typing the following command.

conda install -c peterjc123 vc vs2017_runtime
conda install mkl_fft intel_openmp numpy mkl

As for the wheels package, since we didn’t pack some libraries and VS2017
redistributable files in, please make sure you install them manually.
The VS 2017 redistributable installer can be downloaded.
And you should also pay attention to your installation of Numpy. Make sure it
uses MKL instead of OpenBLAS. You may type in the following command.

pip install numpy mkl intel-openmp mkl_fft

Another possible cause may be you are using GPU version without NVIDIA
graphics cards. Please replace your GPU package with the CPU one.

from torch._C import *

ImportError: DLL load failed: The operating system cannot run %1.

This is actually an upstream issue of Anaconda. When you initialize your
environment with conda-forge channel, this issue will emerge. You may fix
the intel-openmp libraries through this command.

conda install -c defaults intel-openmp -f

Usage (multiprocessing)¶

Multiprocessing error without if-clause protection¶

RuntimeError:
       An attempt has been made to start a new process before the
       current process has finished its bootstrapping phase.

   This probably means that you are not using fork to start your
   child processes and you have forgotten to use the proper idiom
   in the main module:

       if __name__ == '__main__':
           freeze_support()
           ...

   The "freeze_support()" line can be omitted if the program
   is not going to be frozen to produce an executable.

The implementation of multiprocessing is different on Windows, which
uses spawn instead of fork. So we have to wrap the code with an
if-clause to protect the code from executing multiple times. Refactor
your code into the following structure.

import torch

def main()
    for i, data in enumerate(dataloader):
        # do something here

if __name__ == '__main__':
    main()

Multiprocessing error “Broken pipe”¶

ForkingPickler(file, protocol).dump(obj)

BrokenPipeError: [Errno 32] Broken pipe

This issue happens when the child process ends before the parent process
finishes sending data. There may be something wrong with your code. You
can debug your code by reducing the num_worker of
DataLoader to zero and see if the issue persists.

Multiprocessing error “driver shut down”¶

Couldn’t open shared file mapping: <torch_14808_1591070686>, error code: <1455> at torchlibTHTHAllocator.c:154

[windows] driver shut down

Please update your graphics driver. If this persists, this may be that your
graphics card is too old or the calculation is too heavy for your card. Please
update the TDR settings according to this post.

CUDA IPC operations¶

THCudaCheck FAIL file=torchcsrcgenericStorageSharing.cpp line=252 error=63 : OS call failed or operation not supported on this OS

They are not supported on Windows. Something like doing multiprocessing on CUDA
tensors cannot succeed, there are two alternatives for this.

1. Don’t use multiprocessing. Set the num_worker of
DataLoader to zero.

2. Share CPU tensors instead. Make sure your custom
DataSet returns CPU tensors.

0 / 0 / 0

Регистрация: 13.11.2019

Сообщений: 18

1

13.11.2019, 13:53. Показов 10653. Ответов 11


Подскажите почему возникают ошибки при установке?

стоит win7x64, python-3.7.4-amd64, pycharm-community-2018.3.7

модуль torch не устанавливается
либо пишет ошибка: ModuleNotFoundError: No module named ‘tools.nnwrap’

либо пишет:

pip3 install https://download.pytorch.org/w… _amd64.whl
^
SyntaxError: invalid syntax

стоит pip версии 10 и до 19 не обновляется

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



1302 / 842 / 409

Регистрация: 12.03.2018

Сообщений: 2,305

13.11.2019, 14:04

2

del



0



Автоматизируй это!

Эксперт Python

6375 / 4122 / 1133

Регистрация: 30.03.2015

Сообщений: 12,194

Записей в блоге: 29

13.11.2019, 14:20

3

Цитата
Сообщение от AnatolyT
Посмотреть сообщение

SyntaxError: invalid syntax

ты в консоли питона чтоли пишешь пип инсталл?)) скрин покажи где эта ошибка

опять 25 кстати — зачем какие то пип инсталл писать если можно нажать плюсик в настройках пайчарм и все установить как надо?



0



1283 / 668 / 365

Регистрация: 07.01.2019

Сообщений: 2,176

13.11.2019, 14:29

4



0



0 / 0 / 0

Регистрация: 13.11.2019

Сообщений: 18

13.11.2019, 15:28

 [ТС]

5

Цитата
Сообщение от Welemir1
Посмотреть сообщение

зачем какие то пип инсталл писать если можно нажать плюсик в настройках пайчарм и все установить как надо?

при установке в настройках пайчарм пишет ошибка: ModuleNotFoundError: No module named ‘tools.nnwrap’
через консоль :
pip3 install https://download.pytorch.org/w… _amd64.whl
^
SyntaxError: invalid syntax



0



1283 / 668 / 365

Регистрация: 07.01.2019

Сообщений: 2,176

13.11.2019, 15:32

6

Просто pip напишите



0



Автоматизируй это!

Эксперт Python

6375 / 4122 / 1133

Регистрация: 30.03.2015

Сообщений: 12,194

Записей в блоге: 29

13.11.2019, 15:40

7

AnatolyT, ты читаешь что я тебе пишу?
такая ошибка (SyntaxError: invalid syntax) означает что ты команду выполняешь в консоли ПИТОНА!!! а надо в консоли ОС!
разницу чувствуешь?

второе, повторяю — в пайчарм нужно через настройки добавлять либы, а ты не добавил (я уверен) потому и пишет что нот фоунд. Посмотри как добавлять виртуальную среду и библиотеки в Пайчарм!

Внимание, прочти, что я написал!



0



0 / 0 / 0

Регистрация: 13.11.2019

Сообщений: 18

13.11.2019, 15:42

 [ТС]

8

Миниатюры

Не устанавливается Pytorch
 



0



1302 / 842 / 409

Регистрация: 12.03.2018

Сообщений: 2,305

13.11.2019, 16:14

9

Цитата
Сообщение от AnatolyT
Посмотреть сообщение

через консоль :

через какую консоль?
Консоль python или все же терминал?

Просто на скрине вывод видно. Создается впечатление, что вы создали файл t1.py, в нем написали эту команду и выполнили его.



0



Автоматизируй это!

Эксперт Python

6375 / 4122 / 1133

Регистрация: 30.03.2015

Сообщений: 12,194

Записей в блоге: 29

13.11.2019, 16:42

10

AnatolyT, как выше сказали — похоже ты пип инсталл в файле скрипта написал, что делать не надо.
По установке — пора заглянуть в документацию питорча, нет ли там особенностей по установке на винду и 3 питон.



0



0 / 0 / 0

Регистрация: 13.11.2019

Сообщений: 18

13.11.2019, 16:53

 [ТС]

11

Цитата
Сообщение от ioprst
Посмотреть сообщение

через какую консоль?
Консоль python или все же терминал?
Просто на скрине вывод видно. Создается впечатление, что вы создали файл t1.py, в нем написали эту команду и выполнили его.

я делал пип инсталл и через терминал и через Python консоль
и там и там выдает : SyntaxError: invalid syntax



0



0 / 0 / 0

Регистрация: 13.11.2019

Сообщений: 18

14.11.2019, 13:34

 [ТС]

12

Оооох…я поставил)))
через cmd pip3 install https://download.pytorch.org/w… _amd64.whl
другая версия не ставится

потом torchvision также

но пайчарм не видел…в итоге пришлось искать папки torch в директиве не пайчарм а питона и копировать в пайчарм ручками…заработало)))

пы.сы. :нафига так все усложнять?



0



Pytorch is an Open source machine learning library that was developed by the Social Giant Facebook. You can do many things using it, like NLP, computer vision and deep learning, etc. But one thing you should be aware that its computations are similar to Numpy. The only difference is that Pytorch uses GPU for computation and Numpy uses CPU. This makes it fast. Most beginners are unable to properly install Pytorch in Pycharm In this tutorial on “How to”  you will know how to install Pytorch in Pycharm. Just follow the simple steps for the proper installation of the Pytorch.

When you write import torch then you will see an error like the figure below (Red underline). It means Pytorch is not installed in Pycharm and you will get the error No module named torch when your run the code. So you have to install this module. Follow the below steps for installing it.

pytorch installation error

Step 1: Click on Setting and click on Project: Your Project Name

Go to File>>Setting and click on Project: Your_project_name. There you will see two options. Project Interpreter and Project Structure.

pytorch project interpreter window

Step 2: Click on the Project Interpreter. There you will see all the installed packages. Pytorch is not there let’s install it.

project interpreter window

Step 3: Click on the “+” sign and search for the PyTorch. You will see it, and its description on the right side. Select it and click on Install Package.  This will install the Package. If an error comes then try to search for the torch and install it otherwise it is successfully installed.

If you are seeing an error like this “Error occurred when installing Package Pytorch“. Then you should install Pytorch through Pycharm Terminal.

Go to the Pyrcharm terminal and write the command

pip3 install https://download.pytorch.org/whl/cpu/torch-1.0.1-cp37-cp37m-win_amd64.whl

pytorch terminal installation

That’s all you have to do for installing Pytorch in Pycharm.

How to test or check if Pytorch is installed or not?

After installing the Pytorch, you can easily check its version. Just use the following code.

import torch as t
print(t.__version__)

You will see the version info.

torch version check

Other Questions Asked by the Reader

Q 1: I am getting errors like no module named torch. How to solve this issue?

No module named torch error is an import error. It generally occurs when you have not properly installed it in your system. To remove it you have to install it. If you are working on Pycharm then the above steps will solve these issues. Otherwise, you can install it manually.  You can use the pip command to install it. First, update your pip command using the following commands.

python -m pip install –upgrade pip

After that install Pytorch using the pip command

For python 3. xx

pip3 install torch

For python 2. xx

pip install torch

It will remove the no module named PyTorch error.

Q 2. error occurred when installing package pycharm

If you are getting errors while installing the package in pycharm then try to update or change the python version. Also, update pycharm and the pip package. Then after installing the torch package. It will successfully install the package.

Similar Articles :

How to Install Scikit Learn in Pycharm ? Only 5 Steps

How to Install Pandas in Pycharm? : Only 4 Steps

How to Install Scrapy in Pycharm : Install it in 5 Steps Only

Join our list

Subscribe to our mailing list and get interesting stuff and updates to your email inbox.

We respect your privacy and take protecting it seriously

Thank you for signup. A Confirmation Email has been sent to your Email Address.

Something went wrong.

#python #cmd #pytorch

#питон #cmd #пыторч

Вопрос:

Я пытаюсь установить PyTorch в cmd, чтобы импортировать его в проект pycharm. это дает мне многочисленные ошибки после запуска setup.py установка для PyTorch … ошибка.

 ERROR: Command errored out with exit status 1:
     command: 'c:userssarahappdatalocalprogramspythonpython38python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:UserssarahAppDataLocalTemppip-install-uejad0d4pytorch_87cb825d32c24f6ca6f350ea09c367a4setup.py'"'"'; __file__='"'"'C:UserssarahAppDataLocalTemppip-install-uejad0d4pytorch_87cb825d32c24f6ca6f350ea09c367a4setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'rn'"'"', '"'"'n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record 'C:UserssarahAppDataLocalTemppip-record-k6l1ba85install-record.txt' --single-version-externally-managed --user --prefix= --compile --install-headers 'C:UserssarahAppDataRoamingPythonPython38IncludePyTorch'
         cwd: C:UserssarahAppDataLocalTemppip-install-uejad0d4pytorch_87cb825d32c24f6ca6f350ea09c367a4
    Complete output (5 lines):
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "C:UserssarahAppDataLocalTemppip-install-uejad0d4pytorch_87cb825d32c24f6ca6f350ea09c367a4setup.py", line 11, in <module>
        raise Exception(message)
    Exception: You tried to install "pytorch". The package named for PyTorch is "torch"
    ----------------------------------------
ERROR: Command errored out with exit status 1: 'c:userssarahappdatalocalprogramspythonpython38python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:UserssarahAppDataLocalTemppip-install-uejad0d4pytorch_87cb825d32c24f6ca6f350ea09c367a4setup.py'"'"'; __file__='"'"'C:UserssarahAppDataLocalTemppip-install-uejad0d4pytorch_87cb825d32c24f6ca6f350ea09c367a4setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'rn'"'"', '"'"'n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record 'C:UserssarahAppDataLocalTemppip-record-k6l1ba85install-record.txt' --single-version-externally-managed --user --prefix= --compile --install-headers 'C:UserssarahAppDataRoamingPythonPython38IncludePyTorch' Check the logs for full command output.
 

Ответ №1:

Лучший способ установить PyTorch — использовать pip или conda с командами, представленными на их веб-сайте: https://pytorch.org /

Таким образом, вы можете выбрать, какую ОС вы используете, какую версию CUDA (или без CUDA), и используете ли вы conda или pip.

Пожалуйста, обратите внимание, что с сегодняшнего дня (14.12/20) я попытался установить PyTorch в новой среде, и это не удалось из-за новой версии Numpy. Я решил эту проблему, сначала установив Numpy:

 pip install numpy==1.18
 

А затем PyTorch, как обычно, с их веб-сайта. Обратите внимание, что их команда pip install указывает torch как имя пакета, а не pytorch , которое вы, похоже, использовали.

Комментарии:

1. Что вы подразумеваете под » он включает torch, а не pytorch «?

2. В исходном комментарии пользователь получил: Exception: You tried to install "pytorch". The package named for PyTorch is "torch" . Это то, что я имел в виду. Я отредактирую свой ответ.

Проблемы, возникшие при установке pytorch

Чтобы выучить пиорч, установите пиорч дома по электронной книге на зимних каникулах.
Однако, поскольку скорость Интернета дома слишком низкая, пакет не может быть загружен, что не приводит к прогрессу в обучении.
В этот период я ​​попробовал образ Цинхуа, но установка не удалась.
Путем непрерывных попыток я наконец нашел два локальных метода установки для успешной установки pytorch, поэтому я открыл сообщение, чтобы записать этот метод, и я надеюсь, что он поможет вам столкнуться с той же сетью. Спросите друзей.

Ошибка загрузки из-за низкой скорости интернета:


После нескольких попыток:

Решение:

1. Используйте адрес на рисунке 1, чтобы вручную загрузить пакет pytorch.

Обратите внимание, что вы должны выбрать в соответствии с загруженной версией anaconda, версией python и версией cuda.
После загрузки войдите в базовую среду и используйте метод локальной установки:

conda install D:pytorch-1.4.0-py3.7_cuda101_cudnn7_0.tar.bz2

Ниже приведены версия и путь, который я скачал.
Вам нужно знать свой адрес, а затем открыть свойства, чтобы скопировать имя сжатого пакета,Не пропустите суффикс .bz2
Я рекомендую этот метод локальной установки.
Но это только пакет pytorch, будут другие пакеты, которые вам нужно будет загрузить вручную во время глубокого обучения.

2. Установить через pip

Найдено на pytorch.org
Ниже представлен веб-сайт пакета
После нажатия кнопки «Открыть» найдите версию pytorch и версию torchvision, соответствующие вашей версии python и cuda, для загрузки.
После загрузки запустите его прямо в базовой среде:

pip install D:torch-1.4.0-cp38-cp38-win_amd64.whl

Так что его можно установить
Torchvision использует тот же метод

0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Pythonw exe ошибка при запуске приложения 0xc000007b
  • Python стандартная ошибка среднего