pytorch中反向传播求梯度的问题

我们都知道pytorch中有自动求梯度的功能,具体例子如下代码:

import torch
a = torch.ones(1, 1, requires_grad=True)
b = a**2+3
c = a+b
d = c**2+b
print('d',d.grad_fn)

运行结果为:

d <AddBackward0 object at 0x000001AE67612E48>

也就是能求d关于a的梯度

但是,当进行如下的运算时却无法进行梯度求解:

import torch
a = torch.ones(1, 1, requires_grad=True)
b = a**2+3
c = a+b
d = c**2+b
print('d',d.grad_fn)

x = torch.tensor([[a,b],[c,d]])
y = torch.tensor([[a,c],[b,d]])
result = torch.mm(x,y)
print(‘result’,result.grad)

运行结果:

result None

怎么才能让它进行后面的相乘运算后得到的结果result还能进行梯度求解呢