最小化殘差
在這個練習中,你將完成一個函式,用來視覺化比較模型與資料,並計算與列印 RSS。你會多次呼叫它,觀察當你改變 a0 與 a1 時,RSS 如何變化。我們將看到,先前找到的那組參數值,正是可以「最小化」RSS 的解。
本練習屬於課程
Python 線性建模入門
練習說明
- 補上對
model()的呼叫,傳入資料xd與模型參數a0、a1。 - 將
rss計算為residuals的平方再加總。 - 針對不同的
a0與a1值,使用compute_rss_and_plot_fit(),看看 RSS 如何改變。 - 請確認原本的參數值
a0=150與a1=25可以最小化 RSS,並以這組數值送出答案。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Complete function to load data, build model, compute RSS, and plot
def compute_rss_and_plot_fit(a0, a1):
xd, yd = load_data()
ym = model(xd, ____, ____)
residuals = ym - yd
rss = np.sum(np.square(____))
summary = "Parameters a0={}, a1={} yield RSS={:0.2f}".format(____, ____, rss)
fig = plot_data_with_model(xd, yd, ym, summary)
return rss, summary
# Chose model parameter values and pass them into RSS function
rss, summary = compute_rss_and_plot_fit(a0=____, a1=____)
print(summary)