我正在lmfit
使用带有以下代码的一些测试数据来运行 Python 2.7。1/y
我需要权重为(使用 Leven-Marq. 例程)的加权拟合。我已经定义了权重并在这里使用它们:
from __future__ import division
from numpy import array, var
from lmfit import Model
from lmfit.models import GaussianModel, LinearModel
import matplotlib.pyplot as plt
import seaborn as sns
xd = array([1267, 1268, 1269, 1270, 1271, 1272, 1273, 1274, 1275, 1276,
1277, 1278, 1279, 1280, 1281, 1282, 1283, 1284, 1285, 1286, 1287, 1288,
1289, 1290, 1291, 1292, 1293, 1294, 1295, 1296, 1297, 1298, 1299, 1300,
1301, 1302, 1303, 1304, 1305, 1306, 1307, 1308, 1309, 1310, 1311, 1312,
1313, 1314, 1315, 1316, 1317, 1318, 1319, 1320, 1321, 1322, 1323, 1324,
1325, 1326, 1327, 1328, 1329, 1330, 1331, 1332, 1333, 1334])
yd = array([238, 262, 255, 271, 270, 281, 261, 278, 280, 254, 289, 285, 304, 314,
329, 342, 379, 450, 449, 564, 613, 705, 769, 899, 987, 1043, 1183, 1295, 1298,
1521, 1502, 1605, 1639, 1572, 1659, 1558, 1476, 1397, 1267, 1193, 1016, 951,
835, 741, 678, 558, 502, 480, 442, 399, 331, 334, 308, 283, 296, 265, 264,
273, 258, 270, 262, 263, 239, 263, 251, 246, 246, 234])
mod = GaussianModel() + LinearModel()
pars = mod.make_params(amplitude=25300, center=1299, sigma=7, slope=0, intercept=450)
result = mod.fit(yd, pars, method='leastsq', x=xd, weights=1./yd)
rsq = 1 - result.residual.var() / var(yd)
print(result.fit_report())
print rsq
plt.plot(xd, yd, 'bo', label='raw')
plt.plot(xd, result.init_fit, 'k--', label='Initial_Guess')
plt.plot(xd, result.best_fit, 'r-', label='Best')
plt.legend()
plt.show()
输出是:
[[Model]]
(Model(gaussian) + Model(linear))
[[Fit Statistics]]
# function evals = 27
# data points = 68
# variables = 5
chi-square = 0.099
reduced chi-square = 0.002
Akaike info crit = -434.115
Bayesian info crit = -423.017
[[Variables]]
sigma: 7.57360038 +/- 0.063715 (0.84%) (init= 7)
center: 1299.41410 +/- 0.071046 (0.01%) (init= 1299)
amplitude: 25369.3304 +/- 263.0961 (1.04%) (init= 25300)
slope: -0.15015228 +/- 0.071540 (47.65%) (init= 0)
intercept: 452.838215 +/- 93.28860 (20.60%) (init= 450)
fwhm: 17.8344656 +/- 0.150037 (0.84%) == '2.3548200*sigma'
height: 1336.33919 +/- 17.28192 (1.29%) == '0.3989423*amplitude/max(1.e-15, sigma)'
.
.
.
.
0.999999993313
最后一行(就在此处上方,或紧接在 之前plt.plot(xd, yd, 'bo', label='raw')
)是 R^2 并且结果拟合附在此处。.
R^2 和输出的目视检查表明这是一个合理的拟合。我期待减少 1.00 阶的卡方(来源)。但是,减少的卡方值的返回值比 1.00 小几个数量级。
由于默认情况下没有权重并且lmfit
我需要加权拟合,因此我已经定义了权重,但我认为我需要以不同的方式指定它们。我怀疑这种权重规范可能导致减少的卡方变得如此之小。
是否有不同的方法来指定权重或其他一些参数,以便曲线拟合后减少的卡方接近或等于 1.00 的大小?