gpt4 book ai didi

python - cvxpy 正在解决产生空答案

转载 作者:行者123 更新时间:2023-12-04 07:28:56 25 4
gpt4 key购买 nike

我正在使用以下代码:

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.value在调用 prob.solve() 后尝试访问变量的值之前是有限的.由于您有一个最大化问题,而 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com