線性迴歸怎麼運作

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

Maarten Van den Broeck

Content Developer at DataCamp

標準的簡單線性迴歸圖

帶有線性迴歸趨勢線的散佈圖。

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

殘差視覺化

帶有線性迴歸趨勢線的散佈圖,並從各點畫到趨勢線的線段,表示殘差。

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

最佳擬合的衡量指標

最簡單的想法(不可行)

  • 把所有殘差相加。
  • 有些殘差為負。

下一個更簡單的想法(可行)

  • 把每個殘差平方後加總。
  • 這稱為「平方和」。
使用 Python 的 statsmodels 進行迴歸分析:中級

數值最佳化小插曲

二次方程式的折線圖

x = np.arange(-4, 5, 0.1)
y = x ** 2 - x + 10

xy_data = pd.DataFrame({"x": x,
                        "y": y})

sns.lineplot(x="x",
             y="y",
             data=xy_data)

二次函數 y = x ** 2 - x + 10

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

用微積分解方程

$y = x ^ 2 - x + 10$

$\frac{\partial y}{\partial x} = 2 x - 1$

$0 = 2 x - 1$

$x = 0.5$

$y = 0.5 ^ 2 - 0.5 + 10 = 9.75$

  • 不是所有方程式都能這樣解。
  • 你可以讓 Python 幫你算。

如果這裡看不太懂也別擔心,做練習不需要用到。

前面的二次函數,已求出最小值

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

minimize()

from scipy.optimize import minimize
def calc_quadratic(x):
  y = x ** 2 - x + 10
  return y
minimize(fun=calc_quadratic,
         x0=3)
      fun: 9.75
 hess_inv: array([[0.5]])
      jac: array([0.])
  message: 'Optimization terminated successfully.'
     nfev: 6
      nit: 2
     njev: 3
   status: 0
  success: True
        x: array([0.49999998])
使用 Python 的 statsmodels 進行迴歸分析:中級

一個線性迴歸演算法

定義一個函式來計算平方和指標。

 

呼叫 minimize() 尋找讓此函式最小的係數。

def calc_sum_of_squares(coeffs):
  intercept, slope = coeffs
  # More calculation!
minimize(
  fun=calc_sum_of_squares,
  x0=0
)
使用 Python 的 statsmodels 進行迴歸分析:中級

一起來練習吧!

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

Preparing Video For Download...