具不等式限制的凸式限制最佳化

Python 最佳化入門

Jasmin Ludolf

Content Developer

角點解 vs. 內部解

  • Alexia 只有 5 小時的工作時間

$$ w\leq 5$$

  • 兩個限制:
    • 一天 24 小時
    • 工作 5 小時
  • 限制形成一個角點
  • 內部解不在交點

無差異曲線與限制。最佳效用的無差異曲線通過限制的交點。

Python 最佳化入門

具產能限制的製造商

  • 車廠在兩座廠 $A$、$B$ 生產同款車
    • 產量:$q_A$、$q_B$
    • 產能:$q_A\leq 90$、$q_B\leq 90$
    • 成本:$C_A(q)=3q$、$C_B(q)=3.5q$
  • 需求:
    • $P=120-Q$
  • 合約:
    • $Q\geq 92$
  • 目標最大化利潤:
    • $\displaystyle\max \Pi(q_A,q_B)$

汽車生產線

Python 最佳化入門

利潤最大化

  • 目標:
    • $\Pi = R-C$
      • $R = PQ$
Python 最佳化入門

利潤最大化

  • 目標:
    • $\Pi = R-C$
      • $R = PQ = (120-Q)Q $
Python 最佳化入門

利潤最大化

  • 目標:

    • $\Pi = R-C$
      • $R = PQ = (120-Q)Q=\left[120-(q_A+q_B)\right](q_A+q_B)$
      • $C=C_A+C_B=3q_A+3.5q_B$
  • 邊界

    • $0\leq q_A, q_B\leq 90$
  • 限制
    • $Q\geq92\Leftrightarrow 92\leq q_A+q_B$
Python 最佳化入門

問題表述

$$\max_{q_A,q_B}R(q_A,q_B)-C(q_A,q_B)$$

$$s.t.$$

$$R(q_A,q_B)=\left[120-(q_A+q_B)\right](q_A+q_B)$$

$$\ \ \ \ \ C(q_A,q_B)=3q_A+3.5q_B$$

$$\ \ \ 0\leq q_A, q_B\leq 90$$

$$ \ \ \ \ 92\leq q_A+q_B$$

from scipy.optimize import minimize,\
        Bounds, LinearConstraint


def R(q): return (120 - (q[0] + q[1] )) * (q[0] + q[1])
def C(q): return 3*q[0] + 3.5*q[1]
def profit(q): return R(q) - C(q)
bounds = Bounds([0, 0], [90, 90])
constraints = LinearConstraint([1, 1], lb=92)
Python 最佳化入門

用 SciPy 最大化利潤

result = minimize(lambda q: -profit(q),

[50, 50],
bounds=bounds, constraints=constraints)
print(result.message) print(f'The optimal number of cars produced in plant A is: {result.x[0]:.2f}') print(f'The optimal number of cars produced in plant B is: {result.x[1]:.2f}') print(f'The firm made: ${-result.fun:.2f}')
Optimization terminated successfully
The optimal number of cars produced in plant A is: 90.00
The optimal number of cars produced in plant B is: 2.00
The firm made: $2299.00
Python 最佳化入門

SciPy 的非線性限制

from scipy.optimize import NonlinearConstraint 
import numpy as np


constraints = NonlinearConstraint(lambda q: q[0] + q[1], lb=92, ub=np.inf)
result = minimize(lambda q: -profit(q), [50, 50], bounds=Bounds([0, 0], [90, 90]), constraints=constraints)
Python 最佳化入門

使用 NonlinearConstraint 的解

print(result.message)
print(f'The optimal number of cars produced in plant A is: {result.x[0]:.2f}')
print(f'The optimal number of cars produced in plant B is: {result.x[1]:.2f}')
print(f'The firm made: ${-result.fun:.2f}') 
Optimization terminated successfully
The optimal number of cars produced in plant A is: 90.00
The optimal number of cars produced in plant B is: 2.00
The firm made: $2299.00 
  • 直線性問題用 LinearConstraint()
  • 其他情況用 NonlinearConstraint()
Python 最佳化入門

一起來練習吧!

Python 最佳化入門

Preparing Video For Download...