计算最小二乘拟合的置信带

时间:2014-11-25 00:00:46

标签: python statistics regression confidence-interval

我有一个问题,我现在已经打了好几天了。

  

如何计算拟合的(95%)置信区间?

将曲线拟合到数据是每个物理学家的日常工作 - 所以我认为这应该在某个地方实施 - 但我无法找到实现这一点,我也不知道如何以数学方式进行此操作。 / p>

我找到的唯一的事情是seaborn,它为线性最小二乘做得很好。

import numpy as np                                                                                                                                                                                                                         
from matplotlib import pyplot as plt
import seaborn as sns
import pandas as pd

x = np.linspace(0,10)
y = 3*np.random.randn(50) + x

data = {'x':x, 'y':y}
frame = pd.DataFrame(data, columns=['x', 'y'])
sns.lmplot('x', 'y', frame, ci=95)

plt.savefig("confidence_band.pdf")

linear-least-square

但这只是线性最小二乘法。当我想要适合,例如像saturation-eqn这样的饱和度曲线,我已经搞砸了。

当然,我可以从像scipy.optimize.curve_fit这样的最小二乘法的std-error计算t分布,但这不是我正在搜索的内容。

感谢您的帮助!!

2 个答案:

答案 0 :(得分:6)

您可以使用StatsModels模块轻松实现此目的。

另见this examplethis answer

以下是您的问题的答案:

import numpy as np
from matplotlib import pyplot as plt

import statsmodels.api as sm
from statsmodels.stats.outliers_influence import summary_table

x = np.linspace(0,10)
y = 3*np.random.randn(50) + x
X = sm.add_constant(x)
res = sm.OLS(y, X).fit()

st, data, ss2 = summary_table(res, alpha=0.05)
fittedvalues = data[:,2]
predict_mean_se  = data[:,3]
predict_mean_ci_low, predict_mean_ci_upp = data[:,4:6].T
predict_ci_low, predict_ci_upp = data[:,6:8].T

fig, ax = plt.subplots(figsize=(8,6))
ax.plot(x, y, 'o', label="data")
ax.plot(X, fittedvalues, 'r-', label='OLS')
ax.plot(X, predict_ci_low, 'b--')
ax.plot(X, predict_ci_upp, 'b--')
ax.plot(X, predict_mean_ci_low, 'g--')
ax.plot(X, predict_mean_ci_upp, 'g--')
ax.legend(loc='best');
plt.show()

Example

答案 1 :(得分:0)

kmpfit' s confidence_band()计算非线性最小二乘的置信带。这里为您的饱和曲线:

from pylab import *
from kapteyn import kmpfit

def model(p, x):
  a, b = p
  return a*(1-np.exp(b*x))

x = np.linspace(0, 10, 100)
y = .1*np.random.randn(x.size) + model([1, -.4], x)

fit = kmpfit.simplefit(model, [.1, -.1], x, y)
a, b = fit.params
dfdp = [1-np.exp(b*x), -a*x*np.exp(b*x)]
yhat, upper, lower = fit.confidence_band(x, dfdp, 0.95, model)

scatter(x, y, marker='.', color='#0000ba')
for i, l in enumerate((upper, lower, yhat)):
  plot(x, l, c='g' if i == 2 else 'r', lw=2)
savefig('kmpfit confidence bands.png', bbox_inches='tight')

dfdp是关于每个参数p(即a和b)的模型f = a *(1-e ^(b * x))的偏导数∂f/∂p,有关背景链接,请参阅我的answer类似问题。在这里输出:

kmpfit confidence bands

相关问题