2017-06-22 72 views
2

对我的评价,我想跑滚动1000窗口在这个网址找到该数据集的OLS regression estimation:使用以下Python脚本 https://drive.google.com/open?id=0B2Iv8dfU4fTUa3dPYW5tejA0bzgPython的大熊猫有没有属性醇 - 错误(滚动OLS)

# /usr/bin/python -tt 

import numpy as np 
import matplotlib.pyplot as plt 
import pandas as pd 
from statsmodels.formula.api import ols 

df = pd.read_csv('estimated.csv', names=('x','y')) 

model = pd.stats.ols.MovingOLS(y=df.Y, x=df[['y']], 
           window_type='rolling', window=1000, intercept=True) 
df['Y_hat'] = model.y_predict 

然而,当我跑我的Python脚本,我收到此错误:AttributeError: module 'pandas.stats' has no attribute 'ols'。这个错误可能来自我使用的版本吗?安装我的Linux节点上的pandas有一个版本的0.20.2

+0

用,会发生什么'从pandas.stats导入ols'? – roganjosh

+0

它说'ImportError:无法导入名称'ols''。 –

+0

你用'print(dir(pd.stats))'得到了什么?我不在笔记本电脑上,很快就会回家测试自己。它在列表中吗? – roganjosh

回答

3

pd.stats.ols.MovingOLS在大熊猫版本中删除0.20.0

http://pandas-docs.github.io/pandas-docs-travis/whatsnew.html#whatsnew-0200-prior-deprecations

https://github.com/pandas-dev/pandas/pull/11898

我无法找到一个 '现成'对于什么应该是滚动回归这样明显的用例的解决方案。

以下方法应该可以避免在更优雅的解决方案中投入太多时间。它使用numpy根据回归参数和滚动窗口中的X值来计算回归的预测值。

window = 1000 
a = np.array([np.nan] * len(df)) 
b = [np.nan] * len(df) # If betas required. 
y_ = df.y.values 
x_ = df[['x']].assign(constant=1).values 
for n in range(window, len(df)): 
    y = y_[(n - window):n] 
    X = x_[(n - window):n] 
    # betas = Inverse(X'.X).X'.y 
    betas = np.linalg.inv(X.T.dot(X)).dot(X.T).dot(y) 
    y_hat = betas.dot(x_[n, :]) 
    a[n] = y_hat 
    b[n] = betas.tolist() # If betas required. 

上面的代码等同于以下约35%的速度:

model = pd.stats.ols.MovingOLS(y=df.y, x=df.x, window_type='rolling', window=1000, intercept=True) 
y_pandas = model.y_predict 
+0

是的,就像我从上面的评论中学到的那样。那么,对于我们如何将它与最新版本的“熊猫”一起使用,你有什么想法吗? –

+0

@DestaHaileselassieHagos您想要从滚动回归中得到什么结果(例如,斜率,截距,预测值等) – Alexander

+0

@Alexander,例如预测值。谢谢! –

相关问题