python - 如何使用最新版本的 Pandas 进行 OLS 回归

标签 python python-3.x pandas numpy linear-regression

我想运行一个滚动的 1000 窗口 OLS 回归估计 数据集以进行评估,网址如下:

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 中删除,我们可以从以下链接中看到它。

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

我们如何使用最新版本的 Pandas 进行OLS 回归

最佳答案

虽然通常我会建议在滚动基础上应用类似 statsmodels.ols 的东西*,但您的数据集很大(258k 行上长度为 1000 个窗口),这样您会遇到内存错误.因此,您可以使用线性代数方法计算系数,然后将这些系数应用于解释变量的每个窗口。有关更多信息,请参阅 A Matrix Formulation of the Multiple Regression Model .

* 要查看 statsmodels 的实现,请查看我创建的包装器 here .一个例子是 here .

意识到这里的 yhat 不是一个 nx1 向量——它是一堆 nx1 向量堆叠在一起,即每个滚动的 1000 周期 block 有一组预测。因此,您的预测形状将为 (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)

最后:您是否考虑过使用 Random Forest Classifier假设您的 y 变量是离散的?

关于python - 如何使用最新版本的 Pandas 进行 OLS 回归,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44709790/

相关文章:

python - Windows 上 Python (v3.0) 中的环境变量

python - Pandas DF 中取消虚拟变量的最有效方法

Python 3 和 Gspread 导入错误

Python 2to3 - 不要删除 unicode 前缀

python是字符串的运算符行为

python - 有没有办法检查数据框中的线性相关列?

python - 加入 Pandas 数据框中的重复列

python - 使用 pandas.to_excel() 时没有 Excel 编写器 'openpyxl'

python - Python中的多线程(我的代码正确)

python - 检查值是否包含在张量中