简单记录一下利用python的SciPy库进行曲线拟合的方法,主要分为三个步骤,(1) 获取待拟合数据; (2) 定义函数描述待拟合曲线; (3)利用Scipy.optimize.curve_fit模块进行拟合。
获取数据的步骤不再赘述,这里从步骤二开始。以泊松分布为例,首先定义函数poisson_func
,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| import math def poisson_func(k, l, c): """Poisson function inputs ====== k: np.ndarray number of accidents, i.e., the x axis; l: double the lambda parameter of Poisson distribution c: double a constant for release the optimization output ====== the fitted result according to l and c w.r.t. k note ==== l and c are the parametres to be estimated. """ k_mat = np.ones(k.shape) for x, i in enumerate(k): k_mat[i] = math.factorial(x) return l**k / k_mat*np.exp(-l) + c
|
紧接着,根据待拟合的数据,对参数进行估计,如下
1 2 3 4
| from scipy.optimize import curve_fit popt, pcov = curve_fit(poisson_func, x, y) perr = np.sqrt(np.diag(pcov))
|
其中popt
为估计的参数,pcov
为对应的相关矩阵,其对角线为方差,可用于计算拟合参数的误差perr。
下图为我的测试样例,图中橙色三角为待拟合样本点,蓝色实线为拟合结果。
References
[1] Scipy.optimize.curve_fit
[2] Poisson distribution