Des*_*gos 6 python numpy linear-regression python-3.x pandas
我想OLS regression estimation
在以下URL中运行数据集的滚动1000窗口以进行评估:
https://drive.google.com/open?id=0B2Iv8dfU4fTUa3dPYW5tejA0bzg
我尝试使用以下Python
脚本与pandas
版本0.20.2
.
# /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
Run Code Online (Sandbox Code Playgroud)
但是,当我运行我的Python
脚本时,我收到此错误:AttributeError: module 'pandas.stats' has no attribute 'ols'
.我发现这个错误的原因是因为它从Pandas
版本中删除了,因为0.20.0
我们可以从以下链接看到它.
https://github.com/pandas-dev/pandas/pull/11898
我们如何OLS Regression
处理最新版本的熊猫?
虽然通常我建议应用类似statsmodels.ols
滚动的东西*,你的数据集很大(258k行的长度为1000的窗口),你会遇到内存错误.因此,您可以使用线性代数方法计算系数,然后将这些系数应用于解释变量的每个窗口.有关此内容的更多信息,请参阅多元回归模型的矩阵表达式.
*要查看statsmodel的实现,请参阅我在此处创建的包装器.一个例子是在这里.
意识到yhat
这里不是一个nx1向量 - 它是一堆堆叠在彼此之上的nx1向量,即每个滚动1000周期块有一组预测.因此,预测的形状将为(257526,1000),如下所示.
import numpy as np
import pandas as pd
df = pd.read_csv('input/estimated.csv', names=('x','y'))
def rolling_windows(a, window):
"""Creates rolling-window 'blocks' of length `window` from `a`.
Note that the orientation of rows/columns follows that of pandas.
Example
=======
onedim = np.arange(20)
twodim = onedim.reshape((5,4))
print(twodim)
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]
[12 13 14 15]
[16 17 18 19]]
print(rwindows(onedim, 3)[:5])
[[0 1 2]
[1 2 3]
[2 3 4]
[3 4 5]
[4 5 6]]
print(rwindows(twodim, 3)[:5])
[[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
[[ 4 5 6 7]
[ 8 9 10 11]
[12 13 14 15]]
[[ 8 9 10 11]
[12 13 14 15]
[16 17 18 19]]]
"""
if isinstance(a, (Series, DataFrame)):
a = a.values
if a.ndim == 1:
a = a.reshape(-1, 1)
shape = (a.shape[0] - window + 1, window) + a.shape[1:]
strides = (a.strides[0],) + a.strides
windows = np.lib.stride_tricks.as_strided(a, shape=shape, strides=strides)
return np.squeeze(windows)
def coefs(y, x):
return np.dot(np.linalg.inv(np.dot(x.T, x)), np.dot(x.T, y))
rendog = rolling_windows(df.x.values, 1000)
rexog = rolling_windows(df.drop('x', axis=1).values, 1000)
preds = list()
for endog, exog in zip(rendog, rexog):
pred = np.sum(coefs(endog, exog).T * exog, axis=1)
preds.append(pred)
preds = np.array(preds)
print(preds.shape)
(257526, 1000)
Run Code Online (Sandbox Code Playgroud)
最后:考虑到你的变量是离散的,你考虑过在这里使用随机森林分类器y
吗?