pytorch-tensor

创建一个 Tensor 并设置 requires_grad=True :

import torch
x = torch.ones(2, 2, requires_grad=True)
print(x)
print(x.grad_fn)

输出:

tensor([[1., 1.],
        [1., 1.]], requires_grad=True)
None

再做一下运算操作:

y = x + 2
print(y)
print(y.grad_fn)

输出:

tensor([[3., 3.],
        [3., 3.]], grad_fn=)

注意x是直接创建的,所以它没有 grad_fn , 而 y是通过一个加法操作创建的,所以它有一个为 的 grad_fn 。

像x这种直接创建的称为叶子节点,叶子节点对应的 grad_fn 是 None 。

print(x.is_leaf, y.is_leaf) # True False

再来点复杂度运算操作:

z = y * y * 3
out = z.mean()   #平均值
print(z, out)

输出:

tensor([[27., 27.],
        [27., 27.]], grad_fn=) tensor(27., grad_fn=)

通过 .requires_grad_() 来用in-place的方式改变 requires_grad 属性:

a = torch.randn(2, 2) # 缺失情况下默认 requires_grad = False
a = ((a * 3) / (a - 1))
print(a.requires_grad) # False
a.requires_grad_(True)
print(a.requires_grad) # True
b = (a * a).sum()
print(b.grad_fn)

输出:

False
True


 

未经允许不得转载!pytorch-tensor