可以制作一个循环并手动构造雅可比矩阵,但我想知道是否还有更有效的方法。
我所做的一个示例,仅给出了雅可比矩阵的一行:
import torch
dt = torch.tensor([0.02]).double()
m = torch.tensor([1.0]).double()
l = torch.tensor([1.0]).double()
g = torch.tensor([9.80665]).double()
pi = torch.tensor([3.14159265359]).double()
def pendulom (x, u):
theta = torch.atan2(x[0], x[1])
theta_dot = x[2]
next_theta = theta + theta_dot*dt
theta_dot_dot = -3.0 * g / (2 * l) * tr.sin(theta + pi)
theta_dot_dot += 3.0 / (m * l**2) * u.double()
next_theta_dot = theta_dot + theta_dot_dot * dt
return torch.stack((
torch.sin(next_theta),
torch.cos(next_theta),
next_theta_dot
),0)
x = torch.tensor([0., 1., 0.],dtype=torch.float64, requires_grad=True)
u = torch.tensor([-1.0], dtype=torch.float64, requires_grad=True)
y = pendulom(x,u)
y.backward(torch.ones_like(y))
x.grad
output:
tensor([1.2942, 0.0000, 1.0200], dtype=torch.float64)