我不觉得其他答案令人满意。主要是因为您应该同时考虑数据的时间序列结构和横截面信息。您不能简单地将每个实例的特征视为一个系列。这样做会不可避免地导致信息丢失,而且简单地说,在统计上是错误的。
也就是说,如果你真的需要去 PCA,你至少应该保留时间序列信息:
主成分分析
在silgon之后,我们将数据转换成一个numpy数组:
# your 1000 pandas instances
instances = [pd.DataFrame(data=np.random.normal(0, 1, (300, 20))) for _ in range(1000)]
# transformation to be able to process more easily the data as a numpy array
data=np.array([d.values for d in instances])
这使得应用 PCA 更容易:
reshaped_data = data.reshape((1000*300, 20)) # create one big data panel with 20 series and 300.000 datapoints
n_comp=10 #choose the number of features to have after dimensionality reduction
pca = PCA(n_components=n_comp) #create the pca object
pca.fit(pre_data) #fit it to your transformed data
transformed_data=np.empty([1000,300,n_comp])
for i in range(len(data)):
transformed_data[i]=pca.transform(data[i]) #iteratively apply the transformation to each instance of the original dataset
最终输出形状:transformed_data.shape: Out[]: (1000,300,n_comp)。
PLS
但是,您可以(并且在我看来应该)使用偏最小二乘法PLS从特征矩阵构造因子。这也将进一步降低维度。
假设您的数据具有以下形状。 T=1000, N=300, P=20.
那么我们有 y=[T,1], X=[N,P,T]。
现在,很容易理解,要使其工作,我们需要将矩阵设为conformable for multiplication。在我们的例子中,我们将有:y=[T,1]=[1000,1], Xpca=[T,P* N]=[1000,20*300]
直观地说,我们所做的是为每个 P=20 基本特征的每个滞后 (299=N-1) 创建一个新特征。
即对于给定的实例i,我们将有这样的东西:
实例i:
x1,i, x1,i-1,..., x1,ij, x2,i, x2,i-1,..., x2,ij,..., xP,i, xP,i-1,..., xP,ij with j=1,...,N-1:
现在,在 python 中实现 PLS 非常简单。
# your 1000 pandas instances
instances = [pd.DataFrame(data=np.random.normal(0, 1, (300, 20))) for _ in range(1000)]
# transformation to be able to process more easily the data as a numpy array
data=np.array([d.values for d in instances])
# reshape your data:
reshaped_data = data.reshape((1000, 20*300))
from sklearn.cross_decomposition import PLSRegression
n_comp=10
pls_obj=PLSRegression(n_components=n_comp)
factorsPLS=pls_obj.fit_transform(reshaped_data,y)[0]
factorsPLS.shape
Out[]: (1000, n_comp)
PLS 在做什么?
为了让事情更容易掌握,我们可以查看three-pass regression filter(工作文件here)(3PRF)。 Kelly 和 Pruitt 表明 PLS 只是他们 3PRF 的一个特例:
()
其中 Z 表示代理矩阵。我们没有这些,但幸运的是,凯利和普鲁伊特已经证明我们可以没有它。我们需要做的就是确保回归量(我们的特征)是标准化的,并在没有截距的情况下运行前两个回归。这样做会自动选择代理。
所以,简而言之,PLS 允许您
- 比 PCA 实现进一步的降维。
- 在创建因子时同时考虑特征之间的横截面变异性和每个序列的时间序列信息。