天天看点

〖Pytorch笔记0〗Ubuntu16.04系统Anaconda下安装Pytorch(基于conda或pip)

目录

         一. 基于conda安装

1.1. 修改conda镜像源

1.2 conda安装Pytorch下载过慢解决办法

1.3. 安装Pytorch

二. 基于pip文件安装

2.1. 配置镜像源

2.2. 下载.whl安装文件

2.3. 安装pytorch

2.4. 测试

三. Pytorch能做什么?

3.1. GPU加速

3.2. 自动求导

3.3. 常用网络层

一. 基于conda安装

  • 我们在Ubuntu下用pip或者conda安装软件包都容易龟速最终导致失败,但是嗑盐的我们耽误不起时间,所以要找一个最好最快的安装的方式,以下我介绍基于conda和pip的两种安装方式,先保证电脑里已经安装好了Anaconda。

1.1. 修改conda镜像源

  • 在一个Anconda环境中创建一个pytorch环境,用于在里面安装所需要的包,
[email protected]:~$ conda create -n pytorch python=3.6
           
  • 有不理解的可以参考我之前的文档:linux笔记:使用conda命令管理包、管理环境详细讲解_布衣小张-CSDN博客;在终端中运行以下命令修改镜像源,可以明显加速安装,使用清华conda镜像。
conda config --prepend 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
           
注意:更新2019-07-06,由于清华源已经封闭,可以使用国科大。
# 或者使用国科大镜像源
conda config --prepend channels https://mirrors.ustc.edu.cn/anaconda/pkgs/main/
conda config --prepend channels https://mirrors.ustc.edu.cn/anaconda/pkgs/free/
conda config --set show_channel_urls yes
           
注意:更新2019-10-01,清华源已经可以继续使用。 
  • 要查看镜像源是否安装成功的话,建议终端中运行以下命令:
[email protected]:~$ conda config --set show_channel_urls yes
           
  • 会生成一个~/.condarc文件,运行cat命令查看文件内容。
(pytorch) [email protected]:~$ cat ~/.condarc
#会显示如下:
channels:
  - https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/free/
  - https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud/pytorch/
  - https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud/conda-forge/
  - https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud/msys2/
  - https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main/
  - defaults
show_channel_urls: true
report_errors: true
           
  • 这样每次用conda安装时,在package右边都会显示安装源的地址,那么我们对于安装的时间能有一个大致的估计。修改后,用conda安装镜像源中任何库都能明显加速,在我的电脑上安装速度级可以达到MB/s 

1.2 conda安装Pytorch下载过慢解决办法

  • 当使用conda安装的时候,可能会遇到下载过慢的问题,下载的时候可能会遇到无尽的等待。这里推荐用清华源替代默认conda源的方法,可以解决下载过慢的问题。
  • 添加清华源
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源:
conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud/conda-forge/
conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud/msys2/
conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud/bioconda/
conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud/menpo/
conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud/pytorch/
           
  •  根据Python和CUDA选择对应的版本,然后官方给出提示可通过运行:
〖Pytorch笔记0〗Ubuntu16.04系统Anaconda下安装Pytorch(基于conda或pip)
  • 但是这里一定要注意,去掉-c pytorch,安装的时候才会默认从清华源下载相应的包,因此这里用命令行
conda install pytorch torchvision cudatoolkit=10.0
           

1.3. 安装Pytorch

〖Pytorch笔记0〗Ubuntu16.04系统Anaconda下安装Pytorch(基于conda或pip)
〖Pytorch笔记0〗Ubuntu16.04系统Anaconda下安装Pytorch(基于conda或pip)
  • 我安装的方法是conda+python3.6+cuda8.0,所以安装命令如下:(根据PyTorch选择适合自己的)
zhangkf@Ubuntu2:~$ conda install pytorch torchvision cuda80 -c pytorch
           

二. 基于pip文件安装

  • 2020-06-19:参考链接:Ubuntu16.04+Pytorch1.4.0+cuda10.0的pip安装
# 当直接按照PyTorch官网安装时,
pip install torch===1.5.0 torchvision===0.6.0 -f https://download.pytorch.org/whl/torch_stable.html
pip install torch===1.4.0 torchvision===0.5.0 -f https://download.pytorch.org/whl/torch_stable.html

# 输入:
python -c "import torch; print(torch.version.cuda)"

# 输出:
10.1

# 输入:nvcc -V

# 输出:
10.0

# 所以,此时pytorch的cuda版本和系统的cuda版本是不匹配的。解决方法:
pip install torch===1.4.0+cu100 torchvision===0.5.0+cu100 -f https://download.pytorch.org/whl/torch_stable.html
           
  • 查python解释器的位置
import sys
print(sys.executable)  #解释器
           
  • 2020-09-14:参考链接:PyTorch碎片:PyToch和Torchvision对应版本
  • 有时候基于conda安装pytorch,下载速度会非常的慢,这个时候可以考虑用这个方法,也是很简单的。首先创建一个环境:
[email protected]:~$ conda create -n pytorch python=3.6
           
  • 创建完毕进入环境中:
[email protected]:~$ conda activate pytorch
           

2.1. 配置镜像源

  • 请参考博文Ubuntu16.10下配置pip国内镜像源加速安装. 这一步是为加速安装torch vision进行的。

