在熊猫中有效扩展OLS

时间:2019-11-25 21:18:27

标签: python pandas linear-regression statsmodels

我想探索在熊猫(或其他接受DataFrame / Series友好的库)中执行扩展OLS的解决方案。

  1. 假设数据集很大,我对使用for循环的任何解决方案都不感兴趣;
  2. 我正在寻找有关扩展而不是滚动的解决方案。滚动功能始终需要固定的窗口,而展开使用可变的窗口(从头开始);
  3. 请不要建议pandas.stats.ols.MovingOLS,因为它已过时;
  4. 请不要建议其他不推荐使用的方法,例如expanding_mean

例如,有一个具有两列dfX的DataFrame y。为了简化起见,我们只计算beta。 目前,我正在考虑类似

import numpy as np
import pandas as pd
import statsmodel.api as sm

def my_OLS_func(df, y_name, X_name):
  y = df[y_name]
  X = df[X_name]
  X = sm.add_constatn(X)
  b = np.linalg.pinv(X.T.dot(X)).dot(X.T).dot(y)
  return b

df = pd.DataFrame({'X':[1,2.5,3], 'y':[4,5,6.3]})

df['beta'] = df.expanding().apply(my_OLS_func, args = ('y', 'X'))

df['beta']的期望值为0(或NaN),0.666666671.038462

但是,此方法似乎不起作用,因为该方法似乎非常不灵活。我不确定如何将两个系列作为参数传递。 任何建议,将不胜感激。

1 个答案:

答案 0 :(得分:1)

一种选择是使用Statsmodels中的RecursiveLS(递归最小二乘)模型:

# Simulate some data
rs = np.random.RandomState(seed=12345)

nobs = 100000
beta = [10., -0.2]
sigma2 = 2.5

exog = sm.add_constant(rs.uniform(size=nobs))
eps = rs.normal(scale=sigma2**0.5, size=nobs)
endog = np.dot(exog, beta) + eps

# Construct and fit the recursive least squares model
mod = sm.RecursiveLS(endog, exog)
res = mod.fit()
# This is a 2 x 100,000 numpy array with the regression coefficients
# that would be estimated when using data from the beginning of the
# sample to each point. You should usually ignore the first k=2
# datapoints since they are controlled by a diffuse prior.
res.recursive_coefficients.filtered