我想探索在 pandas(或其他接受 DataFrame/Series 友好的库)中高效执行扩展 OLS 的解决方案。
- 假设数据集很大,我对任何带有 for 循环的解决方案都不感兴趣;
- 我正在寻找有关扩展而不是滚动的解决方案。滚动函数始终需要固定窗口,而扩展函数则使用可变窗口(从头开始);
- 请不要建议使用
pandas.stats.ols.MovingOLS
,因为它已被弃用; - 请不要建议其他已弃用的方法,例如
expanding_mean
。
例如,有一个包含两列 X
和 y
的 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/