開始使用免費開始

線性迴歸演算法

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

工作流程如下:

  • 首先,撰寫一個函式,使用以下通用語法來計算平方和:
def function_name(args):
  # some calculations with the args
  return outcome
  • 接著,使用 scipy 的 minimize 函式,找出讓此函式最小化的係數。

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

minimize() 也已載入。

本練習屬於課程

使用 Python 的 statsmodels 進行迴歸分析:中級

檢視課程

動手互動練習

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

# Complete the function
def calc_sum_of_squares(coeffs):
    # Unpack coeffs
    ____, ____ = ____
    # Calculate predicted y-values
    y_pred = ____ + ____ * ____
    # Calculate differences between y_pred and y_actual
    y_diff = ____ - ____
    # Calculate sum of squares
    sum_sq = ____
    # Return sum of squares
    return sum_sq
  
# Test the function with intercept 10 and slope 1
print(calc_sum_of_squares([10, 1]))
編輯並執行程式碼