Python中的Matlab lsqnonlin

时间:2016-05-13 13:29:32

标签: python matlab scipy mathematical-optimization

我一直在研究Hartley和Zisserman多视图几何文本,并实现了用于计算基本矩阵的金标准算法。这需要使用Levenberg-Marquardt解决非线性最小化问题。

我用scipy.optimize.least_squares实现了此功能,但性能比使用lsqnonlin的类似(例如,相同功能)的matlab代码慢了几个数量级。在任何一种情况下,我都不提供雅可比行列式或雅各比派稀疏性的面具。

关于计算时间,对于可用的scipy求解器范围,这是正确的。我想知道是否存在与matlab具有相似性能(数值和速度)的替代方案,或者是否需要转移到包装的编译求解器?

编辑代码请求评论。我试图限制插入的代码总量。

Matlab的:

P2GS = lsqnonlin(@(h)ReprojErrGS(corres1,PF1,corres2,h),PF2); 

function REGS = ReprojErrGS(corres1,PF1,corres2,PF2)
   %Find estimated 3D point by Triangulation method
   XwEst = TriangulationGS(corres1,PF1,corres2,PF2);
   %Reprojection Back to the image
   x1hat = PF1*XwEst;
   x1hat = x1hat ./ repmat(x1hat(3,:),3,1);
   x2hat = PF2*XwEst;
   x2hat = x2hat ./ repmat(x2hat(3,:),3,1);
   %Find root mean squared distance error
   dist = ((corres1 - x1hat).*(corres1 - x1hat))  +  ((corres2 - x2hat).*    (corres2 - x2hat));
   REGS = sqrt(sum(sum(dist)) / size(corres1,2));           

三角测量是标准方法,迭代所有点,设置Ax = 0并使用SVD求解。

Python:

# Using 'trf' for performance, swap to 'lm' for levenberg-marquardt
result = optimize.least_squares(projection_error, p1.ravel(), args=(p, pt.values, pt1.values), method='trf')
# Inputs are pandas dataframe, hence the .values

# Triangulate the correspondences 
xw_est = triangulate(pt, pt1, p, p1)
# SciPy does not like 2d multi-dimensional variables, so reshape

if p1.shape != (3,4):
    p1 = p1.reshape(3,4)

xhat = p.dot(xw_est).T
xhat /= xhat[:,-1][:,np.newaxis]
x2hat = p1.dot(xw_est).T
x2hat /= x2hat[:,-1][:,np.newaxis]
# Compute error
dist = (pt - xhat)**2 + (pt1 - x2hat)**2
reproj_error = np.sqrt(np.sum(dist, axis=1) / len(pt))
# print(reproj_error)
return reproj_error

这应该是完全矢量化的。三角测量如上。我可以补充一点,但可能会链接一个要点,以保持问题规模可管理。

2 个答案:

答案 0 :(得分:0)

least_squares非常新。截至2015年秋季,SciPy土地上没有替代品。否则,例如的Ceres。

肯定有很多机会加快least_squares ---拉取请求很乐意接受:-)。首先要检查的是SciPy与一个体面的LAPACK实现相关联。

答案 1 :(得分:0)

我认为速度差异很大的原因是matlab的lsqnonlin能够检测Jacobian矩阵的稀疏结构,因此计算速度更快。另一方面,scipy的minimum_squares不会处理稀疏的Jacobian矩阵,不会像标准情况一样计算Jacobian的每个元素(还有不必要的条目)。

在这个特定的优化问题(确定基本矩阵的金标准算法)中,雅各布矩阵的稀疏计算对于获得如Hartley和Zisserman中所述和的良好性能至关重要。 (取决于F计算的点对应的数量,最多为10分钟的几分钟)

这是到稀疏LM实现的Paython包装器的链接。但是运行起来要复杂一些:

http://www.bmp.ds.mpg.de/pysparselm.html

我希望scipy的minimum_squares很快将得到升级,以处理稀疏的Jacobian。