PyTorch 概览
深度学习库的优势
参考教程:https://www.bilibili.com/video/BV1Rv411y7oE
- 提供 GPU 加速;
- 自动求导;
- 常用 API
Tensor 运算
- Torch.add
- Torch.mul
- Torch.matmul
- Torch.view
- Torch.expand
- Torch.cat
- ...
神经网络
对不同层数有不同的接口
- Nn.Linear 全连接层
- Nn.ReLU 激活函数
- Nn.Conv2d 2d卷积操作
- Nn.Softmax
- Nn.Sigmoid 激活函数
- Nn.CrossEntropyLoss 交叉熵损失计算函数
- ...
测试运行时间
import torch
import time
print(torch.__version__)
print(torch.cuda.is_available())
a = torch.randn(10000, 1000)
b = torch.randn(1000, 2000)
t0 = time.time()
c = torch.matual(a,b)
print(time.time() - t0)
print(a.device, c.norm(2))
device = torch.device('cuda')
a = a.to(device)
b = b.to(device)
t1 = time.time()
c = torch.matual(a,b)
# 第一次运行会进行环境的初始化,时间反而比 CPU 长;再次运行就会比较准确的反应运算时间
print(time.time() - t1)
print(a.device, c.norm(2))
t2 = time.time()
c = torch.matual(a,b)
print(time.time() - t2)
print(a.device, c.norm(2))
测试求导
import torch
from torch import autograd
x = torch.tensor(1.)
a = torch.tensor(1.,requires_grad = True)
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.)
'''
神经网络结构再深,也是一系列函数的嵌套;因此可以使用 pytorch 对输出的 loss,对中间的每一个 weight 求导,这样进行更新的时候很方便。
相关资料
-
PyTorch官方教程中文版
http://www.pytorch123.com -
PyTorch Tutorial for Deep Learning Researchers
https://github.com/yunjey/pytorch-tutorial -
知乎:新手如何入门pytorch?
https://www.zhihu.com/question/55720139 -
PyTorch学这个就够了!
https://www.bilibili.com/video/BV1Rv411y7oE
教程相关笔记:
https://github.com/tsuirak/skills/tree/master/Pytorch/Pytorch_learn_by_dragen1860