线性回归如何工作

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

Passons à la pratique !

Python 中级回归:使用 statsmodels

Preparing Video For Download...