如何使用最新版本 Pandas 进行 OLS 回归
How to do OLS Regression with the latest version of Pandas
我想 运行 滚动 1000 window OLS regression estimation
的数据集用于我的评估 URL:
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
但是,当我 运行 我的 Python
脚本时,我收到此错误:AttributeError: module 'pandas.stats' has no attribute 'ols'
。我发现这个错误的原因是因为它从 Pandas
版本 0.20.0
之后被删除了,我们可以从下面的 link.
中看到它
https://github.com/pandas-dev/pandas/pull/11898
我们如何使用最新版本的PandasOLS Regression
?
虽然通常我会建议在滚动基础上应用类似 statsmodels.ols
的内容*,但您的数据集很大(长度为 1000 windows,258k 行)并且您将 运行这样的内存错误。因此,您可以使用线性代数方法计算系数,然后将这些系数应用于解释变量的每个 window。有关更多信息,请参阅 A Matrix Formulation of the Multiple Regression Model.
* 要查看 statsmodels 的实现,请查看我创建的包装器 here. An example is 。
意识到 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)
最后:鉴于您的 y
变量是离散的,您是否考虑过在此处使用 Random Forest Classifier?
您只需为
导入以下库
from statsmodels.regression.linear_model import OLS
我想 运行 滚动 1000 window OLS regression estimation
的数据集用于我的评估 URL:
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
但是,当我 运行 我的 Python
脚本时,我收到此错误:AttributeError: module 'pandas.stats' has no attribute 'ols'
。我发现这个错误的原因是因为它从 Pandas
版本 0.20.0
之后被删除了,我们可以从下面的 link.
https://github.com/pandas-dev/pandas/pull/11898
我们如何使用最新版本的PandasOLS Regression
?
虽然通常我会建议在滚动基础上应用类似 statsmodels.ols
的内容*,但您的数据集很大(长度为 1000 windows,258k 行)并且您将 运行这样的内存错误。因此,您可以使用线性代数方法计算系数,然后将这些系数应用于解释变量的每个 window。有关更多信息,请参阅 A Matrix Formulation of the Multiple Regression Model.
* 要查看 statsmodels 的实现,请查看我创建的包装器 here. An example is
意识到 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)
最后:鉴于您的 y
变量是离散的,您是否考虑过在此处使用 Random Forest Classifier?
您只需为
导入以下库from statsmodels.regression.linear_model import OLS