使用 `numpy` 進行最小平方法
以下公式是根據導論中討論的微積分推導而得。在這個練習中,我們先假設推導正確,並用 numpy 在程式碼中實作這些公式。
$$ a_{1} = \frac{ covariance(x, y) }{ variance(x) } $$ $$ a_{0} = mean(y) - a_{1} mean(x) $$
本練習屬於課程
Python 線性建模入門
練習說明
- 從預先載入的資料計算兩個變數
x, y的平均值與偏差。 - 使用
np.sum()完成最小平方法的公式,並用它們計算a0與a1的最佳值。 - 使用
model(),根據這些最佳的斜率 a1 與截距 a0,建立模型值y_model。 - 使用預先定義的
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)