開始使用免費開始

線性迴歸演算法

若要真正理解線性迴歸,了解演算法如何運作很有幫助。lm() 的程式碼有數百行,因為它必須能處理任何公式與任何資料集。不過,針對單一資料集的簡單線性迴歸,你其實只要用幾行程式碼就能實作一個線性迴歸演算法。

工作流程如下:

  1. 撰寫一段腳本來計算平方和。
  2. 將它包成一個函式。
  3. 使用 R 的通用最佳化函式,找出讓平方和最小的係數。

解釋變數(taiwan_real_estaten_convenience 欄)已提供為 x_actual。 應變數(taiwan_real_estateprice_twd_msq 欄)已提供為 y_actual

本練習屬於課程

R 的迴歸分析中級

檢視課程

動手互動練習

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

# Set the intercept to 10
intercept <- ___

# Set the slope to 1
slope <- ___

# Calculate the predicted y values
y_pred <- ___

# Calculate the differences between actual and predicted
y_diff <- ___

# Calculate the sum of squares
___
編輯並執行程式碼