简体   繁体   English

了解scipy优化中的约束

[英]Understanding constraint in scipy's optimize

I am trying to understand constraints in the scipy optimize function. 我试图了解scipy优化功能的constraints I want to minimize the function under the assumption, that input values would always be positive. 我想在假设输入值始终为正的情况下最小化函数。 So I have my constraint function defined as follows: 所以我的约束函数定义如下:

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

What would happen if all my inputs are negative? 如果我所有的输入都为负,将会发生什么? I tried with negative inputs but could not understand the result. 我尝试使用负输入,但无法理解结果。 What is the constraint attribute really meant for? 约束属性的真正含义是什么? It also gives results with negative values. 它还给出带有负值的结果。

Here is my complete code. 这是我完整的代码。

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))

Your constraint function is incorrect 您的约束函数不正确

inputs[0] - inputs[0] will always be 0, it should be inputs[0] - inputs[0]始终为0,应该为

def apply_constraint(inputs):
    return inputs[0]

Constraints work in one of two ways either type = 'eq' or type = 'ineq' 约束以两种方式之一起作用: type = 'eq'type = 'ineq'

The constraint function will be evaluated and compared with 0 约束函数将被评估并与0比较

For an equality constraint the constraint function will be forced to = 0 对于相等约束,约束函数将强制为= 0

For an inequality constraint the constraint function will be forced to be non-negative ie >=0 对于不等式约束,约束函数将被强制为非负值,即>=0

In this case using the constraint function above and type = 'ineq' should work 在这种情况下,使用上面的约束函数和type = 'ineq'应该有效

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM