使用目标对象的.backward()进行反向梯度求导
import torch x = torch.randn(3, 4, requires_grad=True) print(x) b = torch.randn(3, 4, requires_grad=True) t = x + b y = t.sum() y.backward() print(b.grad) x = torch.rand(1) b = torch.rand(1, requires_grad=True) w = torch.rand(1, requires_grad=True) y = x * w z = y + b z.backward(retain_graph=True) print(w.grad) print(b.grad)
原文地址:https://www.cnblogs.com/my-love-is-python/p/12643596.html
时间: 2024-10-13 14:18:19