我正在尝试使用 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)