zoukankan      html  css  js  c++  java
  • 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

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

  • 相关阅读:
    8月15日
    【k8s】创建 tls 类型 Secret
    使用 openssl 生成 CA 证书
    【k8s】跨 Namespace 使用 Ingress
    Windows 和 Centos 导入 CA 证书
    使用 openssl 生成服务器证书
    【k8s】nginx ingress 配置 https
    【k8s】通过 https 访问 dashboard
    1012day人口普查系统
    8.3日志
  • 原文地址:https://www.cnblogs.com/BlueBlueSea/p/14989523.html
Copyright © 2011-2022 走看看