การหาค่าที่เหมาะสมด้วย Scipy
เป็นไปได้ที่จะเขียนโซลูชันแบบ analytic ด้วย numpy เพื่อหาค่า RSS ที่น้อยที่สุด แต่สำหรับโมเดลที่ซับซ้อนกว่านี้ การหาสูตร analytic อาจทำไม่ได้ จึงต้องหันมาใช้วิธีอื่นแทน
ในแบบฝึกหัดนี้ จะใช้ scipy.optimize ซึ่งเป็นแนวทางที่ยืดหยุ่นกว่าในการแก้ปัญหาการหาค่าที่เหมาะสมแบบเดิม
ในระหว่างนั้น จะได้เห็นค่าที่ส่งคืนเพิ่มเติมจากเมธอดนี้ ซึ่งบอกว่า "ค่าที่ดีที่สุดนั้นดีแค่ไหน" โดยจะใช้ข้อมูลและพารามิเตอร์ชุดเดิมกับแบบฝึกหัดที่ผ่านมา เพื่อให้เปรียบเทียบกับแนวทางของ scipy ได้ง่ายขึ้น
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
Introduction to Linear Modeling in Python
คำแนะนำการฝึกหัด
- กำหนดฟังก์ชัน
model_func(x, a0, a1)ที่รับอาร์เรย์xและส่งคืนค่าa0 + a1*x - ใช้ฟังก์ชัน
optimize.curve_fit()ของscipyเพื่อคำนวณค่าที่เหมาะสมของa0และa1 - แตก
param_optออกมาเพื่อเก็บพารามิเตอร์โมเดลเป็นa0 = param_opt[0]และa1 = param_opt[1] - ใช้ฟังก์ชัน
compute_rss_and_plot_fitที่กำหนดไว้แล้วเพื่อทดสอบและตรวจสอบคำตอบ
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
# Define a model function needed as input to scipy
def model_func(x, a0, a1):
return ____ + (____*x)
# Load the measured data you want to model
x_data, y_data = load_data()
# call curve_fit, passing in the model function and data; then unpack the results
param_opt, param_cov = optimize.curve_fit(____, x_data, y_data)
a0 = param_opt[0] # a0 is the intercept in y = a0 + a1*x
a1 = param_opt[1] # a1 is the slope in y = a0 + a1*x
# test that these parameters result in a model that fits the data
fig, rss = compute_rss_and_plot_fit(____, ____)