x2=torch.tensor(x,requires_grad=True)
t2=torch.tensor(t,requires_grad=True)
def mr():
for k in range(n):
z01=solve_burgers(torch.tensor([x2[k]]),0.25,0.01/np.pi)[0]
z01.backward(retain_graph=True)
u_xr=x2.grad[k]
u_tr=t2.grad[k]
return u_xr,u_tr,u_xxr
solve_burgers 是求解汉堡方程的函数。
当我运行此代码来计算导数时,出现以下错误: 类型错误:“NoneType”对象不可订阅
如何修复该错误?
您可以添加支票
None
:
def mr():
u_xr, u_tr = [], []
for k in range(n):
z01 = solve_burgers(torch.tensor([x2[k]]), 0.25, 0.01 / np.pi)[0]
z01.backward(retain_graph=True)
if x2.grad is not None:
u_xr.append(x2.grad.item())
x2.grad.zero_()
if t2.grad is not None:
u_tr.append(t2.grad.item())
t2.grad.zero_()
return u_xr, u_tr