cvxpy 正在解决产生空答案

cvxpy is solving to produce empty answer

我正在使用以下代码:

import sys, numpy as np
import cvxpy as cvx

if __name__ == '__main__':
    sims = np.random.randint(20, 30, size=500)
    center = 30
    n = [500, 1]

    # minimize     p'*log(p)
    # subject to
    #              sum(p) = 1
    #              sum(p'*a) = target1

    A = np.mat(np.vstack([np.ones(n[0]), sims]))
    b = np.mat([1.0, center]).T

    x = cvx.Variable(n)
    obj = cvx.Maximize(cvx.sum(cvx.entr(x)))
    constraints = [A @ x == b]
    prob = cvx.Problem(obj, constraints)
    prob.solve()
    weights = np.array(x.value)

此处x.value为空。我不确定如何修改我的上述设置。我正在尝试将 sims 的平均值重新调整为此处由变量 center 定义的不同值。

首先调试方式: 尝试使用它来查看问题所在:

prob.solve(verbose=True)

这是为了检查是否找到了解决方案:

print(prob.status)

在你的情况下,问题是不可行的,你试图解决的线性问题 - 并不总是有解决方案。您可以引入一个“eps”变量来定义您的问题所需的准确性,或者使用线性代数库提前测试是否存在某些解决方案。

在调用 prob.solve() 之后尝试访问变量值之前,请记住检查 prob.value 是否有限。由于你有一个最大化问题,并且 prob.value returns -inf (见下面的输出),这意味着你的问题是不可行的:

import sys, numpy as np
import cvxpy as cvx

if __name__ == '__main__':
    sims = np.random.randint(20, 30, size=500)
    center = 30
    n = [500, 1]

    # minimize     p'*log(p)
    # subject to
    #              sum(p) = 1
    #              sum(p'*a) = target1

    A = np.mat(np.vstack([np.ones(n[0]), sims]))
    b = np.mat([1.0, center]).T

    x = cvx.Variable(n)
    obj = cvx.Maximize(cvx.sum(cvx.entr(x)))
    constraints = [A @ x == b]
    prob = cvx.Problem(obj, constraints)
    prob.solve()
    print(prob.value)
    weights = np.array(x.value)

输出:

-inf

来自Variable values return 'None' after solving the problem

Diagnosing infeasibility issues is a common task when using optimization models in practice. Usually you will find either a bug in your code, or you will see that the abstract mathematical model can be infeasible (even if coded up perfectly).

为了快速参考您的抽象数学模型可能是如何不可行的,而不是代码中的错误,您可以尝试替换

constraints = [A @ x == b]

constraints = [A @ x >= b] # Outputs 183.9397...

或与

constraints = [A @ x <= b] # Outputs 6.2146...

您会发现您的代码有效。