開始使用免費開始

線性迴歸

我們將假設生育率是女性不識字率的線性函式。也就是說,$f = a i + b$,其中 \(a\) 是斜率、\(b\) 是截距。可以把截距視為最低生育率,可能介於 1 到 2 之間。斜率則告訴我們生育率隨不識字率如何變化。我們可以使用 np.polyfit() 找到最佳擬合直線。

請繪製資料點與最佳擬合直線,並列印斜率與截距。(想一想:它們的單位是什麼?)

本練習屬於課程

Statistical Thinking in Python(第 2 部分)

檢視課程

練習說明

  • 使用 np.polyfit() 計算迴歸線的斜率與截距。記得 fertility 在 y 軸、illiteracy 在 x 軸。
  • 列印線性迴歸得到的斜率與截距。
  • 若要繪製最佳擬合直線,先用 np.array() 建立由 0 和 100 組成的陣列 x。然後依照迴歸參數計算理論上的 y 值,也就是 y = a * x + b
  • 在同一張圖上同時繪製資料點與迴歸直線。記得替座標軸加上標籤。
  • 按下 Submit 以顯示你的圖表。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

# Plot the illiteracy rate versus fertility
_ = plt.plot(illiteracy, fertility, marker='.', linestyle='none')
plt.margins(0.02)
_ = plt.xlabel('percent illiterate')
_ = plt.ylabel('fertility')

# Perform a linear regression using np.polyfit(): a, b
a, b = ____

# Print the results to the screen
print('slope =', a, 'children per woman / percent illiterate')
print('intercept =', b, 'children per woman')

# Make theoretical line to plot
x = ____
y = ____ * ____ + ____

# Add regression line to your plot
_ = plt.plot(____, ____)

# Draw the plot
plt.show()
編輯並執行程式碼