量化模型拟合

使用 Python 中的 statsmodels 进行回归入门

Maarten Van den Broeck

Content Developer at DataCamp

鲷鱼与鲈鱼模型

鲷鱼 之前展示过的鲷鱼质量与长度的散点图及趋势线。

鲈鱼 之前展示过的鲈鱼质量与长度的散点图及趋势线。

使用 Python 中的 statsmodels 进行回归入门

判定系数

也称为"r 平方"或"R 平方"。

响应变量方差中可由解释变量预测的比例

  • 1 表示完美拟合
  • 0 表示最差拟合
使用 Python 中的 statsmodels 进行回归入门

.summary()

查看名为"R-Squared"的数值

mdl_bream = ols("mass_g ~ length_cm", data=bream).fit()
print(mdl_bream.summary())
# 部分输出省略                          

                            OLS Regression Results                         
Dep. Variable:                 mass_g   R-squared:                       0.878
Model:                            OLS   Adj. R-squared:                  0.874
Method:                 Least Squares   F-statistic:                     237.6
使用 Python 中的 statsmodels 进行回归入门

.rsquared 属性

print(mdl_bream.rsquared)
0.8780627095147174
使用 Python 中的 statsmodels 进行回归入门

只是相关系数的平方

coeff_determination = bream["length_cm"].corr(bream["mass_g"]) ** 2
print(coeff_determination)
0.8780627095147173
使用 Python 中的 statsmodels 进行回归入门

残差标准误(RSE)

鲷鱼质量与长度散点图的残差,如前所示

  • 预测与观测响应的"典型"差异
  • 与响应变量单位相同。
  • MSE = RSE²
使用 Python 中的 statsmodels 进行回归入门

.mse_resid 属性

mse = mdl_bream.mse_resid
print('mse: ', mse)
mse:  5498.555084973521
rse = np.sqrt(mse)
print("rse: ", rse)
rse:  74.15224261594197
使用 Python 中的 statsmodels 进行回归入门

计算 RSE:残差平方

residuals_sq = mdl_bream.resid ** 2

print("residuals sq: \n", residuals_sq)
residuals sq: 
0      138.957118
1      260.758635
2     5126.992578
3     1318.919660
4      390.974309
    ...
30    2125.047026
31    6576.923291
32     206.259713
33     889.335096
34    7665.302003
Length: 35, dtype: float64
使用 Python 中的 statsmodels 进行回归入门

计算 RSE:残差平方和

residuals_sq = mdl_bream.resid ** 2

resid_sum_of_sq = sum(residuals_sq)

print("resid sum of sq :",
      resid_sum_of_sq)
resid sum of sq : 181452.31780412616
使用 Python 中的 statsmodels 进行回归入门

计算 RSE:自由度

residuals_sq = mdl_bream.resid ** 2

resid_sum_of_sq = sum(residuals_sq)

deg_freedom = len(bream.index) - 2

print("deg freedom: ", deg_freedom)

自由度等于观测数减去模型系数数。

deg freedom:  33
使用 Python 中的 statsmodels 进行回归入门

计算 RSE:比值开方

residuals_sq = mdl_bream.resid ** 2

resid_sum_of_sq = sum(residuals_sq)

deg_freedom = len(bream.index) - 2

rse = np.sqrt(resid_sum_of_sq/deg_freedom)

print("rse :", rse)
rse : 74.15224261594197
使用 Python 中的 statsmodels 进行回归入门

解释 RSE

mdl_bream 的 RSE 为 74

预测的鲷鱼质量与观测质量通常相差约 74g。

使用 Python 中的 statsmodels 进行回归入门

均方根误差(RMSE)

residuals_sq = mdl_bream.resid ** 2

resid_sum_of_sq = sum(residuals_sq)

deg_freedom = len(bream.index) - 2

rse = np.sqrt(resid_sum_of_sq/deg_freedom)

print("rse :", rse)
rse : 74.15224261594197
residuals_sq = mdl_bream.resid ** 2

resid_sum_of_sq = sum(residuals_sq)

n_obs = len(bream.index)

rmse = np.sqrt(resid_sum_of_sq/n_obs)

print("rmse :", rmse)
rmse : 72.00244396727619
使用 Python 中的 statsmodels 进行回归入门

Passons à la pratique !

使用 Python 中的 statsmodels 进行回归入门

Preparing Video For Download...