• Python统计学11——分位数回归


    分位数回归也是数理统计里面经典的模型,他相对于在最小二乘模型上进行了改进,虽然本身还是线性的参数模型,但对损失函数进行了改进。我们都知道最小二乘的损失函数是均方误差最小,分位数的损失函数是:

    可以看到分位数损失函数会对高估的值和低估的值给予一个不同的权重,这样就可以做到‘’分位‘’。

    该模型对于存在异方差的数据有很好的的效果。能准确计算出5%~95%的置信区间

    具体看代码理解:

    导入包,加载自带的案例数据

    1. import numpy as np
    2. import pandas as pd
    3. import statsmodels.api as sm
    4. import statsmodels.formula.api as smf
    5. import matplotlib.pyplot as plt
    6. data = sm.datasets.engel.load_pandas().data
    7. data.head()

     

     X是收入,y是食物支出,很经典的发散数据,因为不同收入区间的家庭的食物支出比例不一样,随着X增大,Y的波动也增大。存在异方差。


    q=0.5时候的分位数回归

    1. mod = smf.quantreg("foodexp ~ income", data)
    2. res = mod.fit(q=0.5)
    3. print(res.summary())

     当q不一样是回归出来的系数是不一样的。我们计算0.05,0.15,0.25.....0.95分位数出来的回归系数,还有最小二乘的回归系数。

    1. quantiles = np.arange(0.05, 0.96, 0.1)
    2. def fit_model(q):
    3. res = mod.fit(q=q)
    4. return [q, res.params["Intercept"], res.params["income"]] + res.conf_int().loc["income"].tolist()
    5. models = [fit_model(x) for x in quantiles]
    6. models = pd.DataFrame(models, columns=["q", "a", "b", "lb", "ub"])
    7. ols = smf.ols("foodexp ~ income", data).fit()
    8. ols_ci = ols.conf_int().loc["income"].tolist()
    9. ols = dict(a=ols.params["Intercept"], b=ols.params["income"], lb=ols_ci[0], ub=ols_ci[1])
    10. print(models)
    11. print(ols)

     


    画图对比

    1. x = np.arange(data.income.min(), data.income.max(), 50)
    2. get_y = lambda a, b: a + b * x
    3. fig, ax = plt.subplots(figsize=(6, 4))
    4. for i in range(models.shape[0]):
    5. y = get_y(models.a[i], models.b[i])
    6. ax.plot(x, y, linestyle="dotted", color="grey")
    7. y = get_y(ols["a"], ols["b"])
    8. ax.plot(x, y, color="red", label="OLS")
    9. ax.scatter(data.income, data.foodexp, alpha=0.2)
    10. ax.set_xlim((200, 3000))
    11. ax.set_ylim((200, 2000))
    12. legend = ax.legend()
    13. ax.set_xlabel("Income", fontsize=16)
    14. ax.set_ylabel("Food expenditure", fontsize=16)

     透明蓝色散点为样本点。蓝色虚线为不同分位数上的回归方程。

    可以看出的几个结论:

    '''粮食支出随着收入的增加而增加

    粮食支出的分散度随着收入的增加而增加

    最小二乘估计值与低收入观测值的拟合度相当差(即OLS线越过大多数低收入家庭)'''

    而且5%~95%的回归方程区间涵盖了所有的真实样本点,置信区间很准确。


     画出回归系数随着分位数的变化图

    1. n = models.shape[0]
    2. plt.plot(models.q, models.b, color="black", label="Quantile Reg.")
    3. plt.plot(models.q, models.ub, linestyle="dotted", color="black")
    4. plt.plot(models.q, models.lb, linestyle="dotted", color="black")
    5. plt.plot(models.q, [ols["b"]] * n, color="red", label="OLS")
    6. plt.plot(models.q, [ols["lb"]] * n, linestyle="dotted", color="red")
    7. plt.plot(models.q, [ols["ub"]] * n, linestyle="dotted", color="red")
    8. plt.ylabel(r"$\beta_{income}$")
    9. plt.xlabel("Quantiles of the conditional food expenditure distribution")
    10. plt.legend()
    11. plt.show()

     

    #上图画出了回归系数随着分位数的变化而变化,OLS系数是恒定的,分位数回归的系数随着分位数变大而变大

    #在大多数情况下,分位数回归点估计值位于OLS置信区间之外,这表明收入对食品支出的影响在整个分布区间内可能不是恒定的

  • 相关阅读:
    css --- 让人上头的flex
    理解React Hooks看这一篇就够了
    SveletJs学习——Transition动画
    米家、涂鸦、Hilink、智汀等生态哪家强?5大主流智能品牌分析
    LaTex(1):使用在线表格生成器工具生成LaTex表格
    数据结构和算法:栈与队列
    kafka 生产者 API 实践总结
    MinIO (一)安装并生成windows服务
    智慧环卫管理系统解决方案(垃圾分类)
    【云原生】灰度发布、蓝绿发布、滚动发布、灰度发布解释
  • 原文地址:https://blog.csdn.net/weixin_46277779/article/details/126743129