You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

疑问:代码中lambda函数的theta参数来源及使用逻辑

关于ProbInvKinematics类中theta参数的来源与逻辑解析

以下是你提到的代码片段(full_promp.py):

class ProbInvKinematics:
    #params:
    #fwd_k: A forward kinematics object

    def __laplace_cost_and_grad(self, theta, mu_theta, inv_sigma_theta, mu_x, inv_sigma_x):
        
        print ("theta ",theta)
        f_th, jac_th, ori = self.fwd_k.position_and_jac(theta)
        jac_th = jac_th[0:3,:]
        diff1 = theta - mu_theta
        tmp1 = np.dot(inv_sigma_theta, diff1)
        diff2 = f_th - mu_x
        tmp2 = np.dot(inv_sigma_x, diff2)
        
        nll = 0.5*(np.dot(diff1,tmp1) + np.dot(diff2,tmp2))
        
        grad_nll = tmp1 + np.dot(jac_th.T,tmp2)
        
        return nll, grad_nll

    def __init__(self, fwd_kinematics):
        self.fwd_k = fwd_kinematics

    def inv_kin(self, mu_theta, sig_theta, mu_x, sig_x):
        inv_sig_theta = np.linalg.inv(sig_theta)
        inv_sig_x = np.linalg.inv(sig_x)
        cost_grad = lambda theta: self.__laplace_cost_and_grad(theta, mu_theta, inv_sig_theta, mu_x, inv_sig_x)
        cost = lambda theta: cost_grad(theta)[0]
        grad = lambda theta: cost_grad(theta)[1]
        res = opt.minimize(cost, mu_theta, method='BFGS', jac=grad)
        post_mean = res.x
        post_cov = res.hess_inv
        return post_mean, post_cov

使用示例:

import robpy.full_promp as promp

prob_inv_kin = promp.ProbInvKinematics(fwd_kin)
mu_cartesian = np.array([-0.62, -0.44, -0.34])
Sigma_cartesian = 0.02**2*np.eye(3) 
mu_q, Sigma_q = prob_inv_kin.inv_kin(mu_theta=prior_mu_q, sig_theta=prior_Sigma_q,
        mu_x = mu_cartesian, sig_x = Sigma_cartesian)

theta参数的来源

theta是机器人关节角度的向量,它的值由BFGS优化器在迭代过程中自动生成和传递,具体调用链如下:

  1. 在inv_kin方法中,定义了cost_grad匿名函数,它接受theta作为参数,并将其传递给__laplace_cost_and_grad。
  2. 随后cost和grad两个匿名函数分别提取cost_grad的返回值(负对数似然和梯度),作为opt.minimize的目标函数和梯度函数。
  3. opt.minimize(对应scipy.optimize.minimize)的第二个参数mu_theta是优化的初始值(即示例中的prior_mu_q,关节角度的先验均值)。BFGS优化器会从这个初始值出发,不断迭代生成新的theta候选值,代入cost和grad函数计算,直到找到使目标函数最小的theta。
  4. 每次优化器调用cost或grad时,都会将当前的候选theta传入,最终传递到__laplace_cost_and_grad中,这就是你打印出的theta值的来源。

theta参数的使用逻辑

在__laplace_cost_and_grad方法中,theta的核心作用是作为逆运动学的求解变量,具体逻辑:

  • 传入theta后,通过正运动学对象self.fwd_k计算末端执行器的笛卡尔位置f_th,以及对应的雅可比矩阵jac_th。
  • 结合关节角度的先验分布(mu_theta、inv_sigma_theta)和目标笛卡尔位置的分布(mu_x、inv_sigma_x),计算负对数似然(nll)——这个值代表当前theta与先验和目标的匹配程度,值越小说明匹配度越高。
  • 同时计算nll的梯度(grad_nll),优化器利用这个梯度信息调整theta的取值方向,更快地收敛到最优解。
  • 优化结束后,最优的theta值会作为res.x返回,也就是逆运动学问题的解post_mean(关节角度的后验均值)。

内容的提问来源于stack exchange,提问作者Harald S.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 14:41:31