与Tensorflow的静态计算图不同,pytorch的计算图是动态的,可以根据计算需要实时改变计算图
基于python,具备GPU加速的张量和动态神经网络深度学习框架。
安装
按照官网指示,https://pytorch.org
python 3.6 cpu 稳定版
pip3 install http://download.pytorch.org/whl/cpu/torch-0.4.1-cp36-cp36m-linux_x86_64.whl
pip3 install torchvision
—可以换个有gpu的服务器么。。。
教程
官方教程
Pytorch张量运算
100多种,包括转置,数学运算,线性代数,索引切分 https://pytorch.org/docs/stable/torch.html
Tensor创建:
1 | # torch.tensor(data) creates a torch.Tensor object with the given data. |
concatenation运算
1 | # By default, it concatenates along the first axis (concatenates rows) |
Reshaping Tensors
1 | x = torch.randn(2, 3, 4) # 2*3*4的随机tensor |
Torch Tensor与 NumPy array的互相转换
Converting a Torch Tensor to a NumPy array
1 | from __future__ import print_function |
Converting NumPy Array to Torch Tensor
1 | import numpy as np |
autograd 自动求导
原理
1 | # Tensor factory methods have a ``requires_grad`` flag |
脱离自动求导的方法
z.detach()
该命令将z从计算历史中分离出来。
returns a tensor that shares the same storage as z, but with the computation history forgotten. It doesn’t know anything
about how it was computed.
with torch.no_grad()
将需要停止自动求导的代码库放置于with torch.no_grad() 范围内
1 | print(x.requires_grad) #True |
Neural networks
Training a Classifier
先使用python包将数据导入成numpy array
- images: Pillow, OpenCV
- audio: scipy and librosa
- text: NLTK and SpaCy
torchvision包提供了计算机视觉领域 Imagenet, CIFAR10, MNIST等数据集的数据入口。
torchvision.datasets
torch.utils.data.DataLoader