• torch detach()与.data


    转自:https://blog.csdn.net/DreamHome_S/article/details/85259533

    1.区别

    • .data 返回和 x 的相同数据 tensor, 但不会加入到x的计算历史里,且require s_grad = False,这样有些时候是不安全的, 因为 x.data 不能被 autograd 追踪求微分 。
    • .detach() 返回相同数据的 tensor ,且 requires_grad=False ,但能通过 in-place 操作报告给 autograd 在进行反向传播的时候。

    2.例子

    .data

    >>> a = torch.tensor([1,2,3.], requires_grad =True)
    >>> out = a.sigmoid()
    >>> c = out.data
    >>> c.zero_()
    tensor([ 0., 0., 0.])
    
    >>> out                   #  out的数值被c.zero_()修改
    tensor([ 0., 0., 0.])
    
    >>> out.sum().backward()  #  反向传播
    >>> a.grad                #  这个结果很严重的错误,因为out已经改变了
    tensor([ 0., 0., 0.])

    .detach()

    >>> a = torch.tensor([1,2,3.], requires_grad =True)
    >>> out = a.sigmoid()
    >>> c = out.detach()
    >>> c.zero_()
    tensor([ 0., 0., 0.])
    
    >>> out                   #  out的值被c.zero_()修改 !!
    tensor([ 0., 0., 0.])
    
    >>> out.sum().backward()  #  需要原来out得值,但是已经被c.zero_()覆盖了,结果报错
    RuntimeError: one of the variables needed for gradient
    computation has been modified by an

    综上,区别是修改后再使用是否会提示报错。

  • 相关阅读:
    CCF 201712-4 90分
    hdu2159
    ch11 持有对象
    ch7复用类
    PLSQL Developer 9注册码
    vue + typespript + webpack
    JavaScript 复制内容到剪贴板
    在不同电脑设备之间, 同步 VSCode 的插件和配置
    常用正则:提取内容, 格式化数字
    js css3 固定点拖拽旋转
  • 原文地址:https://www.cnblogs.com/BlueBlueSea/p/14989523.html
Copyright © 2020-2023  润新知