首页 > 解决方案 > Scipy最小二乘警告:“无法估计参数的协方差”

问题描述

使用 scipy.optimize.curve_fit() 获取参数的协方差似乎是一个常见问题,但常见的解决方案对我没有太大帮助。(没有给出一个好的初始猜测,没有足够的数据点,没有输入一个 numpy 数组,没有使用 float64。)这重现了我的错误:

x = np.array([103.15, 113.15, 269.3, 273.15, 273.15, 283.15, 290.0, 293.15, 293.15, 296.15, 296.15, 303.15, 303.15, 303.15, 310.0, 313.15, 313.15, 318.15, 323.15, 323.15, 330.0, 333.15, 348.16, 350.0, 353.15])
y = np.array([-0.2468283, -0.19681169, -0.01856526, -0.01707074, -0.01698771, -0.01333444,  -0.01072733, -0.00986383, -0.00974759, -0.00830289, -0.00896712, -0.00699103, -0.00667552, -0.0063102, -0.00440053, -0.00368648, -0.0034374, -0.00199269, -0.00092992, -0.00066423, 0.00106277, 0.00166058, 0.00464962, 0.0060445,0.00650947])

((u0, u1, r0, r1), pcov) = scipy.optimize.curve_fit(f, x, y, p0=np.array([1.0, 0.01, 0.3, 0.5]))
    
print(u0, u1, r0, r1)
print(pcov)

我的功能在哪里:

def f(x, u0, u1, r0, r1):
    k = 8.617333262145E-5

    term1 = (np.exp(-u0/(k*x)) - np.exp(u1/(k*x))) * r0**3
    term2 = (np.exp(u1/(k*x)) - 1) * r1**3
    
return -(2 * np.pi / 3) * (term1 + term2)

输出是

OptimizeWarning: Covariance of the parameters could not be estimated
  warnings.warn('Covariance of the parameters could not be estimated',
1.0 0.010062693926842859 0.3093891634616651 0.4627801922742623
[[inf inf inf inf]
 [inf inf inf inf]
 [inf inf inf inf]
 [inf inf inf inf]]

绘制具有最佳拟合的数据点显示了出色的匹配。我不确定如何用协方差来解决这个问题。有任何想法吗?

标签: pythonscipyleast-squaresscipy-optimize

解决方案


根据文档

如果解决方案中的雅可比矩阵没有满秩,则 'lm' 方法返回一个填充有 np.inf 的矩阵,另一方面,'trf' 和 'dogbox' 方法使用 Moore-Penrose 伪逆来计算协方差矩阵。

我尝试使用method='trf'您的数据并且似乎有效。我不知道为什么雅可比在这种情况下是不可逆的。


推荐阅读