Linear programming

การหาค่าที่เหมาะสมที่สุดใน Python เบื้องต้น

Jasmin Ludolf

Content Developer

Linear programming

  • ฟังก์ชันวัตถุประสงค์และข้อจำกัดมีความสัมพันธ์เชิงเส้น

  • ต่างจากแบบผสม: ที่มีทั้งส่วนเชิงเส้นและไม่เชิงเส้น

การหาค่าที่เหมาะสมที่สุดใน Python เบื้องต้น

ส่วนผสมผลิตภัณฑ์

 

ประเภท จำนวน ขวด (ชม./กล่อง) ถ้วย (ชม./กล่อง)
$M_A$ 4 1.5 1.3
$M_B$ 3 0.8 2.1

 

  • เครื่องจักรแต่ละเครื่องทำงาน 30 ชั่วโมงต่อสัปดาห์

 

  • ความต้องการ: ขวดสำหรับเครื่องดื่ม, ถ้วยสำหรับโยเกิร์ต
การหาค่าที่เหมาะสมที่สุดใน Python เบื้องต้น

การสูงสุดกำไร

  • กำไรต่อกล่อง
B ($/กล่อง) C ($/กล่อง)
480 510

 

  • ฟังก์ชันวัตถุประสงค์: $480B + 510C$
  • ข้อจำกัด
    • เครื่อง A: $1.5B+1.3C\leq 4 \times 30$
    • เครื่อง B: $0.8B+ 2.1C \leq 3\times 30$
    • ข้อจำกัดไม่ติดลบ: $B, C \geq 0$
การหาค่าที่เหมาะสมที่สุดใน Python เบื้องต้น

การใช้ PuLP

from pulp import *


model = LpProblem('MaxProfit', LpMaximize)
B = LpVariable('B', lowBound=0) C = LpVariable('C', lowBound=0)
model += 480*B + 510*C
model += 1.5*B + 1.3*C - 120, "M_A" model += 0.8*B + 2.1*C - 90, "M_B"
  • LpMaximize หรือ LpMinimize
การหาค่าที่เหมาะสมที่สุดใน Python เบื้องต้น

ผลลัพธ์โมเดล PuLP

print(model)
ProductMix:
MAXIMIZE
480*B + 510*C + 0
SUBJECT TO
M_A: 1.5 B + 1.3 C <= 120

M_B: 0.8 B + 2.1 C <= 90

VARIABLES
B Continuous
C Continuous
การหาค่าที่เหมาะสมที่สุดใน Python เบื้องต้น

การแก้ปัญหาด้วย PuLP

status = model.solve()
print(status)
Welcome to the CBC MILP Solver 
...
1
print(f"Profit = {value(model.objective):.2f}")
print(f"Tons of bottles = {B.varValue:.2f}, tons of cups = {C.varValue:.2f}")
Profit = 40137.44
Boxes of bottles = 63.98, boxes of cups = 18.48
การหาค่าที่เหมาะสมที่สุดใน Python เบื้องต้น

การจัดการตัวแปรและข้อจำกัดหลายรายการ

variables = LpVariable.dicts("Product", ['B', 'C'], lowBound=0)

หรือ

variables = LpVariable.dicts("Product", range(2), 0)
A = LpVariable.matrix('A', (range(2), range(2)), 0)
box_profit = {'B': 480, 'C': 510}
model += lpSum([box_profit[i] * variables[i] for i in ['B', 'C']]) 

model += 1.5*variables['B'] + 1.3*variables['C'] <= 120, "M_A"
model += 0.8*variables['B'] + 2.1*variables['C'] <= 90, "M_B"
การหาค่าที่เหมาะสมที่สุดใน Python เบื้องต้น

มาฝึกกันเถอะ!

การหาค่าที่เหมาะสมที่สุดใน Python เบื้องต้น

Preparing Video For Download...