|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
a = torch.arange(4., requires_grad = True)
b = torch.ones(4, requires_grad = True)
with torch.no_grad():
c = a+b
之后假如要对c求梯度,我怎么设置requires_grad = True呢?
在 with torch.no_grad() 的上下文环境中创建的张量,其 requires_grad 属性会被自动设置为 False,
这意味着在这个上下文环境内的张量不会被纳入计算图中,也不会对后续的梯度计算产生影响。
如果想要将其设置为 True,需要在 with torch.no_grad() 块之外再次显式地设置 requires_grad=True,
例如:
- a = torch.arange(4., requires_grad=True)
- b = torch.ones(4, requires_grad=True)
- with torch.no_grad():
- c = a + b
- # 将 c 的 requires_grad 设置为 True
- c.requires_grad_(True)
- # 对 c 进行计算,产生梯度
- loss = c.sum()
- loss.backward()
- # 查看梯度
- print(a.grad)
- print(b.grad)
- print(c.grad)
复制代码
上述代码中,通过调用 c.requires_grad_(True) 将 c 的 requires_grad 属性设置为 True,然后再对 c 进行操作并计算梯度。
|
|