我有一个问题,我和它争论了好几天。
如何计算拟合的(95%)置信区间?
数据拟合曲线是每一个物理学家的日常工作——所以我认为这应该在某个地方实现——但我找不到一个实现方法,我也不知道如何在数学上做到这一点。
我发现的唯一一件事是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")

但这只是线性最小二乘法。当我想拟合饱和曲线的时候,我就完蛋了。
当然,我可以用最小二乘法的标准差来计算t分布,比如scipy.optimize.curve_fit,但这不是我要寻找的。
谢谢你的帮助!!

最佳答案

您可以使用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()

08-20 00:26