python - pandas 中的高效扩展 OLS

标签 python pandas linear-regression statsmodels

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

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

例如,有一个包含两列 Xy 的 DataFrame df。为了简单起见,我们只计算 beta。 目前,我正在考虑类似的事情

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

def my_OLS_func(df, y_name, X_name):
  y = df[y_name]
  X = df[X_name]
  X = sm.add_constant(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.66666667,以及1.038462

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

最佳答案

一种选择是使用 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

关于python - pandas 中的高效扩展 OLS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59040238/

相关文章:

python - 基于 URL 的数据库路由

python - 类似于numpy的diff的功能

python - str.replace 在函数中不起作用

python - 有没有办法遍历列表并返回以其内容命名的变量?

python - 余弦波的贝叶斯拟合花费的时间比预期的要长

exception - 返回 Exception 实例而不是在 Python 中引发它有什么缺点?

python - 以同样的方式转换 CSV 文件的文件夹,然后使用 python 输出多个数据帧

python - 对多个时间序列进行分组和聚合

r - R中的高阶(或非常高阶)多项式回归(或替代?)

Python - linear_model.Lasso 的 k 折交叉验证