Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

การใช้ Nelder-Mead Algorithm ด้วย SciPy ใน Python

Nelder-Mead Algorithm (หรือ Downhill Simplex Method) เป็น Optimization Algorithm แบบไม่ใช้ Gradient (Derivative-free) เหมาะสำหรับ:

  • ฟังก์ชันที่ไม่ต่อเนื่อง (Discontinuous)
  • ฟังก์ชันที่มี Noise/Roughness สูง
  • ปัญหา Parameter Estimation และ Statistical Problems
  • Multidimensional Unconstrained Minimization

ข้อจำกัด: ช้าในการหา Optimal Gradient ไม่เหมาะสำหรับ High-dimensional Problems (มากกว่า ~20 มิติ) ควรใช้ Gradient-based Methods แทน (เช่น BFGS, L-BFGS-B)

ตัวอย่างโค้ด


import numpy as np
from scipy.optimize import minimize

def f(x):
    return 0.6 * (1 - x[0])**2

result = scipy.optimize.minimize(f, [2, -1], method="Nelder-Mead")
print(result)

ผลลัพธ์


final_simplex: (array([[ 1. , -1.27109375],
        [ 1. , -1.27118835],
        [ 1. , -1.27113762]]), array([0., 0., 0.]))
fun: 0.0
message: 'Optimization terminated successfully.'
nfev: 147
nit: 69
status: 0
success: True
x: array([ 1. , -1.27109375])

คำอธิบาย

  • นำเข้า NumPy และ minimize จาก scipy.optimize

  • กำหนดฟังก์ชัน目的 f(x) = 0.6(1 - x[0])² (ค่าต่ำสุดที่ x[0]=1)

  • เรียก minimize(f, x0, method="Nelder-Mead") โดย x0=[2, -1] เป็นจุดเริ่มต้น

  • ผลลัพธ์: success=True, x=[1.0, -1.27...], fun=0.0 (ค่าต่ำสุด)

พารามิเตอร์สำคัญของ minimize()

พารามิเตอร์คำอธิบาย
method'Nelder-Mead', 'BFGS', 'L-BFGS-B', 'SLSQP', 'COBYLA', 'trust-constr' ฯลฯ
boundsขอบเขตตัวแปร (สำหรับ L-BFGS-B, SLSQP)
constraintsเงื่อนไข (Equality/Inequality)
optionsmaxiter, xatol, fatol, disp ฯลฯ
callbackฟังก์ชันเรียกทุก iteration

เมื่อไหร่ควรใช้ Nelder-Mead?

  • ฟังก์ชันไม่มี Gradient หรือหา Gradient ยาก
  • มิติไม่สูง (< 20)
  • ฟังก์ชันมี Noise หรือไม่เรียบ
  • ไม่มี Constraint (Unconstrained)