繪製自助法(bootstrap)迴歸
視覺化線性迴歸可能的變異性,一個不錯的做法是把每一次斜率與截距的自助法重抽樣複本所得到的迴歸線都畫出來。請對前 100 個斜率與截距的自助法複本(分別儲存在 bs_slope_reps 與 bs_intercept_reps)執行這個動作。
本練習屬於課程
Statistical Thinking in Python(第 2 部分)
練習說明
- 產生用來繪製迴歸線的 x 值陣列,只包含
0與100。請使用np.array()。 - 撰寫一個
for迴圈,在每次迭代中依照成對自助法複本的斜率與截距畫出一條迴歸線。總共畫100條線。- 在每次繪圖時,回想迴歸方程式
y = a*x + b。此處a是bs_slope_reps[i],b是bs_intercept_reps[i]。 - 在呼叫
plt.plot()時,指定關鍵字引數linewidth=0.5、alpha=0.2,以及color='red'。
- 在每次繪圖時,回想迴歸方程式
- 繪製散佈圖,x 軸為
illiteracy、y 軸為fertility。記得指定marker='.'與linestyle='none'這兩個關鍵字引數。 - 標示座標軸、設定 2% 邊界,並顯示圖表。這部分已為你完成,按下 Submit Answer 來視覺化這些自助法迴歸!
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Generate array of x-values for bootstrap lines: x
x = ____
# Plot the bootstrap lines
for i in range(____):
_ = plt.plot(____,
____*x + ____,
____=0.5, ____=0.2, ____='red')
# Plot the data
_ = ____
# Label axes, set the margins, and show the plot
_ = plt.xlabel('illiteracy')
_ = plt.ylabel('fertility')
plt.margins(0.02)
plt.show()