Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/315.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 利用StatsModels绘制二阶多项式分位数回归_Python_Pandas_Regression_Statsmodels - Fatal编程技术网

Python 利用StatsModels绘制二阶多项式分位数回归

Python 利用StatsModels绘制二阶多项式分位数回归,python,pandas,regression,statsmodels,Python,Pandas,Regression,Statsmodels,我将按照StatsModels示例绘制分位数回归线。只需对我的数据稍加修改,这个示例就非常有效,生成了这个图(请注意,我修改了代码,只绘制了0.05、0.25、0.5、0.75和0.95分位数): 然而,我想为二阶多项式拟合(而不是线性拟合)绘制OLS拟合和相应的分位数。例如,以下是相同数据的第二阶OLS行: 如何修改链接示例中的代码以生成非线性分位数 以下是根据链接示例修改的相关代码,以生成第一个绘图: d = {'temp': x, 'dens': y} df = pd.DataFram

我将按照StatsModels示例绘制分位数回归线。只需对我的数据稍加修改,这个示例就非常有效,生成了这个图(请注意,我修改了代码,只绘制了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 Perktheld)的援助值得高度赞扬

以下是相关代码和绘图:

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百分位

您能否澄清模型中“I”的用途<代码>'dens~temp+I(temp**2.0)这是用于Patsy(一种公式“迷你语言”)的语法。看见(x**2.0)在公式中不起作用,您需要
I
,这样patsy就不会试图进行分类转换。我是否应该担心
未来警告:使用非元组序列进行多维索引是不可取的;使用'arr[tuple(seq)]`代替'arr[seq]`。在将来,这将被解释为数组索引“arr[np.array(seq)]”,这将导致错误或不同的结果。
?我不确定代码的哪个部分会抛出此警告。。。StatsModels包中有什么?但是是的,这看起来可能值得注意。如果它在您自己的代码中,也许一些简单的修改可以解决该警告。如果是在StatsModels中,可能需要引起StatsModels开发人员的注意。