复习了下pytorch。
自动求导机制
从后向排除子图
自动求导如何编码历史信息
Variable上的In-place操作
In-place正确性检查
CUDA语义
cuda
最佳实践
扩展PyTorch
扩展torch.autograd
扩展 torch.nn
多进程最佳实践
多进程
共享CUDA张量
最佳实践
序列化语义
保存模型的推荐方法
torch.save(the_model.state_dict().PATH) the_model = TheModelClass(*args,**kwargs) the_model.load_state_dict(torch.load(PATH))
torch.save(the_model, PATH)
the_model = torch.load(PATH)
CODE
1 import torchvision 2 from torch.autograd import Variable 3 import torch 4 5 #requires_grad 6 x = Variable(torch.randn(5, 5)) 7 y = Variable(torch.randn(5, 5)) 8 z = Variable(torch.randn(5, 5),requires_grad=True) 9 a = x + y 10 print(a.requires_grad) #False 11 b = a + z 12 print(b.requires_grad) #True 13 14 15 #volatile 16 regular_input = Variable(torch.randn(5,5)) 17 volaile_input = Variable(torch.randn(5,5),volatile = True) 18 model = torchvision.models.resnet18(pretrained = True) 19 print(model(regular_input).requires_grad) #True 20 print(model(volaile_input).requires_grad) #False 21 print(model(volaile_input).volatile) #True 22 print(model(volaile_input).requires_grad) #False 23 24 #cuda 25 x = torch.cuda.FloatTensor(1) 26 # x.get_device() == 0 27 y = torch.FloatTensor(1).cuda() 28 # y.get_device() == 0 29 30 with torch.cuda.device(1): 31 #当前分配给GPU1 32 a = torch.cuda.FloatTensor(1) 33 34 b = torch.FloatTensor(1).cuda() 35 36 c = a + b 37 # c.get_device() == 1 38 z = x + y 39 # z.get_device() == 0 40 d = torch.randn(2).cuda(2) 41 #d.get_device() == 2
常用包
torch
torch:张量相关的运算,包括创建,索引,切片,连接,换位,随机抽样,序列化,并行化,数学操作等
torch.nn:包含搭建网络层的模块和一系列的损失函数(卷积,池化,BN批处理,Linear , Dropout等)
torch.nn.functional:激活函数(线性,Dropout,,relu,leaky_relu,sigmoid等)
torch.autograd:提供了类和函数用来对任意标量函数进行求导
torch.optim:各种优化算法(SGD,Adam,Adagrad等)
torch.nn.init:更改模块参数初始化方式
torch.utils.data:加载数据
torch.Tensor:一种包含单一数据类型元素的多维矩阵
torch.Storage:一个单一数据类型的连续一维数组
torchvision
torchvision.datasets: 中包含了以下数据集
torchvision.models:包含以下模型结构
torchvision.transforms:PIL.Image相关
torchvision.utils:将给定的Tensor保存成image文件
原文:https://www.cnblogs.com/Asumi/p/12466556.html