gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 23:58:48 28 4
gpt4 key购买 nike

我现在遇到了一个问题,我为此争论了好几天。

How do I calculate the (95%) confidence band of a fit?

将曲线拟合到数据是每个物理学家的日常工作——所以我认为这应该在某个地方实现——但我找不到一个实现,我也不知道如何在数学上做到这一点。

我唯一找到的是 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 等最小二乘法的标准误差计算 t 分布,但这不是我要搜索的。

感谢您的帮助!

最佳答案

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

关于python - 计算最小二乘拟合的置信带,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27116479/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com