2.2. 下载.whl安装文件

  • 可以按pytorch安装指南的网址Previous PyTorch Versions | PyTorch,选择适合自己的版本。我选择的是下面
  • Pytorch离线安装包链接1
  • Pytorch离线安装包链接2
  • 清华镜像下载pytorch安装包3,对应得方法:pytorch安装(在线与离线,推荐离线)
  • 2021年8月18日:https://download.pytorch.org/whl/torch_stable.html
  • 对应上面:CUDA10.2安装+pytorch1.7.1安装+torchvision0.8.2安装 + cudnn安装(深度学习GPU加速)_java_pythons的博客-CSDN博客
〖Pytorch笔记0〗Ubuntu16.04系统Anaconda下安装Pytorch(基于conda或pip)
  • pip install -U -r requirements.txt
               
# pip install -r requirements.txt

# base ----------------------------------------
Cython
matplotlib>=3.2.2
numpy>=1.18.5
opencv-python>=4.1.2
pillow
PyYAML>=5.3
scipy>=1.4.1
tensorboard>=2.2
torch>=1.6.0
torchvision>=0.7.0
tqdm>=4.41.0

# coco ----------------------------------------
# pycocotools>=2.0

# export --------------------------------------
# packaging  # for coremltools
# coremltools==4.0b3
# onnx>=1.7.0
# scikit-learn==0.19.2  # for coreml quantization

# extras --------------------------------------
# thop  # FLOPS computation
# seaborn  # plotting
           

2.3. 安装pytorch

  • 把下载好的文件传输到服务器中,进入刚刚创建好环境,用pip install .whl文件即可。
(pytorch) [email protected]:~$ pip install torch-0.3.0.post4-cp27-cp27mu-linux_x86_64.whl
(pytorch) [email protected]:~$ pip install torch vision
           
  • 有了镜像加持和.whl文件的本地化,安装很顺利 ,torch vision安装非常迅速。

2.4. 测试

  • 在终端中按以下顺序运行命令python。
(second) [email protected]:~/code$ ipython
Python 3.7.6 | packaged by conda-forge | (default, Mar 23 2020, 23:03:20) 
Type 'copyright', 'credits' or 'license' for more information
IPython 7.14.0 -- An enhanced Interactive Python. Type '?' for help.

In [1]: import torch                                                                          

In [2]: torch.cuda.is_available()                                                             
Out[2]: True

In [3]:  
 
           
  • 上面显示true就是安装成功。
注意:安装过程中如果遇到这样的问题,安装过程中出错: Could not import setuptools ,或者 Failed building wheel for pyyaml,问题简写了,看看有没有这几个关键词。有的话的请参考我的文章:问题会得到解决,安装过程中不报错的话即代表安装成功,然后开始入坑吧.祝你好运。『linux笔记』pip 安装keras,pytorch出错: Could not import setuptools ,Failed building wheel for pyyaml_布衣小张-CSDN博客。

三. Pytorch能做什么?

  • 动态图:计算的进行和代码的运行是同时的。
  • 静态图:先构建函数,之后便不能更改,只能喂数据。好处:一次成型,一旦建好之后使用起来非常方便,不需要自己中间修改。问题:比如TensorFlow自建了一套命名体系,中间的所有变量和时序的控制逻辑都是使用自己的,用Python写的时候就非常麻烦,所以TensorFlow2.0支持动态图优先。

3.1. GPU加速

  • 代码如下
import 	torch
import  time
print(torch.__version__)
print(torch.cuda.is_available())

# print('hello, world.')

a = torch.randn(10000, 1000)
b = torch.randn(1000, 2000)

t0 = time.time()
c = torch.matmul(a, b)
t1 = time.time()
print(a.device, t1 - t0, c.norm(2))

device = torch.device('cuda')
a = a.to(device)
b = b.to(device)

t0 = time.time()
c = torch.matmul(a, b)
t2 = time.time()
print(a.device, t2 - t0, c.norm(2))

t0 = time.time()
c = torch.matmul(a, b)
t2 = time.time()
print(a.device, t2 - t0, c.norm(2))
           
  • 运行结果
1.0.1.post2
True
cpu 0.06677007675170898 tensor(141467.7188)
cuda:0 0.002493143081665039 tensor(141467.7188, device='cuda:0')
cuda:0 0.0007426738739013672 tensor(141467.7188, device='cuda:0')
           

3.2. 自动求导

  • 自动求导,对神经网络中的weight更新时非常方便
  • 求下面这个函数在x=1处对a,b,c的导数!
〖Pytorch笔记0〗Ubuntu16.04系统Anaconda下安装Pytorch(基于conda或pip)
  • 代码
import  torch
from    torch import autograd

x = torch.tensor(1.)
a = torch.tensor(1., requires_grad=True) # 后面这一部分告诉Pytorch对a进行求导
b = torch.tensor(2., requires_grad=True)
c = torch.tensor(3., requires_grad=True)

y = a**2 * x + b * x + c

print('before:', a.grad, b.grad, c.grad)
grads = autograd.grad(y, [a, b, c])
print('after :', grads[0], grads[1], grads[2])
           
  • 运行结果
before: None None None
after : tensor(2.) tensor(1.) tensor(1.)
           

3.3. 常用网络层

  • pytorch中封装了大量的神经网络需要的运算以及程序结构的一些接口。
〖Pytorch笔记0〗Ubuntu16.04系统Anaconda下安装Pytorch(基于conda或pip)
  • 部分参考了作者:Ubuntu16.04下Pytorch安装(基于conda或pip)_yucicheung的博客-CSDN博客