【问题标题】:Understanding constraint in scipy's optimize了解 scipy 优化中的约束
【发布时间】:2019-02-10 20:48:50
【问题描述】:

我试图了解constraints 中的scipy 优化功能。我想在假设输入值始终为正的情况下最小化函数。所以我的约束函数定义如下:

def apply_constraint(inputs):
    return inputs[0] - inputs[0]

如果我的所有输入都是负数会怎样?我尝试使用负输入,但无法理解结果。约束属性的真正含义是什么?它还会给出负值的结果。

这是我的完整代码。

from __future__ import division
import numpy as np
from scipy.optimize import minimize


def f(x):
    Y = ((x + 100) / 100)
    return Y[0]


def apply_constraint(inputs):
    return inputs[0] - inputs[0]


my_constraints = ({'type': 'eq', "fun": apply_constraint})

min_result = minimize(f, [2], method="SLSQP", options={
                    'disp': False}, bounds=[(-2, 101)], constraints=my_constraints)

print("Minima found at: X = {}, Y = {}".format(min_result.x, min_result.fun))

【问题讨论】:

    标签: python scipy


    【解决方案1】:

    你的约束函数不正确

    inputs[0] - inputs[0] 永远是 0,应该是

    def apply_constraint(inputs):
        return inputs[0]
    

    约束以type = 'eq'type = 'ineq' 两种方式之一起作用

    将评估约束函数并与0进行比较

    对于等式约束,约束函数将被强制为= 0

    对于不等式约束,约束函数将被强制为非负,即>=0

    在这种情况下,使用上面的约束函数和type = 'ineq' 应该可以工作

    【讨论】:

    • OP 想知道 constraint_function 如何影响结果。你可以试着用一个例子来解释一下。
    猜你喜欢
    • 2014-07-13
    • 1970-01-01
    • 1970-01-01
    • 2022-09-17
    • 2021-08-18
    • 1970-01-01
    • 1970-01-01
    • 2022-01-22
    • 2015-06-09
    相关资源
    最近更新 更多