【问题标题】:Rolling PCA on pandas dataframe在熊猫数据框上滚动 PCA
【发布时间】:2017-08-28 23:46:04
【问题描述】:

我想知道是否有人知道如何在 pandas 数据帧上实现滚动/移动窗口 PCA。我环顾四周,发现了 R 和 MATLAB 中的实现,但没有找到 Python。任何帮助将不胜感激!

这不是重复的 - 移动窗口 PCA 与整个数据帧上的 PCA 不同。不明白区别请看pandas.DataFrame.rolling()

【问题讨论】:

  • 那太宽泛了。描述你到底想要什么,以及在你的数据帧上使用一个简单的 for 循环有什么问题,每个循环都使用 sklearn 的 pca?您提到其他语言的类似工具,但没有链接或任何正式描述。
  • 为什么要滚动 PCA?从统计的角度来看,这没有意义。
  • 与您需要滚动平均值或滚动标准差的原因相同。基础数据是时间序列

标签: python pandas pca


【解决方案1】:

不幸的是,pandas.DataFrame.rolling() 似乎在滚动之前将 df 展平,因此它不能像预期的那样滚动 df 的行并将行窗口传递给 PCA。

以下是基于滚动索引而不是行的解决方法。它可能不是很优雅,但很有效:

# Generate some data (1000 time points, 10 features)
data = np.random.random(size=(1000,10))
df = pd.DataFrame(data)

# Set the window size
window = 100

# Initialize an empty df of appropriate size for the output
df_pca = pd.DataFrame( np.zeros((data.shape[0] - window + 1, data.shape[1])) )

# Define PCA fit-transform function
# Note: Instead of attempting to return the result, 
#       it is written into the previously created output array.
def rolling_pca(window_data):
    pca = PCA()
    transf = pca.fit_transform(df.iloc[window_data])
    df_pca.iloc[int(window_data[0])] = transf[0,:]
    return True

# Create a df containing row indices for the workaround
df_idx = pd.DataFrame(np.arange(df.shape[0]))

# Use `rolling` to apply the PCA function
_ = df_idx.rolling(window).apply(rolling_pca)

# The results are now contained here:
print df_pca

快速检查显示,由此产生的值与通过手动切片适当的窗口并在其上运行 PCA 计算的控制值相同。

【讨论】:

  • 这在运行时是否等同于手动切片并在每个切片上执行独立的 PCA?或者有什么东西可以让你在每次踏上窗户时重用现有的 PCA,从而节省时间?
  • 相当于独立的PCA。尝试找到一种方法来保留现有的 PCA 会很有趣。也许 scikit-learn 的 IncrementalPCA 可以作为灵感。
  • 我一直在调查,但 IPCA 无法删除记录,所以这只是解决方案的一半
  • 代码给了我一个 keyerror: 0 at this line --> df_pca.iloc[int(window_data[0])] = transf[0,:]..知道为什么会这样吗?
  • 尝试 window_data.iloc[0],因为它是 pd.Series
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-03-31
  • 1970-01-01
  • 1970-01-01
  • 2019-01-25
  • 1970-01-01
  • 2020-04-23
  • 2019-03-21
相关资源
最近更新 更多