scipy 为什么这种shgo最小化失败了?

ttcibm8c  于 2023-06-23  发布在  Go
关注(0)|答案(1)|浏览(164)

我尝试在shgo中使用线性约束。下面是一个简单的MWE:

from scipy.optimize import shgo,  rosen

# Set up the constraints list
constraints = [{'type': 'ineq', 'fun': lambda x, i=i: x[i+1] - x[i] - 0.1} for i in range(2)]

# Define the variable bounds
bounds = [(0, 20)]*3

# Call the shgo function with constraints
result = shgo(rosen, bounds, constraints=constraints)

# Print the optimal solution
print("Optimal solution:", result.x)
print("Optimal value:", result.fun)

满足这些约束的示例解决方案是:

rosen((0.1, 0.21, 0.32))
13.046181

但是如果你运行代码,你会得到:

Optimal solution: None
Optimal value: None

根本找不到可行的解决方案!这是一个bug吗?

oug3syen

oug3syen1#

对于当前的输入,您得到的是None,因为constraints没有在shgo(rosen, bounds, constraints=constraints)中使用。
根据该文件:https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.shgo.html
约束应该是dict或dict序列。
您的constraintslist
因此,您必须执行constraints=constraints[0]

from scipy.optimize import shgo,  rosen

# Set up the constraints list
constraints = [{'type': 'ineq', 'fun': lambda x, i=i: x[i+1] - x[i] - 0.1} for i in range(2)]

# Define the variable bounds
bounds = [(0, 20)]*3

# Call the shgo function with constraints
result = shgo(rosen, bounds, constraints=constraints[0])

# Print the optimal solution
print("Optimal solution:", result.x)
print("Optimal value:", result.fun)
#output

Optimal solution: [ 0. 20. 20.]
Optimal value: 14480362.0

编辑:

如果我们打印约束,我们将得到:

[{'type': 'ineq', 'fun': <function __main__.<listcomp>.<lambda>(x, i=0)>},
 {'type': 'ineq', 'fun': <function __main__.<listcomp>.<lambda>(x, i=1)>}]

我们也可以这样做:

# Call the shgo function with constraints
result = shgo(rosen, bounds, constraints=constraints[1])

# Print the optimal solution
print("Optimal solution:", result.x)
print("Optimal value:", result.fun)
output:

Optimal solution: [ 1.77749693  3.16168239 10.        ]
Optimal value: 5.279267671341584

相关问题