输出来自scipy.optimize.leastsq()的所有猜测

时间:2019-09-06 21:30:09

标签: python scipy regression least-squares

我希望制作一个动画,说明scipy.optimize.leastsq()提供的最小二乘回归分析如何收敛于特定结果。有什么方法可以让函数将每次迭代的猜测值元组追加到列表中,直到函数收敛到局部最小值为止?或者,是否存在包含此功能的其他库?

以下是我所拥有的:

# initial guess for gaussian distributions to optimize [height, position, width].
# if more than 2 distributions required, add a new set of [h,p,w] initial parameters to 'initials' for each new distribution.
# new parameters should be of the same format for consistency; i.e. [h,p,w],[h,p,w],[h,p,w]... etc.
# A 'w' guess of 1 is typically a sufficient estimation.

initials = [6.5,13,1],[4.5,19,1]

# determines the number of gaussian functions to compute from the initial guesses
n = len(initials)

# formats initials into a 1D array
var = np.concatenate(initials)

# data matrix
M = np.array(master)

# defines a typical gaussian function, of independent variable x,
# amplitude a, position b, and width parameter c.
def gaussian(x,a,b,c):
    return a*np.exp((-(x-b)**2.0)/c**2.0)

# defines the expected resultant as a sum of intrinsic gaussian functions
def GaussSum(x, p):
    return sum(gaussian(x, p[3*k], p[3*k+1], p[3*k+2]) for k in range(n))

# defines condition of minimization, reducing the square of the difference between the data (y) and the function 'func(x,p)'
def residuals(p, y, x):
    return (y - GaussSum(x,p))**2

# executes least-squares regression analysis to optimize initial parameters
cnsts = leastsq(residuals, var, args=(M[:,1],M[:,0]))[0]

我最终希望的是,“ cnsts”是从初始猜测到最终猜测的每个猜测的元组列表。

1 个答案:

答案 0 :(得分:0)

如果我正确地理解了您的问题,那么您想在拟合线性回归线时对每个不同的系数进行猜测,然后列出所有被猜测的系数?类似于NN如何反向传播误差以更好地拟合模型?

线性回归不能猜测不同的系数。只是在计算它们... https://www.statisticshowto.datasciencecentral.com/probability-and-statistics/regression-analysis/find-a-linear-regression-equation/#FindaLinear