我正在尝试将动态n模态高斯函数拟合到一些测试数据,但是在获取scipy.optimize.curve_fit方法以正确解释我的参数时遇到了一些困难。
from scipy.optimize import curve_fit
import numpy as np
def gaussian(x_g, mu, sigma, a):
return a * np.exp((-1 * (x_g-mu) ** 2) / (2 * sigma)**2)
def n_modal(x_n, mu_n, sigma_n, a_n):
mu_n = np.array(mu_n)
sigma_n = np.array(sigma_n)
a_n = np.array(a_n)
result = 0
for i in range(mu_n.shape[0]):
result += gaussian(x_n, mu_n[i], sigma_n[i], a_n[i])
return result
xes = np.linspace(-2*np.pi, 2*np.pi, 1000)
ys = np.sin(2*xes)
mus = np.array([-6, -4, -2, -1, 1, 2, 4, 6]).reshape((1, 8))
sigmas = np.array([1, 1, 1, 1, 1, 1, 1, 1]).reshape((1, 8))
asz = np.array([1, -1, -1, 1, -1, 1, -1, 1]).reshape((1, 8))
params = np.concatenate((mus, sigmas, asz), axis=0)
param_opt, param_cov = curve_fit(n_modal, xes, ys, p0=params)
终端只是告诉我,正如预期的那样,我输入了错误数量的参数,因为该方法可能无法弄清楚该函数为mu_n,sigma_n和a_n接受了动态数量的参数。 / p>
我知道我可以使用大量变量(参见下文)来重新制作函数,但是我想要一些更通用的东西。我有什么选择?
def bimodal(x_bi, mu1, sigma1, a1, mu2, sigma2, a2):
return (gaussian(x_bi, mu1, sigma1, a1) +
gaussian(x_bi, mu2, sigma2, a2))
def trimodal(x_tri, mu1, sigma1, a1, mu2, sigma2, a2, mu3, sigma3, a3):
return (gaussian(x_tri, mu1, sigma1, a1) +
gaussian(x_tri, mu2, sigma2, a2) +
gaussian(x_tri, mu3, sigma3, a3))
def tetramodal(x_tet, mu1, sigma1, a1, mu2, sigma2, a2, mu3, sigma3, a3, mu4, sigma4, a4):
return (gaussian(x_tet, mu1, sigma1, a1) +
gaussian(x_tet, mu2, sigma2, a2) +
gaussian(x_tet, mu3, sigma3, a3) +
gaussian(x_tet, mu4, sigma4, a4))