我正在使用以下代码:
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()
后尝试访问变量值之前,请记住检查 prob.value
是否有限。由于您有一个最大化问题,并且 prob.value
返回 -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...
您将看到您的代码有效。
关于python - cvxpy 正在解决产生空答案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68059871/