2017-06-22 51 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,例如預測值。謝謝! –

相關問題