- 一.发展
- 二.同类框架
- PyTorch和TensorFlow区别
- 1.动态图
- 2.静态图
- 3.总结
- 三.PyTorch简单功能
- 1.GPU加速
- 2.自动求导
- 3.常用网络层
2002年Torch
2011年Torch7
2016.10发布PyTorch0.1,THNN后端
2018.12发布1.0,CAFFE2后端
2019.5发布1.1
Google:keras,TensorFlow
Amazon:MXNet
Facebook:Caffe2,PyTorch
类似于人的思维模式,每次直接用具体的值进行计算并得到结果。
PyTorch是动态图。
就像先定义一个公式,每次我们都会重新给定一个具体值,运行时会代入公式计算结果,创建公式和运行两段分离,静态体现在公式创建好后是不能更改的。
TensorFlow1是静态图,TensorFlow2是动态图和静态图结合。
作为研究人员或者新手人员,推荐PyTorch,使用简单,把更多精力放在算法上。
作为工程师,推荐TensorFLow2,工业布局更好。
import torch
import time
print(torch.torch_version)
print(torch.cuda.is_available())
#两个矩阵
a = torch.randn(10000,1000)
b = torch.randn(1000,2000)
#使用cpu计算矩阵的乘法,并记录计算时间0
t0 = time.time()
c = torch.matmul(a,b)
t1 = time.time()
print(a.device,t1-t0,c.norm(2))
#使用GPU计算
device = torch.device('cuda')
a = a.to(device)
b = b.to(device)
t0 = time.time()
c = torch.matmul(a,b)
t1 = time.time()
print(a.device,t1-t0,c.norm(2))
#再计算一遍验证结果
t0 = time.time()
c = torch.matmul(a,b)
t1 = time.time()
print(a.device,t1-t0,c.norm(2))
采用CPU运行时间是 0.1456127166748047,采用GPU第一次运行时间是0.38901543617248535,比CPU还大,是因为第一次采用CUDA时会初始化环境,这个时间是不准确的计算时间,第二次可能是因为计算过快,直接显示0。
把矩阵变大一点:
a = torch.randn(10000,1000) b = torch.randn(1000,8000)
结果为:
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])
对于该公式y,对a求偏导得2ax,对b求偏导得x,对c求偏导得1.
3.常用网络层nn.Linear
nn.Conv2d
nn.LSTM
nn.ReLU
nn.Sigmod
nn.Softmax
nn.CrossEntropyLoss
nn.MSE



