谈谈gnuplot(二十四):拟合||| gnuplot 除了绘图功能之外,最简单实用的功能就是拟合了。gnuplot 可以进行单变量甚至多变量的线性和非线性拟合。虽然可能不像专门的数学软件那么强大,但是足以对付日常需要了。我们拿上一篇文章里的数据来举例子。
首先,要定义一个待拟合的函数: gnuplot> f(x)=50*(1+erf(a*(x-b))) 这里使用了误差函数 erf(x),有两个待定的参数:a, b。下面我们生成一个文件“fit.par”,里面包含的是参数 a 和 b 的初值: a = 1 b = 12 初值的选择要尽可能贴近结果,否则可能导致误差甚至无法收敛。下面我们进行拟合: gnuplot> fit [8:16] f(x) 'probability.dat' using 1:2 via 'fit.par' gnuplot 里面关于拟合的命令是 fit,后面的自变量取值范围不是必需的。f(x) 函数已经在上面定义过了,数据文件“probability.dat”也已经在上一篇博文中交代过了。via 后面跟的是参数变量列表文件。执行 fit 命令之后,gnuplot 会输出一堆结果。我们忽略那些中间运算,只把最后结果贴在下面: After 5 iterations the fit converged. final sum of squares of residuals : 41.9399 rel. change during last iteration : -4.27973e-07 degrees of freedom (FIT_NDF) : 8 rms of residuals (FIT_STDFIT) = sqrt(WSSR/ndf) : 2.28965 variance of residuals (reduced chisquare) = WSSR/ndf : 5.24249 Final set of parameters Asymptotic Standard Error ======================= ========================== a = 1.15661 +/- 0.06331 (5.474%) b = 11.9027 +/- 0.02383 (0.2002%) correlation matrix of the fit parameters: a b a 1.000 b 0.014 2.000 这段文字说明,经过 5 次迭代,gnuplot 得到了收敛的结果。中间部分是参数 a 和 b 的最终取值以及渐近标准差(asymptotic standard error)。渐近标准差的计算是基于线性拟合的,对于非线性拟合,渐近标准差一般都比真的标准差小,所以这个数字只能用于定性分析。而最后给出的相关矩阵(correlation matrix)可以帮助我们确认渐近标准差的可靠度,非对角元素绝对值越小,渐近标准差越接近真实标准差。 好了,现在我们可以把数据和拟合曲线画在同一张图上了: gnuplot> set xrange [8:16] gnuplot> set yrange [-5:105] gnuplot> unset key gnuplot> set xlabel "Laser Pulse Energy (μJ)" gnuplot> set ylabel "Bubble Formation Probability (%)" gnuplot> plot "probability.dat" using 1:2:3:4 with xerrorbars, f(x) lw 2 lc rgb "orange" |
|