1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

CVXPYを使ってみたという個人的なメモ書き

Posted at

CVXPYとは?

CVXPYとは線形計画問題を解くプログラムということらしい。
macではpipでインストールできる

pip install cvxpy

解きたい問題は以下の最適化問題を例に考える

線形計画問題
Maximize 70x1 + 30x2
subject to 5x1 + 2x2 ≤ 80,
2x1 + 3x2 ≤ 40,
3x1 + 7x2 ≤ 70,
x1≥0, x2≥0


これをコード化すると以下になる

cvxpy.py
import cvxpy as cp
x1, x2 = cp.Variable(), cp.Variable()
obj = cp.Maximize( (70 * x1) + (30 * x2) )
cons = [(5 * x1) + (2 * x2) <= 80,
               (2 * x1) + (3 * x2) <= 40,
               (3 * x1) + (7 * x2) <= 70,
                x1 >= 0,
                x2 >= 0]
P = cp.Problem(obj, cons)
P.solve(verbose=True)
print("x1 = ", x1.value)
print("x2 = ", x2.value)

実行結果

-----------------------------------------------------------------
           OSQP v0.6.0  -  Operator Splitting QP Solver
              (c) Bartolomeo Stellato,  Goran Banjac
        University of Oxford  -  Stanford University 2019
-----------------------------------------------------------------
problem:  variables n = 2, constraints m = 5
          nnz(P) + nnz(A) = 8
settings: linear system solver = qdldl,
          eps_abs = 1.0e-05, eps_rel = 1.0e-05,
          eps_prim_inf = 1.0e-04, eps_dual_inf = 1.0e-04,
          rho = 1.00e-01 (adaptive),
          sigma = 1.00e-06, alpha = 1.60, max_iter = 10000
          check_termination: on (interval 25),
          scaling: on, scaled_termination: off
          warm start: on, polish: on, time_limit: off

iter   objective    pri res    dua res    rho        time
   1  -1.8391e+02   5.70e-01   7.00e+01   1.00e-01   1.43e-04s
 200  -1.1273e+03   6.31e-04   6.57e-04   2.69e-02   5.30e-04s
plsh  -1.1273e+03   0.00e+00   3.57e-13   --------   8.38e-04s

status:               solved
solution polish:      successful
number of iterations: 200
optimal objective:    -1127.2727
run time:             8.38e-04s
optimal rho estimate: 2.73e-02

x1 =  14.545454545454547
x2 =  3.6363636363636362

解が出た。

まとめ

記述はめんどいけど線形計画問題を一発で解いてくれるのは嬉しいね。
(Qiitaの練習としてこの記事を書いています)

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?