對合適的 Anscombe 資料做線性迴歸
作為練習,請對 Anscombe 四重奏中最適合以線性迴歸解讀的資料集執行線性迴歸。
本練習屬於課程
Statistical Thinking in Python(第 2 部分)
練習說明
- 使用
np.polyfit()計算斜率與截距的參數。Anscombe 資料已存於陣列x與y。 - 列印斜率
a與截距b。 - 從線性迴歸產生理論上的 \(x\) 與 \(y\) 資料。你的 \(x\) 陣列可用
np.array()建立,並應包含3與15。若要產生 \(y\) 資料,將斜率乘上x_theor,再加上截距。 - 先將 Anscombe 資料畫成散佈圖,再畫出理論直線。記得在將 Anscombe 資料繪成散佈圖時,除了
x與y外,還要加入關鍵字引數marker='.'與linestyle='none'。繪製理論直線時不需要這些引數。 - 按下送出即可看到圖表!
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Perform linear regression: a, b
a, b = ____
# Print the slope and intercept
print(____, ____)
# Generate theoretical x and y data: x_theor, y_theor
x_theor = np.array([____, ____])
y_theor = ____ * ____ + ____
# Plot the Anscombe data and theoretical line
_ = ____
_ = ____
# Label the axes
plt.xlabel('x')
plt.ylabel('y')
# Show the plot
plt.show()