首页 > 其他 > 详细

torch 的包应用

时间:2020-02-10 20:56:52      阅读:189      评论:0      收藏:0      [点我收藏+]

1.torchvision.transforms是pytorch中的图像预处理包一般用Compose把多个步骤整合到一起,比如说

    transforms.Compose([transforms.CenterCrop(10),
                                        transforms.ToTensor(),])

2.transforms中的函数

    Resize:把给定的图片resize到given size;
    Normalize:Normalized an tensor image with mean and standard deviation;
    ToTensor:convert a PIL image to tensor (H*W*C) in range [0,255] to a torch.Tensor(C*H*W) in the range [0.0,1.0];
    ToPILImage: convert a tensor to PIL imageScale:目前已经不用了,推荐用ResizeCenterCrop;
    ResizeCenterCrop:在图片的中间区域进行裁剪;
    RandomCrop:在一个随机的位置进行裁剪;
    RandomHorizontalFlip:以0.5的概率水平翻转给定的PIL图像;
    RandomVerticalFlip:以0.5的概率竖直翻转给定的PIL图像;
    RandomResizedCrop:将PIL图像裁剪成任意大小和纵横比;
    Grayscale:将图像转换为灰度图像;
    RandomGrayscale:将图像以一定的概率转换为灰度图像;
    FiceCrop:把图像裁剪为四个角和一个中心T;
    enCropPad:填充ColorJitter:随机改变图像的亮度对比度和饱和度

detach()

 当我们再训练网络的时候可能希望保持一部分的网络参数不变,只对其中一部分的参数进行调整;或者值训练部分分支网络,并不让其梯度对主网络的梯度造成影响,

 这时候我们就需要使用detach()函数来切断一些分支的反向传播

 detach()[source]
返回一个新的Variable,从当前计算图中分离下来的,但是仍指向原变量的存放位置,不同之处只是requires_grad为false,得到的这个Variable永远不需要计算其梯度,不具有grad

即使之后重新将它的requires_grad置为true,它也不会具有梯度grad

这样我们就会继续使用这个新的Variable进行计算,后面当我们进行反向传播时,到该调用detach()的Variable就会停止,不能再继续向前进行传播

 

import torch
a = torch.tensor([1,2,3.],requires_grad=True)#3后面一定有个.
print(a.grad)
out = a.sigmoid()
out.sum().backward()
print(a.grad)

None
tensor([0.1966, 0.1050, 0.0452])


import torch
a = torch.tensor([1,2,3.],requires_grad=True)#3后面一定有个.
print(a.grad)
out = a.sigmoid()
print(out)
#添加detach(),c的require_grad=False
c = out.detach()
print(c)#没有梯度
#没有对c更改,并不影响backward()
out.sum().backward()
print(a.grad)
#使用新生成的Variable进行反向传播
c.sum().backward()
print(a.grad)

None
tensor([0.7311, 0.8808, 0.9526], grad_fn=<SigmoidBackward>)
tensor([0.7311, 0.8808, 0.9526])
tensor([0.1966, 0.1050, 0.0452])

RuntimeError: element 0 of tensors does not require grad and does not have a grad_fn


import torch
a = torch.tensor([1,2,3.],requires_grad=True)#3后面一定有个.
print(a.grad)
out = a.sigmoid()
print(out)
#添加detach(),c的require_grad=False
c = out.detach()
print(c)#没有梯度
c.zero_()
print(c)
print(out)#修改c的同时影响out的值
#没有对c更改,并不影响backward()
out.sum().backward()
print(a.grad)

None
tensor([0.7311, 0.8808, 0.9526], grad_fn=<SigmoidBackward>)
tensor([0.7311, 0.8808, 0.9526])
tensor([0., 0., 0.])
tensor([0., 0., 0.], grad_fn=<SigmoidBackward>)但是还有梯度

RuntimeError: one of the variables needed for gradient computation has been modified by an inplace operation: [torch.FloatTensor [3]], which is output 0 of SigmoidBackward, is at version 1; expected version 0 instead. Hint: enable anomaly detection to find the operation that failed to compute its gradient, with torch.autograd.set_detect_anomaly(True).

 

torch 的包应用

原文:https://www.cnblogs.com/tingtin/p/12286820.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!