PyTorch 官网已经有很详细的安装方法:https://pytorch.org/
但是,下载的速度很慢,这里使用了清华源安装。
1、查看自己电脑安装的cuda版本
打开终端(ctrl+alt+t)输入:
nvcc -V
2、打开终端,使用 conda 安装
安装前需要添加清华源
# 添加清华源的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/
conda install pytorch torchvision cudatoolkit=10.0 # 删除安装命令最后的 -c pytorch,才会采用清华源安装。
3、安装完成后,测试torch和CUDA
1)为了确保PyTorch安装正确,我们可以运行示例PyTorch代码来验证安装。这里我们将构造一个随机初始化的张量。
from __future__ import print_function
import torch
x = torch.rand(5, 3)
print(x)
# The output should be something similar to:
# tensor([[0.2989, 0.2493, 0.2642],
# [0.9508, 0.4811, 0.1085],
# [0.5423, 0.3216, 0.3068],
# [0.8863, 0.8385, 0.5150],
# [0.8451, 0.4620, 0.6266]])
如下图所示:
2)此外,要检查GPU驱动程序和CUDA是否能够被PyTorch启用和访问,需要运行以下命令以返回CUDA驱动程序是否已启用:
import torch
torch.cuda.is_available()
# the output is: True
如下图所示:
最后,大功告成!