python分位数回归模型_python – 使用StatsModels绘制二阶多项式的分位数回归
我遵循StatsModels示例here来绘制分位数回归线.只需对我的数据稍作修改,该示例效果很好,生成此绘图(请注意,我已修改代码以仅绘制0.05,0.25,0.5,0.75和0.95分位数):
但是,我想绘制OLS拟合和相应分位数的二阶多项式拟合(而不是线性).例如,以下是相同数据的二阶OLS行:
如何修改链接示例中的代码以生成非线性分位数?
这是我从链接示例中修改的相关代码,以生成第一个图:
d = {'temp': x, 'dens': y}
df = pd.DataFrame(data=d)
# Least Absolute Deviation
#
# The LAD model is a special case of quantile regression where q=0.5
mod = smf.quantreg('dens ~ temp', df)
res = mod.fit(q=.5)
print(res.summary())
# Prepare data for plotting
#
# For convenience, we place the quantile regression results in a Pandas DataFrame, and the OLS results in a dictionary.
quantiles = [.05, .25, .50, .75, .95]
def fit_model(q):
res = mod.fit(q=q)
return [q, res.params['Intercept'], res.params['temp']] + res.conf_int().ix['temp'].tolist()
models = [fit_model(x) for x in quantiles]
models = pd.DataFrame(models, columns=['q', 'a', 'b','lb','ub'])
ols = smf.ols('dens ~ temp', df).fit()
ols_ci = ols.conf_int().ix['temp'].tolist()
ols = dict(a = ols.params['Intercept'],
b = ols.params['temp'],
lb = ols_ci[0],
ub = ols_ci[1])
print(models)
print(ols)
x = np.arange(df.temp.min(), df.temp.max(), 50)
get_y = lambda a, b: a + b * x
for i in range(models.shape[0]):
y = get_y(models.a[i], models.b[i])
plt.plot(x, y, linestyle='dotted', color='grey')
y = get_y(ols['a'], ols['b'])
plt.plot(x, y, color='red', label='OLS')
plt.scatter(df.temp, df.dens, alpha=.2)
plt.xlim((-10, 40))
plt.ylim((0, 0.4))
plt.legend()
plt.xlabel('temp')
plt.ylabel('dens')
plt.show()
解决方法:
经过一天的调查,想出了一个解决方案,所以发布我自己的答案.在StatsModels的Josef Perktold获得了很多帮助.
这是相关的代码和图:
d = {'temp': x, 'dens': y}
df = pd.DataFrame(data=d)
x1 = pd.DataFrame({'temp': np.linspace(df.temp.min(), df.temp.max(), 200)})
poly_2 = smf.ols(formula='dens ~ 1 + temp + I(temp ** 2.0)', data=df).fit()
plt.plot(x, y, 'o', alpha=0.2)
plt.plot(x1.temp, poly_2.predict(x1), 'r-',
label='2nd order poly fit, $R^2$=%.2f' % poly_2.rsquared,
alpha=0.9)
plt.xlim((-10, 50))
plt.ylim((0, 0.25))
plt.xlabel('mean air temp')
plt.ylabel('density')
plt.legend(loc="upper left")
# with quantile regression
# Least Absolute Deviation
# The LAD model is a special case of quantile regression where q=0.5
mod = smf.quantreg('dens ~ temp + I(temp ** 2.0)', df)
res = mod.fit(q=.5)
print(res.summary())
# Quantile regression for 5 quantiles
quantiles = [.05, .25, .50, .75, .95]
# get all result instances in a list
res_all = [mod.fit(q=q) for q in quantiles]
res_ols = smf.ols('dens ~ temp + I(temp ** 2.0)', df).fit()
plt.figure()
# create x for prediction
x_p = np.linspace(df.temp.min(), df.temp.max(), 50)
df_p = pd.DataFrame({'temp': x_p})
for qm, res in zip(quantiles, res_all):
# get prediction for the model and plot
# here we use a dict which works the same way as the df in ols
plt.plot(x_p, res.predict({'temp': x_p}), linestyle='--', lw=1,
color='k', label='q=%.2F' % qm, zorder=2)
y_ols_predicted = res_ols.predict(df_p)
plt.plot(x_p, y_ols_predicted, color='red', zorder=1)
#plt.scatter(df.temp, df.dens, alpha=.2)
plt.plot(df.temp, df.dens, 'o', alpha=.2, zorder=0)
plt.xlim((-10, 50))
plt.ylim((0, 0.25))
#plt.legend(loc="upper center")
plt.xlabel('mean air temp')
plt.ylabel('density')
plt.title('')
plt.show()
红线:二阶多项式拟合
黑色虚线:第5,第25,第50,第75,第95百分位数
标签:python,pandas,regression,statsmodels
python分位数回归模型_python – 使用StatsModels绘制二阶多项式的分位数回归相关推荐
- python多元线性回归mlr 校正_多元线性 回归模型满足假定 MLR.1 ~假定 MLR.4 时 , 回归参数的 OLS 估计量是 的 。_学小易找答案...
[填空题]任务5-1的照明回路WL4的管内穿线BV-2.5的安装工程量是()m [单选题]必须认识到,我国社会主要矛盾的变化,没有改变我们对我国社会主义所处历史阶段的判断,我国仍处于并将长期处于___ ...
- R语言构建logistic回归模型:WVPlots包PRTPlot函数可视化获取logistic回归模型的最优阈值、优化(precision、enrichment)和recall之间的折衷
R语言构建logistic回归模型:WVPlots包PRTPlot函数可视化获取logistic回归模型的最佳阈值(改变阈值以优化精确度(precision.enrichment)和查全率(recal ...
- R语言计算回归模型标准化残差实战(Standardized Residuals):识别回归模型中离群点
R语言计算回归模型标准化残差实战(Standardized Residuals):识别回归模型中离群点 目录
- python分析鸢尾花数据_python数据挖掘学习笔记】十六.逻辑回归LogisticRegression分析鸢尾花数据...
但是很多时候数据是非线性的,所以这篇文章主要讲述逻辑回归及Sklearn机器学习包中的LogisticRegression算法 #2018-03-28 16:57:56 March Wednesday ...
- python训练模型测试模型_python 机器学习中模型评估和调参
在做数据处理时,需要用到不同的手法,如特征标准化,主成分分析,等等会重复用到某些参数,sklearn中提供了管道,可以一次性的解决该问题 先展示先通常的做法 import pandas as pd f ...
- python决策评价模型_Python大规模建模的特征值选择和性能评估方法详解
大量的特征变量,很多的模型,模型也有很多参数,如何选择合适的特征.合适的模型和合适的模型参数,这对建模是很重要的,但也是很困难的.并且选择最优的方案,方法也是很多的,这里将其中一种方法尽量描述清楚: ...
- logit回归模型假设_一文读懂条件Logistic回归
在医学研究中,为了控制一些重要的混杂因素,经常会把病例和对照按年龄,性别等条件进行配对,形成多个匹配组.各匹配组的病例数和对照人数是任意的,比如一个病例和若干个对照匹配即1:1,在医学上称作" ...
- python回归模型_Python实现线性回归模型
从简单的线性回归模型中可以看到构建一个监督学习网络的基本步骤.下文摘自<动手学深度学习> 线性回归概念 线性回归输出是一个连续值,因此适用于回归问题.回归问题在实际中很常见,如预测房屋价格 ...
- python拟合sir模型_Python—拟合模型
在很多情况下,大家的工作会遇到y数据与x数据存在相关性,但无法知道y与x是那种相关,需要具体知道两者关系,我们可以用拟合模型来完成这个事情. 1:随机源数据 很多初学者想动手尝试的时候,苦于无源数据, ...
- python怎么画形状_python – matplotlib – 如何绘制随机导向的矩形(或任何形状)?...
好问题!我建议你不要在fill_between函数中限制自己.我总是认为深入了解事物是有益的.让我们深入研究Python绘图的本质. 因此,如果你掌握了Path,你基本上可以以任何方式绘制你喜欢的任何 ...
最新文章
- MaxScale:实现MySQL读写分离与负载均衡的中间件利器
- 又一个智商税产品“路由器防辐射笼”,信号都没了,还能火爆全网...
- nginx-启动gzip、虚拟主机、请求转发、负载均衡
- python time,datetime当前时间,昨天时间,时间戳和字符串的转化
- Asp.Net Core 5 REST API 使用 JWT 身份验证 - Step by Step(二)
- 测试驱动开发 测试前移_测试驱动开发–双赢策略
- Redis命令拾遗四——集合类型(命令补充)
- javascript跑马灯效果
- proteus仿真运行时出现的错误
- sublime中文乱码
- Python修改图片分辨率来改变图片大小
- excel取消隐藏_这个毁人无数的Excel黑洞,却成就一批最牛X的高手
- 苹果AirPlay浅析
- grafana text panel配置说明
- 开源的书签服务Cherry
- javabean/Listjavabean与map/Listmap互相转换
- 创建线程以及怎样创建有返回值的线程
- 什么?还在用delete删除数据《死磕MySQL系列 九》
- typename和class
- html中文本重复,在网页中去除文本列表中重复行与计算重复次数的代码原理
热门文章
- python database is locked_解决SQLite database is locked
- java bl层,科普一下bl锁的知识,没解锁的必看!
- win10 联想键盘快捷键关闭_Win10电脑不用鼠标怎么关机键盘与快捷键关机技巧
- linux 命令行 过滤,linux过滤命令
- html 悬浮qq,js悬浮QQ在线客服代码(支持拖动)
- vnc远程控制软件,在Linux上安装vnc远程控制软件只需4步
- python考勤统计_公司HR统计考勤用这个函数公式,快速、准确完成,再也不加班了...
- java fps计算_帧率(FPS)计算的六种方法总结
- 短信验证码如何保障用户信息及资金安全
- word顶部有一道线_word文档上方总有一条线怎样去掉?