简体   繁体   中英

CVXPY: Constraint Violation

I'm attempting to solve an optimization program in cvxpy. The issues is that the answer it returns violates the basic constraint that it was given. I've run this program before with success and attempted to emulate the same code as before but this issue has me confused where I've gone wrong. Any help would be appreciated.

Optimization problem I'm trying to solve:

obj funct: maximize 0.1a1 + 0.1428a2 + 0.2a3
st 7a1 + 11a2 + 16a3 <= 80
a1, a2, a3 > =0, all integers

When I run the code below, it gives me a value of 5 for a1, a2, and a3 which violates the given constraint.

import cvxpy as cvx
import numpy as np
import scipy as sc
from scipy import linalg

#Define Starting Matrix
A1 = np.array([10,0,0])
A2 = np.array([0,7,0])
A3 = np.array([0,0,5])

#Optimal Basis and Inverse
B = np.array([A1, A2, A3])
print(f"B:{B}")
Binv = linalg.inv(B)
print(f"B-1:{Binv}")

#Define Cost Matrix
c = np.array([1, 1, 1])

#Optimal Dual Solution, y.hat
yhat = np.matmul(c,Binv)
print(f"y.hat:{yhat}")

#Pricing Problem
a = cvx.Variable(shape=(3,1), name="a")
w = np.array([[7,11,16]])

#Define Obj Function
objective2 = cvx.Maximize(cvx.matmul(yhat,a))

#Define Constraints
constraint2 = [
    cvx.matmul(a,w)<=80,
    a >=0
]

#Define Problem and Solve
knapsack = cvx.Problem(objective2, constraint2)
solution2 = knapsack.solve()
print(solution2)
print(a.value)

2.2142857137502494    
[[5.]    
 [5.]    
 [5.]]

Your dimensions are broken.

A matrix-multiplication with:

a = cvx.Variable(shape=(3,1), name="a")  # 3 x 1
w = np.array([[7,11,16]])                # 1 x 3

results in:

z = a * w      # 3 x 3

You can easily verify this:

print(cvx.matmul(a,w).shape)
# (3, 3)

You probably want to change your column-vector a to a row-vector a. This also implies a transpose for w (and your other expressions which i won't touch):

a = cvx.Variable(shape=(1,3), name="a")
w = np.array([7,11,16]]).transpose()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM