Search code examples
pythonnumpypca

How do I properly return an array after iterating and doing PCA


I have a 3d array (sample, timestep, feature) named x_train in which I want to iterate through and perform PCA on the 2D array (timestep, feature) for every sample. I have this code, but because it returns a 5x1 array, I am having issues returning values:

from sklearn.decomposition import PCA
pca = PCA(n_components=1)
X_transform_PCA = np.zeros((x_train.shape[0], 1))
for i in range(x_train.shape[0]):
    pca = PCA(n_components=1)
    f  = pca.fit_transform(x_train[i, :, :])
    X_transform_PCA[i,:] = f
print(X_transform_PCA.shape[0])

Solution

  • I figured it out. Looks like this did the trick.

    X_transform_PCA = []
    
    from sklearn.decomposition import PCA
    pca = PCA(n_components=1)
    for i in range(x_train.shape[0]):
        pca = PCA(n_components=1)
        f  = pca.fit_transform(x_train[i, :, :])
        X_transform_PCA.append(f)
    print(X_transform_PCA)