约束说向量的所有元素在 scipy 优化中必须 >= 0

问题描述

输入向量是 x,它包含 5 个元素,我想优化(最小化)一个带有 x 的所有元素应大于或等于 0 的约束的函数。 即,x[i] >= 0 代表 1 <= i <= 5 在我看到并在我的代码中使用的答案之一中,但答案也返回负值

def constraint2(x):
    """constrain all elements of a to be >= 0"""
    return x

cons2 = {'type': 'ineq','fun': constraint2}

我哪里出错了?如何强制执行约束?

解决方法

all(ele >= 0 for ele in x)

试试这个