We consider the following problem:
\[ \begin{align} &\underset{x}{\min}~c^Tx\\ &{\rm}\quad Ax\le b. \end{align} \]# Import packages.
import time
import cvxpy as cp
import numpy as np
import scipy.optimize as op
# Generate a random non-trivial linear program.
m = 4
n = 5
np.random.seed(1)
# CVXPY
s0 = np.random.randn(m)
lamb0 = np.maximum(-s0, 0)
s0 = np.maximum(s0, 0)
x0 = np.random.randn(n)
A = np.random.randn(m, n)
b = A @ x0 + s0
c = -A.T @ lamb0
# Define and solve the CVXPY problem.
x = cp.Variable(n)
prob = cp.Problem(cp.Minimize(c.T@x),
[A @ x <= b])
start_cvxpy = time.time()
prob.solve()
end_cvxpy = time.time()
# Print result.
print("\nThe optimal value is", prob.value)
print("A solution x is")
print(x.value)
print("Time taken by CVXPY:", end_cvxpy - start_cvxpy, "seconds")
The optimal value is -7.730756207394709
A solution x is
[ 1.40553474 -2.12212812 1.3661743 -0.22965191 -0.00562394]
Time taken by CVXPY: 0.0029897689819335938 seconds
result = op.linprog(c, A_ub=A, b_ub=b, method='highs')
result.x
array([3.35987094, 0. , 2.22818143, 0. , 0. ])
x0
array([ 0.86540763, -2.3015387 , 1.74481176, -0.7612069 , 0.3190391 ])
标签:CVXPY,s0,Python,random,SCIPY,np,import,cp
From: https://www.cnblogs.com/junshan/p/18558465