在所有情况下,Numpy Leastsq拟合返回不变的初始猜测

时间:2014-01-15 20:12:00

标签: python numpy least-squares data-fitting

我正在尝试使用Leastsq拟合函数以适应fft中的一些相关点。手头的问题是,无论合适程度有多好或多坏,参数绝对没有变化。换句话说,最小二乘需要6次迭代并且对它们中的任何一个都不做任何操作,然后返回初始参数值。我无法确定为什么没有发生任何事情。

guess = [per_guess,thresh_guess,cen_guess] #parameter guesses, all real numbers    
res, stuff = leastsq(fitting, guess)

拟合函数有许多操作来查找正确的索引,我不会在这里重现以节省空间,但它会返回一个复数列表:

M, freq= fft(real_gv, zf)
def fitting(guess):
    gi, trial_gv = gen_pat(size, guess[0], guess[1], guess[2])
    trial_gv = trial_gv*private.han #apply hanning window
    F, freq= fft(trial_gv, zf) 
    #stuff that picks the right indices
    return M[left_fit target:right_fit_target]-F[left_fit target:right_fit_target]

我在回归中尝试使用数组强制转换,但是我会经常收到关于在复杂和真实浮点数之间进行投射的错误,即使我没有要求任何错误。即使使用这种方法,我偶尔也会收到ComplexWarnings。

编辑:

根据要求,我提出了gen_pat:

def gen_pat(num, period, threshold, pos = 0, step = 1.0, subdivide=10.0, blur = 1.0):
x= np.arange(-num/2,num/2,step) #grid indexes
j=np.zeros((len(x),subdivide))
for i in range(len(x)):
    j[i]=np.linspace(x[i]-0.5*blur,x[i]+0.5*blur,subdivide) #around each discrete point take a subvision. This will be averaged to get the antialiased point. blur allows for underlap (<1) or overlap of pxels
holder = -np.sin(2*np.pi*np.abs(j-pos)/period) #map a sin function for the region
holder = holder < 2.0*threshold-1.0 #map to 1 or 0 based on the fraction of the period that is 0
y = np.sum(holder, axis=1)/float(subdivide) #take the average of the values at the sub-points to get the anti-aliased value at the point i
y= np.array(y)
x= np.array(x)
return x,y

编辑2:

使用res = fmin_powell(fitting, guess, direc=[[1,0,0],[0,0.1,0],[0,0,1]])和修改后的返回来管理工作。还是想知道为什么lestsq不起作用。

return np.sum((M[fit_start_index:fit_end_index].real-F[fit_start_index:fit_end_index].real)**2+(M[fit_start_index:fit_end_index].imag-F[fit_start_index:fit_end_index].imag)**2)

1 个答案:

答案 0 :(得分:0)

提供的函数gen_pat(x1,x2,x3,x4)返回值为1的水平线,用于我尝试的输入(x1,x2,x3,x4)的几个值。其傅立叶分量(当然除了第0个分量)总是零,与参数无关。然后,lesssq算法失败,因为4个参数的变化不会影响您尝试优化的傅立叶分量。

你在gen_pat()做错了,无论是编码还是概念错误,比如选择错误的拟合曲线。