PCA mit Arpack gibt unterschiedliche Werte zurück, wenn sich die Reihenfolge der Beobachtungen ändert, aber warum?Python

Python-Programme
Anonymous
 PCA mit Arpack gibt unterschiedliche Werte zurück, wenn sich die Reihenfolge der Beobachtungen ändert, aber warum?

Post by Anonymous »

Ich habe kürzlich bemerkt, dass Scikit-Learn PCA mit SVD_Solver = "Arpack" verschiedene schwimmende Punktnummern zurückgibt, wenn ich die Reihenfolge der Beobachtungen in einem spärlichen Array ändere. Ist das ein erwartetes Verhalten? Vielen Dank im Voraus!

Code: Select all

import numpy as np
import pandas as pd
from sklearn.decomposition import PCA
import scipy.sparse as sp

# Simulate a sparse gene expression array containing two datasets, dataset1 and 2, both containing 5000 observations
n_obs = 10000 # Total number of observations
n_features = 2000 # Total number of features

# Simulate a concatenated dataset with the order of dataset1 + dataset2
rng = np.random.default_rng(42)
X1 = rng.uniform(0, 5, size=(n_obs, n_features)).astype(np.float32)

# Change the order of the datasets so that it is in the form of dataset2 + dataset1
X2 = np.concatenate((X1[5000:,], X1[:5000,]), axis=0)

X1_sparse = sp.csr_matrix(X1)
X2_sparse = sp.csr_matrix(X2)
print("Matrix 1 shape:", X1_sparse.shape, "nnz:", X1_sparse.nnz)
print("Matrix 2 shape:", X2_sparse.shape, "nnz:", X2_sparse.nnz)

# PCA with ARPACK on X1
pca1 = PCA(n_components=20, svd_solver="arpack", random_state=321)
pcs1 = pca1.fit_transform(X1_sparse.toarray())

# PCA with ARPACK on X2
pca2 = PCA(n_components=20, svd_solver="arpack", random_state=321)
pcs2 = pca2.fit_transform(X2_sparse.toarray())

# Wrap in DataFrames with fake cell IDs
obs_names = [f"cell{i}" for i in range(n_obs)]
pcs1 = pd.DataFrame(pcs1, index=obs_names)
pcs2 = pd.DataFrame(pcs2, index=obs_names[5000:] + obs_names[0:5000])
pcs2 = pcs2.loc[pcs1.index,]

# Compare results
print("\nAre components numerically close (1e-6)?",
np.allclose(np.abs(pcs1), np.abs(pcs2), atol=1e-6))

< /code>
Ich hatte erwartet, dass zwei PCA -Arrays genau gleich sind. Zum Beispiel: PCS1.ILOC [0,0] 
Gibt: -2.9909344 wob Diese beiden Antworten unterscheiden sich um 3,34E-5.>

Quick Reply

Change Text Case: 
   
  • Similar Topics
    Replies
    Views
    Last post