如何解决使用 StatsModels 对二阶多项式进行分位数回归
我已经按照 PJW 的示例 here 绘制了二阶多项式分位数回归。 OLS 模型似乎很适合我的数据,但分位数线出来真的很古怪,我一直无法弄清楚代码哪里出错了。我在下面附上了我的代码和只有 OLS 回归线的图表和带有时髦分位数的图表。任何帮助将不胜感激!
具有 OLS 二阶多项式回归线(黑色)和分位数线(0.05、0.5、0.95)的相同散点图明显错误(红色虚线):
def plot_poly_centiles(parameter_df):
# function to plot quantile lines using polynomial regression
par_name = parameter_df.columns[1]
# plot a scatter graph of the data
plt.subplots(figsize=(10,6))
sns.scatterplot(x='age',y=par_name,data=parameter_df,marker='.',color='blue',alpha=0.1)
model = smf.quantreg(f'{par_name} ~ age + np.power(age,2)',parameter_df)
result = model.fit(q=0.5)
print(result.summary())
# Quantile regression for 5 quantiles
quantiles = [.05,.25,.50,.75,.95]
# get all model result instances in a list
result_all = [model.fit(q=q) for q in quantiles]
result_ols = smf.ols(f'{par_name} ~ age + np.power(age,parameter_df).fit()
# create x for prediction
x = np.arange(parameter_df.age.min(),parameter_df.age.max(),50)
predicted_df = pd.DataFrame({'age': x})
# plot quantile lines
for qm,result in zip(quantiles,result_all):
# get prediction for the model and plot
# here we use a dict which works the same way as the df in ols
y_cent = result.predict({'age': x})
plt.plot(x,y_cent,linestyle='--',linewidth=1,color='red')
# plot ols line
y_ols_predicted = result_ols.predict(predicted_df)
plt.plot(x,y_ols_predicted,color='k',label='OLS')
plt.xlabel('age in days')
plt.ylabel(f'{par_name}')
plt.title(f'Polynomial regression centiles of {par_name} in children')
plt.show()
return parameter_df
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。