Pytorch之autograd

酥酥 发布于 2022-04-14 114 次阅读


				
					import torch

print(torch.__version__)
				
			
				
					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)
				
			
				
					print(x.is_leaf, y.is_leaf)
				
			
True False
				
					z = y * y * 3
out = z.mean()
print(z, out)
				
			
				
					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)
				
			
				
					out.backward() # 等价于 out.backward(torch.tensor(1.))
print(x.grad)
				
			
				
					# 再来反向传播一次,注意grad是累加的
out2 = x.sum()
out2.backward()
print(x.grad)

out3 = x.sum()
x.grad.data.zero_()
out3.backward()
print(x.grad)
				
			
tensor([[5.5000, 5.5000],
        [5.5000, 5.5000]])
tensor([[1., 1.],
        [1., 1.]])
				
					x = torch.tensor([1.0, 2.0, 3.0, 4.0], requires_grad=True)
y = 2 * x
z = y.view(2, 2)
print(z)
				
			
				
					v = torch.tensor([[1.0, 0.1], [0.01, 0.001]], dtype=torch.float)
z.backward(v)

print(x.grad)
				
			
				
					x = torch.tensor(1.0, requires_grad=True)
y1 = x ** 2 
with torch.no_grad():
    y2 = x ** 3
y3 = y1 + y2
    
print(x, x.requires_grad)
print(y1, y1.requires_grad)
print(y2, y2.requires_grad)
print(y3, y3.requires_grad)
				
			
tensor(1., requires_grad=True) True
tensor(1., grad_fn=<PowBackward0>) True
tensor(1.) False
tensor(2., grad_fn=<ThAddBackward>) True
				
					y3.backward()
print(x.grad)
				
			
				
					# y2.backward() # 会报错 RuntimeError: element 0 of tensors does not require grad and does not have a grad_fn
				
			

如果我们想要修改tensor的数值,但是又不希望被autograd记录(即不会影响反向传播),那么我么可以对tensor.data进行操作.

				
					x = torch.ones(1,requires_grad=True)

print(x.data) # 还是一个tensor
print(x.data.requires_grad) # 但是已经是独立于计算图之外

y = 2 * x
x.data *= 100 # 只改变了值,不会记录在计算图,所以不会影响梯度传播

y.backward()
print(x) # 更改data的值也会影响tensor的值
print(x.grad)
				
			
tensor([1.])
False
tensor([100.], requires_grad=True)
tensor([2.])