为什么CVXPY中的求和会出现广播错误

why does summing in cvxpy will occur broadcasting error

提问人:user1155920 提问时间:11/2/2023 更新时间:11/2/2023 访问量:21

问:

我的代码有值错误的问题。它一直显示无法广播维度 (5,)(5,3)。我仍在学习如何使用 cvxpy,所以我找不到解决它的方法。问题出在“transportation_costs = cp.sum(cp.multiply(d, c) * x)”

import cvxpy as cp

# Given data
d = [80, 270, 250, 160, 180]
c = [[4, 5, 6, 8, 10],
     [6, 4, 3, 5, 8],
     [9, 7, 6, 3, 4]]
f = [1000, 1000, 1000]
M = [500, 500, 500]

# Variables
x = cp.Variable((3, 5), boolean=True)
y = cp.Variable(3, boolean=True)

# Objective
transportation_costs = cp.sum(cp.multiply(d, c) * x)
activation_costs = f @ y
cost = transportation_costs + activation_costs
# Constraints
constraints = [cp.sum(x, axis=0) == 1, 
               x <= cp.reshape(y, (3, -1)),
               cp.diag(d) @ x <= M * y]

# Problem
prob = cp.Problem(cp.Minimize(cost), constraints)
prob.solve()

print(f"Optimal cost: ${prob.value:.2f}")
print("x values:")
print(x.value)
print("y values:")
print(y.value)

# Disaggregated constraints
disaggregated_constraints = [d[i]*x[j,i] <= M[j]*y[j] for i in range(5) for j in range(3)]

# Problem with Disaggregated Constraints
prob_disaggregated = cp.Problem(cp.Minimize(cost), constraints[:-1] + disaggregated_constraints)
prob_disaggregated.solve()

print(f"Optimal cost with disaggregated constraints: ${prob_disaggregated.value:.2f}")
print("x values with disaggregated constraints:")
print(x.value)
print("y values with disaggregated constraints:")
print(y.value)`
Python 分析 建模 CVXPY

评论

0赞 Michal Adamaszek 11/2/2023
在参数中,具有不兼容的维度。cp.multiply(d, c) cd

答: 暂无答案