起因
今天被PyTroch tensor的requires_grad搞了一把。具体情况是创建一个tensor和在后续的使用过程中,对requires_grad的取值会影响到python存储的变量是否为leaf node。说起来很抽象,直接上代码。
(有关leaf node,请参考我的另外一篇博客,https://blog.csdn.net/huyaoyu/article/details/81059315)
测试代码
以下代码测试在PyTorch 1.3.1上。
import torch
if __name__ == "__main__":
a = torch.tensor([1.0], requires_grad=False)
print("a.is_leaf = {}. ".format( a.is_leaf ))
b = torch.tensor([1.0], requires_grad=True)
print("b.is_leaf = {}. ".format( b.is_leaf ))
c = torch.tensor(
PyTorch中leaf node的理解与测试

本文探讨了PyTorch中关于leaf node的问题,通过一个实例展示了如何在操作tensor时影响到变量的leaf node状态。在测试代码中,作者发现对tensor进行某些操作会导致其变为非leaf node,这在自动梯度计算中有重要影响。为保持变量为leaf node,建议在使用torch操作时不指定requires_grad,并在最后显式设置成员变量。
最低0.47元/天 解锁文章
1330

被折叠的 条评论
为什么被折叠?



