使用lmfit minimize在三维点数据集中拟合三维直线

2024-04-18 03:46:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用lmfit minimize来拟合三维点数据集上的三维线。在

from lmfit import minimize, Parameters, report_fit,fit_report, printfuncs
import numpy as np

#Parameters of parametric equations:  
#x = p[0] + p[1]*t;
#y = p[2] + p[3]*t;
#z = t;
params = Parameters()
params.add('x0',   value= 1)
params.add('x1',   value= 1)
params.add('y0',   value= 1)
params.add('y1',   value= 1)

#Function to be minimized - sum of distances between the line and each point    
def fun(params,x,y,z):
    x0 = params['x0'].value; x1 = params['x1'].value 
    y0 = params['y0'].value; y1 = params['y1'].value
    d = 0  

    v0 = np.array([x0, y0, 0.0])
    v1 = np.array([x0+x1, y0+y1, 1.])
    for point in range(len(x)):           
        p = np.array([x[point], y[point], z[point]])
        d += np.linalg.norm(np.cross(v1-v0,v0-p))/np.linalg.norm(v1-v0)  
    return d


result = minimize(fun, params,args=(x,y,z)))
result.params.pretty_print()
print(fit_report(result))

错误为类型错误:输入不正确:N=4不得超过M=1。在

我知道这是因为只有1个残差(距离)和4个参数,但这是我需要的。我想优化4个参数,以获得最小距离之和。在


Tags: reportaddvaluenpparamsarrayfitpoint
3条回答

似乎是方法问题。在

The objective function should return the value to be minimized. For the >Levenberg-Marquardt algorithm from leastsq() or least_squares(), this >returned value must be an array, with a length greater than or equal to >the number of fitting variables in the model.

使用Nelder,我得到了结果。 但不是正确的。所以还是不确定密码。在

问题是在您的例子中,fun返回一个标量。对于某些方法来说,这没问题,但是正如您正确地指出的那样,least_squares需要一个数组。我认为重写目标函数以使它返回一个数组应该可以解决这个问题-看看描述和示例here。在

对于使用Levenberg-Marquardt最小化(默认的lmfit.minimize())方法,您应该返回距离的ndarray。也就是说,不要自己求最小平方和。通过返回完整数组(一组特定参数值的所有距离观测值),可以让拟合算法更好地探索参数对拟合质量的影响。在

相关问题 更多 >