【问题标题】:ValueError: The array returned by a function changed size between calls scipy.fsolve()ValueError:函数返回的数组在调用 scipy.fsolve() 之间改变了大小
【发布时间】:2019-07-09 22:54:52
【问题描述】:

我正在尝试使用 scipy.optimize.fsolve() 求解使函数等于零的 x,但不断收到上述错误。我的代码是:

import scipy.optimize as optimize
from scipy.stats import genextreme as gev

gevcombined = [(-0.139, 3.035, 0.871),(-0.0863, 3.103, 0.818),(-0.198, 3.13, 0.982)]
ratio = [0.225, 0.139, 0.294]
P = [0.5,0.8,0.9,0.96,0.98,0.99]
def mixedpop(x):
    for j in range(len(ratio)):
        F = (ratio[j]*gev.cdf(x,gevcombined[j][0],gevcombined[j][1],gevcombined[j][2]))+((1-ratio[j]*gev.cdf(x,gevcombined[j][0],gevcombined[j][1],gevcombined[j][2]))-P
    return F

initial = 10
Rm = optimize.fsolve(mixedpop,initial)

我不断收到错误:

ValueError:the array returned by a function changed size between calls

这个错误是什么意思?预期输出将是每个 P 值的值。因此,对于每个比率,来自 Rm 的 x 值将等于 [3.5, 4, 5.4, 6.3, 7.2, 8.1]

【问题讨论】:

  • fsolve 首先调用具有initial 值的函数,例如mixedpop(10)。然后它会尝试其他值,mixedpop(x)。我不会尝试运行您的代码,但听起来F 的形状可能会随x 的值而变化。

标签: python optimization scipy


【解决方案1】:

好的,我想出了如何让 fsolve 为一系列解决方案工作。

如果我像这样写整个事情,它会起作用:

Rm = []
initial = [10,10,10,10,10,10]
for j in range(len(ratio)):
    f = lambda x : (ratio[j]*gev.cdf(x,gevcombined[j][0],gevcombined[j][1],gevcombined[j][2]))+((1-ratio[j]*gev.cdf(x,gevcombined[j][0],gevcombined[j][1],gevcombined[j][2]))-P
    Rm.append(list(optimize.fsolve(f,initial)))

我的输出是:

[[3.37, 4.37, 5.13, 6.43, 7.91, 9.88],[3.41, 4.42, 5.09, 6.13, 7.07, 8.18],[3.49, 4.87, 5.95, 7.51, 8.80, 10.19]]

【讨论】:

    【解决方案2】:

    发生错误是因为 initial 的形状与您的变量不匹配。

    initial = np.ones(len(x))
    

    但是,我无法理解您的功能正在做什么。它对我有用。

    【讨论】:

      猜你喜欢
      • 2021-02-18
      • 1970-01-01
      • 2011-11-11
      • 1970-01-01
      • 2021-09-01
      • 2013-12-25
      • 2018-08-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多