Least-Squares ด้วย `numpy`
สูตรด้านล่างนี้ได้มาจากการคำนวณแคลคูลัสที่กล่าวถึงในบทนำ ในแบบฝึกหัดนี้ เราจะเชื่อว่าแคลคูลัสถูกต้อง แล้วนำสูตรเหล่านี้มาเขียนโค้ดโดยใช้ numpy
$$ a_{1} = \frac{ covariance(x, y) }{ variance(x) } $$ $$ a_{0} = mean(y) - a_{1} mean(x) $$
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
Introduction to Linear Modeling in Python
คำแนะนำการฝึกหัด
- คำนวณค่าเฉลี่ยและค่าเบี่ยงเบนของตัวแปร
x, yจากข้อมูลที่โหลดไว้ล่วงหน้า - ใช้
np.sum()เพื่อคำนวณตามสูตร Least-Squares แล้วหาค่าที่เหมาะสมที่สุดของa0และa1 - ใช้
model()เพื่อสร้างค่าโมเดลy_modelจากค่าความชัน a1 และจุดตัดแกน a0 ที่ได้ - ใช้ฟังก์ชัน
compute_rss_and_plot_fit()ที่กำหนดไว้แล้ว เพื่อตรวจสอบด้วยภาพว่าโมเดลที่ได้นั้นพอดีกับข้อมูล
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
# prepare the means and deviations of the two variables
x_mean = np.____(x)
y_mean = np.____(y)
x_dev = x - ____
y_dev = y - ____
# Complete least-squares formulae to find the optimal a0, a1
a1 = np.sum(____ * ____) / np.sum( np.square(____) )
a0 = ____ - (a1 * ____)
# Use the those optimal model parameters a0, a1 to build a model
y_model = model(x, ____, ____)
# plot to verify that the resulting y_model best fits the data y
fig, rss = compute_rss_and_plot_fit(a0, a1)