【问题标题】:Minimizing multi variable function while some variables of the function stay constant. The constant variable is a list of lists最小化多变量函数,而函数的某些变量保持不变。常量变量是列表的列表
【发布时间】:2016-10-27 09:44:18
【问题描述】:

我对 python 还很陌生,并且已经遇到了一个相当复杂的问题(至少对我来说是这样)。我想最小化具有多个变量的函数,其中一个变量是我从模拟中获得的数据的列表列表。当程序优化其他两个变量时,此列表应保持不变。

https://gist.github.com/anonymous/0acb424f7c6942329918430fb616c040

到目前为止,这是我在 3 个不同文件中的代码。 Simulation.py 是计算列表列表的模拟。在 Function.py 中包含我想要最小化的函数“Gompertz”。如您所见,它包含三个变量。我想将模拟中的列表(“死亡列表”)放入第一个变量中。我想使用 Scipy 的最小化函数优化其他两个变量。 运行程序给了我以下错误,但我想我编写解决方案的方式通常有问题。任何帮助,将不胜感激 :)。 (不要担心程序中所有包含死亡的名字。我正在研究死亡率数据)

(编辑:我将边界条件更改为 b = (0.001, 10))

编辑:澄清 Optimize.py 是重要的部分。 Simulation.py 和 Function.py 仅用于上下文。我的问题是如何在优化过程中将列表变为常量变量,同时优化其他两个变量。因此,在 Optimize.py 文件中,我将列表的边界条件设置为 b = (deathlist, deathlist),这样它就会保持不变。我不确定这是否正确,如果不正确,我该如何以不同的方式编写此代码。

Traceback (most recent call last): File "/Users/jonas/PycharmProjects
/untitled2/Test/Simulation.py", 
line 25, in <module> sol = minimize(Function.Gompertz, x0, method ='SlSQP',bounds = bnds, constraints 
= cons) File "/Library/Frameworks/Python.framework/Versions/3.5/lib
/python3.5/site-packages/scipy/optimize/_minimize.py", 

line 458, in minimize constraints, callback=callback, **options) File "/Library
/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/scipy
/optimize/slsqp.py", 
line 307, in _minimize_slsqp x = asfarray(x0).flatten() File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/numpy/lib/type_check.py", 
line 105, in asfarray return asarray(a, dtype=dtype) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/numpy/core/numeric.py", 
line 482, in asarray return array(a, dtype, copy=False, order=order) ValueError: setting an array element with a sequence.```

【问题讨论】:

  • 尝试压缩你的代码,只包含有问题的部分。这样更容易回答!
  • 嗯,我不太确定问题出在哪里,这就是为什么我将代码分成 3 个文件。 Simulation.py 不是问题,所以我可以排除它。我把它放在那里只是为了上下文。但 Optimize.py 文件是我认为问题所在。

标签: python optimization scipy minimize


【解决方案1】:

你得到的错误 ValueError: setting an array element with a sequence. 表示数组元素不能包含列表。

为了给 minimize() 常量值,您应该将原始函数的参数拆分为 (n,) ndarray x 和所有其他参数。 因此,为您的 minimize() 函数提供附加常量参数的正确代码是:

def Gompertz(x, consts):

    x1 = x[1]
    x2 = x[2]
    LF = 0

    for j in range (100):
        DEATH = consts[j]
        T = len(consts)
        for tau in range(T): """the length of the list gives the range of the loop"""
                lf_i = x1 * exp(x2 * tau - x1/x2 * (exp(x2 * tau)-1))
                a = DEATH[tau]
                LF += lf_i ** a   """the values from the list are used here as a power of the valute lf_i """
return -LF 
deathlist = Function.Simulation()
x0 = [1,1]

sol = minimize(Function.Gompertz, x0, args=(deathlist,) method ='SlSQP',bounds = bnds, constraints = cons)
print (sol)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-18
    • 1970-01-01
    • 1970-01-01
    • 2021-12-07
    • 2019-11-05
    相关资源
    最近更新 更多