-
2021-01-17 16:51:44
第15章 分位数回归模型
15.1 总体分位数位数
15.位数的估计
.3 分位数回归
.4 分位数回归模型的估计
.5 分位数回归模型的
15.6 分位数的计算分位数回归的
15.7 分位数回归的
以往回归模型是研究被解释变量的条件期望。人们解释变量被解释变量分布的。就是分位数回归,它最早由Koenker和Bassett(1978)提出,是估计一回归变量X与被解释变量Y的分位数之间线性关系的建模方法。正如普通最小二乘OLS回归估计量的计算是基于残差平方一样,分位数回归估计量的计算是基于一种非对称形式的绝对值残差,,中位数回归运用的是最小绝对值离差估计(LADleast absolute deviations estimator)。它和OLS主要区别在于数估计方法和渐近分布的估计在残差检验、数检验、模型设定、预测等方面基本相同。
分位数回归的优点是,能够更加全面的描述被解释变量条件分布的全貌,而不是仅仅分析被解释变量条件期望均值,可以分析解释变量如何影响被解释变量的中位数、分位数等。不同分位数下的数估计量不同,即解释变量对不同水平被解释变量的影响不同。另外,中位数回归与最小二乘法相比,对离群值表现的更加稳健且,分位数回归并不要求很强的假设条件,因此对于分布分位数回归数估计更加稳健。15.1 总体分位数位数
分位数位数对一个连续随机变量y,其总体τ分位数是τ)的义是:y小于等于τ)的概率是τ即
τ = P( y ≤ y(τ)) = F(y(τ))
其中PF(y(τ)) 表示y的累积分布函数(cdf)。比如0.25) = 3,意味着y ≤ 3的概率是0.5。且有
τ) = F-1(y(τ))
即F(y(τ))的反函数是y(τ)。当τ=0.5时τ) 是y的中位数τ= 0.75时τ) 是y的第3/4分位数,τ= 0.25时τ) 是y的第1/4分位数。正态分布,0.5) = 0,0.95) =1.645,0.975) =1.960。
另外,如果随机变量的分布是对称的,那么均值与中位数是相同的。当中位数小于均值,分布是右偏的反之分布是左偏的。
对于回归模型,被解释变量yt对X为条件的τ分位数用函数τ)t(X表示,其含义是:以X为条件的yt小于等于τ)t(X的概率是τ这里的概率是用yt对X的条件分布计算的。且有
τ)t(X = F-1(y(τ)t(X)
其中F(τ)t(X) 是yt给定X的累积概率分布函数(cdf)。则τ)t(X称作被解释变量yt对X的条件分位数函数。而F '(τ)t(X)= f (y(τ)t(X)则称作分位数概率密度函数。其中F'(τ)t(X)表示F(y(τ)t(X)对y(τ)t(X求导。
15.2 总体中位数的估计
y表示,其概率密度函数用f(y)表示,累计概率密度函数用F(y)表示,y的中位数用y(0.5)表示,则y与任一值(的离差绝对值的期望以( = y(0.5) 时为最小。
证明:
=
= (15.1)
根据莱布尼兹公式,若,则有。令,则有。运用于式(15.1),得
==
=
式(15.1)求极小的一阶条件是= 0,即=0,。这意味着(等于中位数y0.5)。
( = y(0.5)
与定理15.1等价的表述是以( = y(0.5)(中位数)时为最小。因此,中位数回归yt = X (( + ut,通过求最小,估计(的中位数回归,从而得到yt的中位数回归。
15.3 分位数回归
Koenker和Bassett(1978)表示yt的分位数回归yt 对任意值(的加权离差绝对值和只有在( =时取得最小值。其中
= (15.2)
(((0, 1)。据此,分位数回归yt = X (( + ut, 求第(分位数回归的方法是求下式(目标函数)最小,
(15.3)
其中表示第(分位数回归位数回归=
其中X,(都是k(1阶列向量。称作分位数回归
=称作中位数回归称作中位数回归数位数回归位数回归。
-
对一个样本,估计的分位数回归yt条件分布的理解就越充分。以一元回归为例,如果用LAD法估计的中位数回归回归yt的分布是非对称的。如果散点图上侧分位数回归直线之间与下侧分位数回归直线之间相比,相互比较接近,则说明被解释变量yt的分布是左偏倚的。反之是右偏倚的。对于不同分位数回归函数如果回归系数的差异很大,说明在不同分位数上解释变量对被解释变量
更多相关内容 -
基于神经网络分位数回归及核密度估计的概率密度预测方法
2020-01-15 10:03:46基于神经网络分位数回归及核密度估计的概率密度预测方法,闻才喜,何耀耀,本文引入神经网络分位数回归和核密度估计方法,把神经网络强大的非线性自适应能力及分位数回归能更加细致刻画解释变量的优点结合 -
基于深度学习分位数回归模型的风电功率概率密度预测
2021-01-12 19:02:21针对风电功率预测问题,在现有预测方法和概率性区间预测的基础上,提出基于深度学习分位数回归的风电功率概率预测方法。该方法采用Adam随机梯度下降法在不同分位数条件下对长短期记忆神经网络(LSTM)的输入、遗忘、... -
分位数回归(quantile regression)简介和代码实现
2021-11-01 09:04:07这种理论也可以在预测统计中为我们服务,这正是分位数回归的意义所在——估计中位数(或其他分位数)而不是平均值。 通过选择任何特定的分位数阈值,我们既可以缓和异常值,也可以调整错误的正/负权衡。我们还可以...普通最小二乘法如何处理异常值? 它对待一切事物都是一样的——它将它们平方! 但是对于异常值,平方会显著增加它们对平均值等统计数据的巨大影响。
我们从描述性统计中知道,中位数对异常值的鲁棒性比均值强。 这种理论也可以在预测统计中为我们服务,这正是分位数回归的意义所在——估计中位数(或其他分位数)而不是平均值。 通过选择任何特定的分位数阈值,我们既可以缓和异常值,也可以调整错误的正/负权衡。我们还可以处理需要分位数界限的情况,例如:婴儿的安全出生体重,顶级竞技电子竞技玩家的技能水平,等等。
什么是分位数?
分位数(Quantile),亦称分位点,是指将一个随机变量的概率分布范围分为几个等份的数值点,常用的有中位数(即二分位数)、四分位由3个部分组成(第25、50和75个百分位,常用于箱形图)和百分位数等。
什么是分位数回归?
分位数回归是简单的回归,就像普通的最小二乘法一样,但不是最小化平方误差的总和,而是最小化从所选分位数切点产生的绝对误差之和。 如果 q=0.50(中位数),那么分位数回归会出现一个特殊情况 - 最小绝对误差(因为中位数是中心分位数)。我们可以通过调整超参数 q,选择一个适合平衡特定于需要解决问题的误报和漏报的阈值。
statsmodels中的分位数回归
分位数回归是一种不太常见的模型,但 Python中的StatsModel库提供了他的实现。这个库显然受到了R的启发,并从它借鉴了各种语法和API。
StatsModel使用的范例与scikit-learn稍有不同。但是与scikit-learn一样,对于模型对象来说,需要公开一个.fit()方法来实际训练和预测。但是不同的是scikit-learn模型通常将数据(作为X矩阵和y数组)作为.fit()的参数,而StatsModel是在初始化对象时传入数据,而fit方法只传递一些可以调试的超参数。
下面是来自statsmodel的例子(Engel数据集包含在与statmodels中)
%matplotlib inline import numpy as np import pandas as pd import statsmodels.api as sm import statsmodels.formula.api as smf import matplotlib.pyplot as plt data = sm.datasets.engel.load_pandas().data mod = smf.quantreg("foodexp ~ income", data) res = mod.fit(q=0.5) print(res.summary())
我们可以看看quantile regression model fit的帮助文档:
help(quant_mod.fit)
分位数回归与线性回归
标准最小二乘回归模型仅对响应的条件均值进行建模,并且计算成本较低。 相比之下,分位数回归最常用于对响应的特定条件分位数进行建模。 与最小二乘回归不同,分位数回归不假设响应具有特定的参数分布,也不假设响应具有恒定方差。
下表总结了线性回归和分位数回归之间的一些重要区别:
xgboost的分位数回归
最后如果想使用xgboost,又想试试分位数回归,那么可以参考以下代码
class XGBQuantile(XGBRegressor): def __init__(self,quant_alpha=0.95,quant_delta = 1.0,quant_thres=1.0,quant_var =1.0,base_score=0.5, booster='gbtree', colsample_bylevel=1, colsample_bytree=1, gamma=0, learning_rate=0.1, max_delta_step=0,max_depth=3, min_child_weight=1, missing=None, n_estimators=100, n_jobs=1, nthread=None, objective='reg:linear', random_state=0,reg_alpha=0, reg_lambda=1, scale_pos_weight=1, seed=None,silent=True, subsample=1): self.quant_alpha = quant_alpha self.quant_delta = quant_delta self.quant_thres = quant_thres self.quant_var = quant_var super().__init__(base_score=base_score, booster=booster, colsample_bylevel=colsample_bylevel, colsample_bytree=colsample_bytree, gamma=gamma, learning_rate=learning_rate, max_delta_step=max_delta_step, max_depth=max_depth, min_child_weight=min_child_weight, missing=missing, n_estimators=n_estimators, n_jobs= n_jobs, nthread=nthread, objective=objective, random_state=random_state, reg_alpha=reg_alpha, reg_lambda=reg_lambda, scale_pos_weight=scale_pos_weight, seed=seed, silent=silent, subsample=subsample) self.test = None def fit(self, X, y): super().set_params(objective=partial(XGBQuantile.quantile_loss,alpha = self.quant_alpha,delta = self.quant_delta,threshold = self.quant_thres,var = self.quant_var) ) super().fit(X,y) return self def predict(self,X): return super().predict(X) def score(self, X, y): y_pred = super().predict(X) score = XGBQuantile.quantile_score(y, y_pred, self.quant_alpha) score = 1./score return score @staticmethod def quantile_loss(y_true,y_pred,alpha,delta,threshold,var): x = y_true - y_pred grad = (x<(alpha-1.0)*delta)*(1.0-alpha)- ((x>=(alpha-1.0)*delta)& (x<alpha*delta) )*x/delta-alpha*(x>alpha*delta) hess = ((x>=(alpha-1.0)*delta)& (x<alpha*delta) )/delta grad = (np.abs(x)<threshold )*grad - (np.abs(x)>=threshold )*(2*np.random.randint(2, size=len(y_true)) -1.0)*var hess = (np.abs(x)<threshold )*hess + (np.abs(x)>=threshold ) return grad, hess @staticmethod def original_quantile_loss(y_true,y_pred,alpha,delta): x = y_true - y_pred grad = (x<(alpha-1.0)*delta)*(1.0-alpha)-((x>=(alpha-1.0)*delta)& (x<alpha*delta) )*x/delta-alpha*(x>alpha*delta) hess = ((x>=(alpha-1.0)*delta)& (x<alpha*delta) )/delta return grad,hess @staticmethod def quantile_score(y_true, y_pred, alpha): score = XGBQuantile.quantile_cost(x=y_true-y_pred,alpha=alpha) score = np.sum(score) return score @staticmethod def quantile_cost(x, alpha): return (alpha-1.0)*x*(x<0)+alpha*x*(x>=0) @staticmethod def get_split_gain(gradient,hessian,l=1): split_gain = list() for i in range(gradient.shape[0]): split_gain.append(np.sum(gradient[:i])/(np.sum(hessian[:i])+l)+np.sum(gradient[i:])/(np.sum(hessian[i:])+l)-np.sum(gradient)/(np.sum(hessian)+l) ) return np.array(split_gain)
https://gist.github.com/benoitdescamps/af5a8e42d5cfc7981e960e4d559dad19#file-xgboostquantile-py
对于LightGBM这里有一篇详细的实现文章:
http://jmarkhou.com/lgbqr/
-
基于EWT和分位数回归森林的短期风电功率概率密度预测
2021-01-12 20:16:33概率密度预测能够给出未来风电功率可能的波动范围、预测值出现的概率及不确定性等更多信息,提出基于经验小波变换(EWT)和分位数回归森林的短期风电功率概率密度组合预测模型。首先,采用新型自适应信号处理方法——... -
基于RBF 神经网络分位数回归的概率密度预测方法
2018-04-19 15:55:31针对电力系统短期负荷预测问题,在现有的组合预测和概率性区间预测的基础上,提出了基于RBF 神经网络分位数回归的概率密度预测方法,得出未来一天中任意时期负 荷的概率密度函数,可以得到比点预测和区间预测更多的... -
python中的分位数回归(初探)
2021-11-08 16:04:17分位数回归 参考文献 Python statsmodels 介绍 - 树懒学堂 (shulanxt.com) Quantile Regression - IBM Documentation https://www.cnblogs.com/TMesh/p/11737368.html 传统的线性回归模型 其的求解方式是一个最小...分位数回归
参考文献
Python statsmodels 介绍 - 树懒学堂 (shulanxt.com)
Quantile Regression - IBM Documentation
https://www.cnblogs.com/TMesh/p/11737368.html
传统的线性回归模型
其的求解方式是一个最小二乘法,保证观测值与你的被估值的差的平方和应该保持最小,
M S E = 1 n ∑ i = 1 n ( y i − f ^ ( x i ) ) 2 = E ( y − f ^ ( x ) ) 2 MSE\ =\ \frac{1}{n}\sum_{i=1}^n{\left( y_i-\widehat{f}\left( x_i \right) \right) ^2\ =\ E\left( y-\widehat{f}\left( x \right) \right)}^2 MSE = n1i=1∑n(yi−f (xi))2 = E(y−f (x))2- 因变量的条件均值分布受自变量x的影响过程,因此我们拟合出来的曲线是在给定x的情况下,y的条件均值
- 随机误差项来均值为0、同方差,因此估计的斜率在现有的基础上是最好的
分位数回归
- 首先提出中位数回归(最小绝对偏差估计)
- 改进出分位数回归
- 描述自变量X对因变量Y的变化范围,以及其不受分布形状的影响。即其不止可以描述条件均值的影响,还可以描述中位数的影响
因此我们能够得到如下的一个损失函数
Q Y ^ ( τ ) = a r g min ξ r ∈ R ( ∑ i : Y i ≥ ξ t a u τ ∣ Y i − ξ r ∣ + ∑ i : Y i < ξ t a u ( 1 − τ ) ∣ Y i − ξ r ∣ ) \widehat{Q_Y}\left( \tau \right) =arg\min _{\xi _{r\in R}}\left( \sum_{i:Y_i\ge \xi _{t^{au}}}{\tau \left| Y_i-\xi _r \right|}+\sum_{i:Y_i<\xi _{t^{au}}}{\left( 1-\tau \right) \left| Y_i-\xi _r \right|} \right) QY (τ)=argξr∈Rmin⎝⎛i:Yi≥ξtau∑τ∣Yi−ξr∣+i:Yi<ξtau∑(1−τ)∣Yi−ξr∣⎠⎞
参数 τ \tau τ的估计算法有:- 单纯形算法
- 内点算法
- 平滑算法
总结来说,在我心目中,分位数回归是对传统回归的一种改进,它不在局限于原来最小二乘法,使得数据可以更多影响其他的点或者类似于中位数的影响。
接下来我们将采用python语言进行实现,采用的数据集是我们之前的文章中cpu—time_tamp的数据
class QuantileRegression: def __init__(self,data): # self.data = pd.DataFrame(data=np.hstack([time_stamp,cpu_util_percent]),columns=["time_stamp","cpu_util_percent"]) self.data = data # self.num = len(time_stamp) pass def __QuantileReq_1__(self): # 主义这里,前面是Y轴,后面是X轴 mod = smf.quantreg('cpu_util_percent~time_stamp',self.data) print(mod) res = mod.fit() print(res) fig = plt.subplots(figsize=(8, 6)) # x = np.arange(self.data.time_stamp.min(),self.data.time_stamp.max(),1000) print(res.summary())
数据解释:
-
Dep. Variable :因变量
-
Model:方法模块
-
Method:方法(最小二乘法)默认使用迭代加权最小二乘法(IRLS)
-
Date:日期
-
Time:时间
-
Pseudo R-squared: 拟合优度
采用的公式为:
R q 2 = 1 − ∑ i = 1 n ρ q ( y i − x i ′ β ) ∑ i = 1 n ρ q ( y i − y q ) R_{q}^{2}=1-\frac{\sum_{i=1}^{n} \rho_{q}\left(y_{i}-x_{i}^{\prime} \beta\right)}{\sum_{i=1}^{n} \rho_{q}\left(y_{i}-y_{q}\right)} Rq2=1−∑i=1nρq(yi−yq)∑i=1nρq(yi−xi′β) -
Bandwidth:窗宽h
公式来源于:
当 y i > x i ′ β , d i = [ q f ( 0 ) ] 2 , 当 y i ≤ x i ′ β , d i = [ 1 − q f ( 0 ) ] 2 f ( 0 ) 的估计为 f ( 0 ) ~ = 1 n ∑ i = 1 n 1 h K [ e i h ] 当 y_{i}>x_{i}^{\prime} \beta , d_{i}=\left[\frac{q}{f(0)}\right]^{2} , 当 y_{i} \leq x_{i}^{\prime} \beta , d_{i}=\left[\frac{1-q}{f(0)}\right]^{2} f(0)_{\text {的估计为 }} \tilde{f(0)}=\frac{1}{n} \sum_{i=1}^{n} \frac{1}{h} K\left[\frac{e_{i}}{h}\right] 当yi>xi′β,di=[f(0)q]2,当yi≤xi′β,di=[f(0)1−q]2f(0)的估计为 f(0)~=n1i=1∑nh1K[hei]其 中 , f ( 0 ) 的估计为 f ( 0 ) ~ = 1 n ∑ i = 1 n 1 h K [ e i h ] 其 中 e i = y i − x i ′ β , K [ ] 表 示 为 核 函 数 其中, f(0)_{\text {的估计为 }} \tilde{f(0)}=\frac{1}{n} \sum_{i=1}^{n} \frac{1}{h} K\left[\frac{e_{i}}{h}\right] 其中e_i=y_i-x_{i}^{'}\beta ,K[]表示为核函数 其中,f(0)的估计为 f(0)~=n1i=1∑nh1K[hei]其中ei=yi−xi′β,K[]表示为核函数
-
Sparsity
-
No. Observations:
-
Df Residuals :Df残差
-
Df Model
-
coef:系数
-
std err:协方差(标准差)
采用以下公式得到:
E s t . A s y . Var [ β q ] = ( X ′ X ) − 1 X ′ D X ( X ′ X ) − 1 Est. Asy.\operatorname{Var}\left[\beta_{q}\right]=\left(X^{\prime} X\right)^{-1} X^{\prime} D X\left(X^{\prime} X\right)^{-1} Est.Asy.Var[βq]=(X′X)−1X′DX(X′X)−1 其中D为对角矩阵, -
t:统计量,表示为 β ~ V a r ~ ( β ) \dfrac{\widetilde{\beta }}{Va\tilde{r}}\left( \beta \right) Var~β (β)
-
P>|t|
-
[0.025 0.975]
-
Intercept:截距
-
cpu_util_percent : 斜率
但在多次实验的过程中,发现一直报过时未收敛的警告,所以我查看了源代码,最终我们怀疑python的分位数回归可能不太适用于曲线回归,可能只能分段式线性回归比较合适,以下是源代码的部分
#!/usr/bin/env python ''' Quantile regression model Model parameters are estimated using iterated reweighted least squares. The asymptotic covariance matrix estimated using kernel density estimation. Author: Vincent Arel-Bundock License: BSD-3 Created: 2013-03-19 The original IRLS function was written for Matlab by Shapour Mohammadi, University of Tehran, 2008 (shmohammadi@gmail.com), with some lines based on code written by James P. Lesage in Applied Econometrics Using MATLAB(1999).PP. 73-4. Translated to python with permission from original author by Christian Prinoth (christian at prinoth dot name). ''' import numpy as np import warnings import scipy.stats as stats from numpy.linalg import pinv from scipy.stats import norm from statsmodels.tools.decorators import cache_readonly from statsmodels.regression.linear_model import (RegressionModel, RegressionResults, RegressionResultsWrapper) from statsmodels.tools.sm_exceptions import (ConvergenceWarning, IterationLimitWarning) [docs]class QuantReg(RegressionModel): # 计算回归系数及其协方差矩阵。q是分位数,vcov是协方差矩阵,默认robust即2.5的方法,核函数kernel默认 # epa,窗宽bandwidth默认hsheather.IRLS最大迭代次数默认1000,差值默认小于1e-6时停止迭代 '''Quantile Regression 使用迭代加权最小二乘法估计分位数回归模型。 Estimate a quantile regression model using iterative reweighted least squares. Parameters ---------- endog : array or dataframe 数据/数据帧 endogenous/response variable 内源性/响应变量 exog : array or dataframe exogenous/explanatory variable(s) 外生/解释变量(s) Notes ----- The Least Absolute Deviation (LAD) estimator is a special case where quantile is set to 0.5 (q argument of the fit method). 最小绝对偏差(LAD)估计量是一种特殊情况 Quantile被设置为0.5 (fit方法的q参数)。 The asymptotic covariance matrix is estimated following the procedure in Greene (2008, p.407-408), using either the logistic or gaussian kernels (kernel argument of the fit method). 在此基础上,对渐近协方差矩阵进行了估计 格林(2008,p.407-408),使用logistic或高斯核 (拟合方法的核心参数)。 References ---------- General: * Birkes, D. and Y. Dodge(1993). Alternative Methods of Regression, John Wiley and Sons. * Green,W. H. (2008). Econometric Analysis. Sixth Edition. International Student Edition. * Koenker, R. (2005). Quantile Regression. New York: Cambridge University Press. * LeSage, J. P.(1999). Applied Econometrics Using MATLAB, * Birkes, D.和Y. Dodge(1993)。回归的可选方法,约翰·威利和儿子。 * Green,W。h(2008)。计量经济学分析。第六版。国际学生版。 * Koenker, R.(2005)。分位数回归。纽约:剑桥大学出版社。 * LeSage J. P.(1999)。应用计量经济学 Kernels (used by the fit method): * Green (2008) Table 14.2 Bandwidth selection (used by the fit method): * Bofinger, E. (1975). Estimation of a density function using order statistics. Australian Journal of Statistics 17: 1-17. * Chamberlain, G. (1994). Quantile regression, censoring, and the structure of wages. In Advances in Econometrics, Vol. 1: Sixth World Congress, ed. C. A. Sims, 171-209. Cambridge: Cambridge University Press. * Hall, P., and S. Sheather. (1988). On the distribution of the Studentized quantile. Journal of the Royal Statistical Society, Series B 50: 381-391. Keywords: Least Absolute Deviation(LAD) Regression, Quantile Regression, Regression, Robust Estimation. * Bofinger E.(1975)。使用顺序统计量估计密度函数。澳大利亚统计杂志17:1-17。 *张伯伦,G.(1994)。分位数回归、审查和工资结构。《计量经济学进展》,第1卷:第六届世界大会,c.a.西姆斯编,171-209。剑桥:剑桥大学出版社。 * Hall, P.和S. Sheather。(1988)。研究分位数的分布。皇家统计学会学报,B辑50:381-391。 关键词:最小绝对偏差回归分位数回归 回归,稳健估计。 ''' # 初始化 def __init__(self, endog, exog, **kwargs): self._check_kwargs(kwargs) super(QuantReg, self).__init__(endog, exog, **kwargs) [docs] def whiten(self, data): """ QuantReg model whitener does nothing: returns data. QuantReg模型增白器什么也不做:返回数据。 """ return data [docs] def fit(self, q=.5, vcov='robust', kernel='epa', bandwidth='hsheather', max_iter=1000, p_tol=1e-6, **kwargs): """ Solve by Iterative Weighted Least Squares 用迭代加权最小二乘法求解 Parameters ---------- q : float Quantile must be strictly between 0 and 1 vcov : str, method used to calculate the variance-covariance matrix of the parameters. Default is ``robust``: - robust : heteroskedasticity robust standard errors (as suggested in Greene 6th edition) - iid : iid errors (as in Stata 12) q:浮动型小数 分位数必须严格在0和1之间 vcoc:str,用于计算方差-协方差矩阵的参数方法。默认是“robust”: -robust:异方差鲁棒性标准误差(如在格林第六版中的建议) - iid: iid错误(如Stata 12) kernel : str, kernel to use in the kernel density estimation for the asymptotic covariance matrix: Kernel: str,用于核密度估计的渐近协方差矩阵的核: - epa: Epanechnikov - cos: Cosine 余旋 - gau: Gaussian 高斯 - par: Parzene bandwidth : str, Bandwidth selection method in kernel density estimation for asymptotic covariance estimate (full references in QuantReg docstring): bandwidth: str,渐近协方差估计核密度估计中的带宽选择方法(完整参考QuantReg文档字符串): - hsheather: Hall-Sheather (1988) - bofinger: Bofinger (1975) - chamberlain: Chamberlain (1994) """ if q <= 0 or q >= 1: raise Exception('q must be strictly between 0 and 1') kern_names = ['biw', 'cos', 'epa', 'gau', 'par'] if kernel not in kern_names: raise Exception("kernel must be one of " + ', '.join(kern_names)) else: kernel = kernels[kernel] if bandwidth == 'hsheather': bandwidth = hall_sheather elif bandwidth == 'bofinger': bandwidth = bofinger elif bandwidth == 'chamberlain': bandwidth = chamberlain else: raise Exception("bandwidth must be in 'hsheather', 'bofinger', 'chamberlain'") #endog样本因变量,exog样本自变量 endog = self.endog exog = self.exog nobs = self.nobs exog_rank = np.linalg.matrix_rank(self.exog) self.rank = exog_rank self.df_model = float(self.rank - self.k_constant) self.df_resid = self.nobs - self.rank #IRLS初始化 n_iter = 0 xstar = exog beta = np.ones(exog.shape[1]) # TODO: better start, initial beta is used only for convergence check # 待办事项:更好的开始,初始测试版仅用于收敛检查 # Note the following does not work yet, # the iteration loop always starts with OLS as initial beta # if start_params is not None: # if len(start_params) != rank: # raise ValueError('start_params has wrong length') # beta = start_params # else: # # start with OLS # beta = np.dot(np.linalg.pinv(exog), endog) """ #注意以下内容还不能使用, 迭代循环总是以OLS作为初始测试开始 #如果start_params不是None: # if len(start_params) != rank: #引发ValueError('start_params has wrong length') # beta = start_params 其他: # #从OLS开始 # beta = np.dot(np. linalgr .pinv(exog), endog) """ diff = 10 cycle = False history = dict(params = [], mse=[]) #IRLS迭代 while n_iter < max_iter and diff > p_tol and not cycle: n_iter += 1 beta0 = beta xtx = np.dot(xstar.T, exog) xty = np.dot(xstar.T, endog) beta = np.dot(pinv(xtx), xty) resid = endog - np.dot(exog, beta) mask = np.abs(resid) < .000001 resid[mask] = ((resid[mask] >= 0) * 2 - 1) * .000001 resid = np.where(resid < 0, q * resid, (1-q) * resid) resid = np.abs(resid) #1/resid[:, np.newaxis]为更新权重W xstar = exog / resid[:, np.newaxis] diff = np.max(np.abs(beta - beta0)) history['params'].append(beta) history['mse'].append(np.mean(resid*resid)) #检查是否收敛,若收敛则提前停止迭代 if (n_iter >= 300) and (n_iter % 100 == 0): # check for convergence circle, should not happen for ii in range(2, 10): if np.all(beta == history['params'][-ii]): cycle = True warnings.warn("Convergence cycle detected", ConvergenceWarning) break # 超出迭代次数,发出警告并结束,迭代次数默认为1000 if n_iter == max_iter: warnings.warn("Maximum number of iterations (" + str(max_iter) + ") reached.", IterationLimitWarning) #计算协方差矩阵 e = endog - np.dot(exog, beta) # Greene (2008, p.407) writes that Stata 6 uses this bandwidth: # h = 0.9 * np.std(e) / (nobs**0.2) # Instead, we calculate bandwidth as in Stata 12 iqre = stats.scoreatpercentile(e, 75) - stats.scoreatpercentile(e, 25) h = bandwidth(nobs, q) h = min(np.std(endog), iqre / 1.34) * (norm.ppf(q + h) - norm.ppf(q - h)) fhat0 = 1. / (nobs * h) * np.sum(kernel(e / h)) if vcov == 'robust': d = np.where(e > 0, (q/fhat0)**2, ((1-q)/fhat0)**2) xtxi = pinv(np.dot(exog.T, exog)) xtdx = np.dot(exog.T * d[np.newaxis, :], exog) vcov = xtxi @ xtdx @ xtxi elif vcov == 'iid': vcov = (1. / fhat0)**2 * q * (1 - q) * pinv(np.dot(exog.T, exog)) else: raise Exception("vcov must be 'robust' or 'iid'") #用系数估计值和协方差矩阵创建一个QuantResults对象,并输出结果 lfit = QuantRegResults(self, beta, normalized_cov_params=vcov) lfit.q = q lfit.iterations = n_iter lfit.sparsity = 1. / fhat0 lfit.bandwidth = h lfit.history = history return RegressionResultsWrapper(lfit) #核函数表达式 def _parzen(u): z = np.where(np.abs(u) <= .5, 4./3 - 8. * u**2 + 8. * np.abs(u)**3, 8. * (1 - np.abs(u))**3 / 3.) z[np.abs(u) > 1] = 0 return z kernels = {} kernels['biw'] = lambda u: 15. / 16 * (1 - u**2)**2 * np.where(np.abs(u) <= 1, 1, 0) kernels['cos'] = lambda u: np.where(np.abs(u) <= .5, 1 + np.cos(2 * np.pi * u), 0) kernels['epa'] = lambda u: 3. / 4 * (1-u**2) * np.where(np.abs(u) <= 1, 1, 0) kernels['gau'] = lambda u: norm.pdf(u) kernels['par'] = _parzen #kernels['bet'] = lambda u: np.where(np.abs(u) <= 1, .75 * (1 - u) * (1 + u), 0) #kernels['log'] = lambda u: logistic.pdf(u) * (1 - logistic.pdf(u)) #kernels['tri'] = lambda u: np.where(np.abs(u) <= 1, 1 - np.abs(u), 0) #kernels['trw'] = lambda u: 35. / 32 * (1 - u**2)**3 * np.where(np.abs(u) <= 1, 1, 0) #kernels['uni'] = lambda u: 1. / 2 * np.where(np.abs(u) <= 1, 1, 0) #窗宽计算 def hall_sheather(n, q, alpha=.05): z = norm.ppf(q) num = 1.5 * norm.pdf(z)**2. den = 2. * z**2. + 1. h = n**(-1. / 3) * norm.ppf(1. - alpha / 2.)**(2./3) * (num / den)**(1./3) return h def bofinger(n, q): num = 9. / 2 * norm.pdf(2 * norm.ppf(q))**4 den = (2 * norm.ppf(q)**2 + 1)**2 h = n**(-1. / 5) * (num / den)**(1. / 5) return h def chamberlain(n, q, alpha=.05): return norm.ppf(1 - alpha / 2) * np.sqrt(q*(1 - q) / n) [docs]class QuantRegResults(RegressionResults): '''Results instance for the QuantReg model''' @cache_readonly def prsquared(self): q = self.q endog = self.model.endog e = self.resid e = np.where(e < 0, (1 - q) * e, q * e) e = np.abs(e) ered = endog - stats.scoreatpercentile(endog, q * 100) ered = np.where(ered < 0, (1 - q) * ered, q * ered) ered = np.abs(ered) return 1 - np.sum(e) / np.sum(ered) #@cache_readonly [docs] def scale(self): return 1. @cache_readonly def bic(self): return np.nan @cache_readonly def aic(self): return np.nan @cache_readonly def llf(self): return np.nan @cache_readonly def rsquared(self): return np.nan @cache_readonly def rsquared_adj(self): return np.nan @cache_readonly def mse(self): return np.nan @cache_readonly def mse_model(self): return np.nan @cache_readonly def mse_total(self): return np.nan @cache_readonly def centered_tss(self): return np.nan @cache_readonly def uncentered_tss(self): return np.nan @cache_readonly def HC0_se(self): raise NotImplementedError @cache_readonly def HC1_se(self): raise NotImplementedError @cache_readonly def HC2_se(self): raise NotImplementedError @cache_readonly def HC3_se(self): raise NotImplementedError [docs] def summary(self, yname=None, xname=None, title=None, alpha=.05): """Summarize the Regression Results Parameters ---------- yname : str, optional Default is `y` xname : list[str], optional Names for the exogenous variables. Default is `var_##` for ## in the number of regressors. Must match the number of parameters in the model title : str, optional Title for the top table. If not None, then this replaces the default title alpha : float significance level for the confidence intervals Returns ------- smry : Summary instance this holds the summary tables and text, which can be printed or converted to various output formats. See Also -------- statsmodels.iolib.summary.Summary : class to hold summary results """ """ 总结回归结果 参数 ---------- Yname: str,可选 默认是“y” list[str],可选 外生变量的名称。默认是' var_## '的## in 回归量的数量。必须匹配的参数个数 在模型中 标题:str,可选 顶级的头衔。如果不是None,则替换 默认的标题 α:浮动 置信区间的显著性水平 返回 ------- smry:概要实例 这包含了汇总表和文本,可以打印或 转换为各种输出格式。 另请参阅 -------- summary:保存汇总结果的类 """ eigvals = self.eigenvals condno = self.condition_number top_left = [('Dep. Variable:', None), ('Model:', None), ('Method:', ['Least Squares']), ('Date:', None), ('Time:', None) ] top_right = [('Pseudo R-squared:', ["%#8.4g" % self.prsquared]), ('Bandwidth:', ["%#8.4g" % self.bandwidth]), ('Sparsity:', ["%#8.4g" % self.sparsity]), ('No. Observations:', None), ('Df Residuals:', None), ('Df Model:', None) ] if title is None: title = self.model.__class__.__name__ + ' ' + "Regression Results" # create summary table instance from statsmodels.iolib.summary import Summary smry = Summary() smry.add_table_2cols(self, gleft=top_left, gright=top_right, yname=yname, xname=xname, title=title) smry.add_table_params(self, yname=yname, xname=xname, alpha=alpha, use_t=self.use_t) # add warnings/notes, added to text format only etext = [] if eigvals[-1] < 1e-10: wstr = "The smallest eigenvalue is %6.3g. This might indicate " wstr += "that there are\n" wstr += "strong multicollinearity problems or that the design " wstr += "matrix is singular." wstr = wstr % eigvals[-1] etext.append(wstr) elif condno > 1000: # TODO: what is recommended wstr = "The condition number is large, %6.3g. This might " wstr += "indicate that there are\n" wstr += "strong multicollinearity or other numerical " wstr += "problems." wstr = wstr % condno etext.append(wstr) if etext: smry.add_extra_txt(etext) return smry
-
论文研究-基于LASSO分位数回归的中期电力负荷概率密度预测方法.pdf
2019-09-20 21:42:31提出的基于LASSO分位数回归概率密度预测方法,首先从影响电力负荷预测的多种外界因素中挑选出重要的影响因子,建立LASSO分位数回归模型.然后,使用triangular核函数,将LASSO分位数回归与核密度估计方法相结合,进行... -
基于深度学习分位数回归模型的风电功率概率密度预测.pdf
2021-08-18 23:47:40基于深度学习分位数回归模型的风电功率概率密度预测.pdf -
论文研究-基于Box-Cox变换分位数回归与负荷关联因素辨识的中长期概率密度预测.pdf
2019-09-20 20:52:22论文研究-基于Box-Cox变换分位数回归与负荷关联因素辨识的中长期概率密度预测.pdf, 中长期电力负荷预测是电力部门制定电力系统发展规划和稳定运行的重要前提.针对影响中... -
证券投资基金收益概率密度预测——基于神经网络分位数回归模型.pdf
2021-09-27 20:59:00证券投资基金收益概率密度预测——基于神经网络分位数回归模型.pdf -
分位数回归
2020-03-10 00:24:43分位数(Quantile),亦称分位点,是指将一个随机变量的概率分布范围分为几个等份的数值点,常用的有中位数(即二分位数)、四分位数、百分位数等。分位数(Quantile),亦称分位点,是指将一个随机变量的概率分布范围分为几个等份的数值点,常用的有中位数(即二分位数)、四分位数、百分位数等。
任意一个累计分布函数 F ( x ) F(x) F(x) ,满足 F ( x ^ ) = σ , σ ∈ ( 0 , 1 ) F(\hat{x}) = \sigma, \sigma\in (0,1) F(x^)=σ,σ∈(0,1) 的 x ^ \hat{x} x^,称为分布 F F F 的分位数。
σ \sigma σ 的含义是该分布中小于 x ^ \hat{x} x^的数占比为 σ \sigma σ,即 P ( x < x ^ ) = σ P(x<\hat{x}) = \sigma P(x<x^)=σ。
给定一个平稳时间序列,我们通常为考虑回归出它的均值。但在更一般的情况下,我们希望回归出样本对应分布的分位点,因为分位点更能反映出分布的性质。
下面用一个例子来说明:
import numpy as np import matplotlib.pyplot as plt %matplotlib inline gauss = [np.random.randn() for _ in range(100)] plt.plot(gauss)
可以直接画出经验概率分布函数from statsmodels.distributions.empirical_distribution import ECDF cdf = ECDF(gauss) plt.plot(cdf.x, cdf.y, label = "statmodels") plt.xlabel('sample value')
在概率分布函数上找分位点太容易了,在纵轴上确定 σ \sigma σ,回到横轴上找 x ^ \hat{x} x^基于梯度下降的分位点回归
在一般的时间序列预测问题中,我们通常是用一个函数取拟合序列,通常学习到的函数是对真实样本均值的估计。
有没有办法让学习函数去逼近真实样本的分位点呢?
只需要使用如下损失函数:
L ( y , y ^ ) = σ max ( y − y ^ , 0 ) + ( 1 − σ ) max ( y ^ − y , 0 ) L(y,\hat{y}) = \sigma\max (y-\hat{y},0) + (1-\sigma)\max(\hat{y}-y,0) L(y,y^)=σmax(y−y^,0)+(1−σ)max(y^−y,0) ∂ L ( y , y ^ ) ∂ y ^ = − σ I ( y − y ^ ) + ( 1 − σ ) I ( y ^ − y ) \frac{\partial L(y,\hat{y})}{\partial \hat{y}} = -\sigma\mathbb{I(y-\hat{y})} + (1-\sigma)\mathbb{I(\hat{y}-y)} ∂y^∂L(y,y^)=−σI(y−y^)+(1−σ)I(y^−y)
其中 y ^ \hat{y} y^ 是输出, y y y 为目标值。rho = 0.75 def grad(rho, z, ze): return -rho if ze <= z else 1-rho ze = 0 lr = 0.1 for z in gauss: ze -= lr*grad(rho, z, ze) cdf = ECDF(gauss) plt.plot(cdf.x, cdf.y, label = "statmodels") plt.plot(ze, rho, 'ro') plt.plot([-3, ze],[rho, rho],'g--') plt.plot([ze, ze],[0, rho],'g--') plt.xlabel('sample value')
rho = 0.1
可以看出,提出下降法很好地找到了序列的分位点,和直接用概率分布函数的结果一致。 -
拓端tecdat|R语言实现贝叶斯分位数回归、lasso和自适应lasso贝叶斯分位数回归分析
2021-06-07 18:09:00摘要 贝叶斯回归分位数在最近的文献中受到广泛关注,本文实现了贝叶斯系数估计和回归分位数(RQ)中的变量选择,带有lasso和自适应...自引入以来,分位数回归一直是理论界非常关注的话题,也在许多研究领域得到了. -
分位数回归(Quantile Regression)
2020-06-29 14:56:31数据采用分位数回归 在执行回归分析时,仅对问题进行数值预测还不够,您还需要表达您对该预测的信心。例如,如果您正在查看特定市场中房屋的价格,并且您的模型预测房屋的售价为262,458.45美元,那么您对模型的预测... -
基于R语言的分位数回归(quantile regression)
2017-12-18 17:45:21分位数回归(quantile regression) 这一讲,我们谈谈分位数回归的知识,我想大家传统回归都经常见到。分位数回归可能大家见的少一些,其实这个方法也很早了,大概78年代就有了,但是那个时候这个理论还不完善。到... -
【时序】MQ-RNN 概率预测模型论文笔记
2022-04-01 23:23:04具体来说,我们利用序列到序列神经网络(例如循环和卷积结构)的表现力和时间特性、分位数回归的非参数特性和直接多水平预测的效率。一种新的训练方案 fork-sequences 专为顺序网络设计,以提高稳定性和性能。我们... -
用R语言进行分位数回归
2018-12-04 21:22:00非线性分位数回归这里的非线性函数为Frank copula函数。 (六)非线性分位数回归 这里的非线性函数为Frank copula函数。 ## Demo of nonlinear quantile regression model based on ... -
拓端tecdat|R语言分位数回归、GAM样条曲线、指数平滑和SARIMA对电力负荷时间序列预测
2020-04-19 21:59:17电力负荷预测是电网规划的基础,其水平的高低将直接影响电网规划质量的优劣。为了准确预测电力负荷,有必要进行建模。 -
【R】【课程笔记】07 分位数回归与VaR(ES)计算
2020-06-10 11:40:34fp 二、非线性分位数回归 参数非线性分位数回归: Box-Cox变换分位数回归(最常用) 局部多项式分位数回归 B样条分位数回归 1、Box-Cox变换分位数回归 “数据不是正态,所以没法用正态性质,所以每个点都做一个变换... -
【时间序列】DeepAR: 自回归RNN预测时序概率分布
2022-01-25 00:20:01本篇介绍一种使用自回归RNN预测时序分布的模型DeepAR,它有效解决了多时序间尺度不一致问题,并基于数据特征选择似然函数预测时序概率分布。推荐阅读:5星。不足之处,还望批评指正。论文:2... -
分位数回归的matlab程序_MATLAB学习笔记之绘图篇
2020-10-21 21:59:36这是一个连续变量(定量变量)的概率分布的估计,并且被卡尔·皮尔逊(Karl Pearson)首先引入。它是一种条形图。 为了构建直方图,第一步是将值的范围分段,即将整个值的范围分成一系列间隔,然后计算每个间隔中有... -
拓端tecdat|R语言分位数回归Quantile Regression分析租房价格
2020-04-14 00:01:58本文想在R软件中更好地了解分位数回归优化。在查看分位数回归之前,让我们从样本中计算中位数或分位数。 -
拓端tecdat|matlab使用分位数随机森林(QRF)回归树检测异常值
2021-04-12 14:16:20这个例子展示了如何使用分位数随机林来检测异常值。分位数随机林可以检测到与给定X的Y的条件分布有关的异常值。 离群值是一些观测值,它的位置离数据集中的...生长回归树的分位数随机森林。 估计预测变量范围.. -
基于分位数回归的分布强化学习(Distributional Reinforcemet Learning with Quantile Regression)
2019-05-20 22:27:54Deep Mind团队联合剑桥大学在2017年提出了一种新的强化学习范式——基于分位数回归的分布强化学习(QR-DRL),为强化学习的未来发展指明了一个更加有前景的方向,以学习回报值的概率分布来代替学习回报值的期望值。... -
数据分析36计(19):美国生鲜配送平台【Instacart】如何实现按时配送——使用分位数回归...
2020-12-22 08:30:00q=0.1和q=0.9的分位数回归,用作预测间隔 分位数回归提供了交货时间的预测间隔。预测间隔随着配送距离的增加而增加,这是合理的,因为对于长距离而言,准确预测变得越来越困难(方差更大,数据更少)。因此,我们... -
【时序】DeepAR 概率预测模型论文笔记
2022-03-23 13:41:37ii)其次,DeepAR 以 Monte Carlo 样本的形式进行概率预测,可用于计算预测范围内所有子范围内的一致分位数估计(打破传统方法比如只能预测某一个分位数估计的局限性),以便做决策。 iii)通过从相似项目中学习,... -
NeurIPS 2018 | 腾讯AI Lab主导提出可用于预测金融市场风险的低维简约分位数回归框架...
2018-12-07 11:30:00与香港城市大学、香港中文大学合作完成的论文中,作者提出了一种低维简约分位数回归框架来学习证券收益率时间序列的动态重尾行为,用于对金融二级市场(包括股票、外汇、债券、大宗商品等)的波动率预测和尾部风险... -
多元线性回归算法预测房价——Excel、jupyter+sklearn
2021-10-26 01:28:07特征共线性问题二、用Excel做房价预测线性回归1. 配置Excel2. 完善数据集2.1 剔除错误数据2.2 处理非数据数值3. Excel做线性回归三、用jupyter+sklearn做线性回归练习1. 打开jupyter步骤2.写入代码2.1 不做数据处理... -
统计学基础专栏04---回归和预测
2021-04-24 16:27:230.4、回归和预测 响应变量 想要预测的变量。 自变量 用于预测响应的变量。 记录 一个表示特定个体或实例的向量,由因子和结果值组成。 截距 回归线的截距,即当 X = 0 时的预测值。 回归系数 回归线的斜率。 拟合值 ...