一. 写在前面
笔者在安装PyTorch前已经安装了Anaconda,为了方便,故将PyTorch安装至Anaconda中。
总体的安装思路是:利用Anaconda Powershell Prompt (类似cmd),通过清华镜像网站,安装适合自己电脑的PyTorch版本。
二. 安装流程
第一步:打开Anaconda Powershell Prompt (以win10为例,在按下屏幕左下角windows键后,找到A开头的Anaconda文件夹,里面有Anaconda Powershell Prompt ,单击打开)
第二步:依次输入四行代码,将PyTorch下载网址首选改为清华镜像网站。代码如下:
conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/free/
conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main/
conda config --set show_channel_urls yes
conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud/pytorch/win-64/
第三步:在PyTorch官网上找到适合自己的版本后,并在Anaconda Powershell Prompt中输入一行代码开始安装
Pytorch官网:https://pytorch.org/
进入官网后,点击“Get Started”,在选择自己的版本号(包括显卡型号)后,在“Run this Command:”行中会出现一行代码,以笔者为例:conda install pytorch torchvision cudatoolkit=10.2 -c pytorch
去掉代码尾部 -c pytorch, 复制代码剩余部分,粘贴至Anaconda Powershell Prompt并运行
第四步(此步非必须):如果提示conda版本需要更新,则在Proceed ([y]/n)? 后输入y,继续运行即可
三. 示例(Prompt中的可能情形)
(base) PS C:\Users\25062> conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/free/
Warning: 'https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/free/' already in 'channels' list, moving to the top
(base) PS C:\Users\25062> conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main/
Warning: 'https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main/' already in 'channels' list, moving to the top
(base) PS C:\Users\25062> conda config --set show_channel_urls yes
(base) PS C:\Users\25062> conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud/pytorch/win-64/
Warning: 'https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud/pytorch/win-64/' already in 'channels' list, moving to the top
(base) PS C:\Users\25062> conda install pytorch torchvision cudatoolkit=10.2
Collecting package metadata (current_repodata.json): done
Solving environment: done
==> WARNING: A newer version of conda exists. <==
current version: 4.8.2
latest version: 4.8.5
Please update conda by running
$ conda update -n base -c defaults conda
## Package Plan ##
environment location: D:\Anaconda\Anaconda
added / updated specs:
- cudatoolkit=10.2
- pytorch
- torchvision
The following NEW packages will be INSTALLED:
cudatoolkit anaconda/pkgs/main/win-64::cudatoolkit-10.2.89-h74a9793_1
ninja anaconda/pkgs/main/win-64::ninja-1.10.1-py37h7ef1ec2_0
pytorch anaconda/cloud/pytorch/win-64::pytorch-1.6.0-py3.7_cuda102_cudnn7_0
torchvision anaconda/cloud/pytorch/win-64::torchvision-0.7.0-py37_cu102
The following packages will be UPDATED:
conda pkgs/main::conda-4.8.2-py37_0 --> anaconda/pkgs/main::conda-4.8.5-py37_0
Proceed ([y]/n)? y
Preparing transaction: done
Verifying transaction: done
Executing transaction: done
四. 检查是否安装成功
打开IDE,以PyCharm为例,在setting中可以查看项目所使用的interpreter中是否包含PyTorch的包。
或者更简单的方式,输入import torch查看是否报错。
如果由于曾经安装失败导致此次安装继续失败,则可以查看本地Anaconda文件夹pkgs目录下是否存在pytorch文件夹(以笔者为例,该文件夹名为pytorch-1.6.0-py3.7_cuda102_cudnn7_0)。若其存在,则删除之,重新安装。