【问题标题】:How to do OLS Regression with the latest version of Pandas如何使用最新版本的 Pandas 进行 OLS 回归
【发布时间】:2017-11-26 08:18:57
【问题描述】:

我想运行一个滚动 1000 个窗口 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之后被删除,我们可以从以下链接中看到它。

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

我们如何使用最新版本的 Pandas 做OLS Regression

【问题讨论】:

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


    【解决方案1】:

    您只需为您的

    导入以下库
    from statsmodels.regression.linear_model import OLS
    

    【讨论】:

      【解决方案2】:

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

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

      意识到这里的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

      【讨论】:

        猜你喜欢
        • 2013-11-28
        • 1970-01-01
        • 1970-01-01
        • 2016-05-03
        • 1970-01-01
        • 2015-07-22
        • 1970-01-01
        • 2019-03-06
        • 2020-09-27
        相关资源
        最近更新 更多