如何获取scipy curve_fit计算方差所用的参数估计值集合?
解决方法:用Bootstrap生成参数估计值集合
scipy的curve_fit返回的pcov是基于最小二乘拟合的渐近协方差估计,并非来自实际的参数样本集合。要获取可用于计算方差、绘制直方图的参数估计值集合,需要通过**自助法(Bootstrap)**重新采样数据并多次拟合:
步骤说明
- 从原始数据中重复有放回采样生成新数据集
- 对每个新数据集用
curve_fit拟合,记录每次的参数估计值 - 用这些参数样本计算方差、绘制直方图
完整代码
import matplotlib.pyplot as plt import numpy as np from scipy.optimize import curve_fit # 原始数据 x_data = np.array([1, 2, 3, 4, 5]) y_data = np.array([2, 4, 9, 16, 25]) def function(x, a, b): return a * np.exp(-b*x) # 常规拟合获取初始参数 popt, pcov = curve_fit(function, x_data, y_data) a_init, b_init = popt # Bootstrap生成参数样本集合 n_bootstrap = 1000 # 采样次数,次数越多结果越稳定 a_samples = [] b_samples = [] for _ in range(n_bootstrap): # 有放回采样数据索引 idx = np.random.choice(len(x_data), size=len(x_data), replace=True) x_boot = x_data[idx] y_boot = y_data[idx] # 对采样数据拟合,用初始参数作为初始猜测提升稳定性 try: popt_boot, _ = curve_fit(function, x_boot, y_boot, p0=popt) a_samples.append(popt_boot[0]) b_samples.append(popt_boot[1]) except RuntimeError: # 跳过拟合失败的情况 continue a_samples = np.array(a_samples) b_samples = np.array(b_samples) # 手动计算方差和标准差 a_var = np.var(a_samples, ddof=1) # 样本方差 a_std = np.std(a_samples, ddof=1) b_var = np.var(b_samples, ddof=1) b_std = np.std(b_samples, ddof=1) # 输出结果对比 print("常规拟合a的标准差(pcov计算):", pcov[0,0]**0.5) print("Bootstrap样本a的标准差:", a_std) print("常规拟合b的标准差(pcov计算):", pcov[1,1]**0.5) print("Bootstrap样本b的标准差:", b_std) # 绘制参数直方图 fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 5)) # a参数直方图 ax1.hist(a_samples, bins=30, edgecolor='black', alpha=0.7) ax1.axvline(a_init, color='red', linestyle='--', label=f'初始拟合值: {a_init:.2f}') ax1.set_xlabel('参数a的估计值') ax1.set_ylabel('频次') ax1.set_title('参数a的Bootstrap估计值分布') ax1.legend() # b参数直方图 ax2.hist(b_samples, bins=30, edgecolor='black', alpha=0.7) ax2.axvline(b_init, color='red', linestyle='--', label=f'初始拟合值: {b_init:.2f}') ax2.set_xlabel('参数b的估计值') ax2.set_ylabel('频次') ax2.set_title('参数b的Bootstrap估计值分布') ax2.legend() plt.tight_layout() plt.show()
关键说明
- Bootstrap通过重复采样模拟参数分布,适合小样本或需要直观分布的场景
- 若拟合出现失败(RuntimeError),可调整
p0参数(初始猜测)或增加采样次数 - 数据符合模型假设时,
pcov计算的渐近标准差与Bootstrap样本标准差会接近
内容的提问来源于stack exchange,提问作者HAILEY RUDE
相关产品推荐
相关产品推荐

