Test PCA equivalence.
(n_components, whiten)
| 437 | @pytest.mark.parametrize("n_components", (None, 0.9999, 8, "mle")) |
| 438 | @pytest.mark.parametrize("whiten", (True, False)) |
| 439 | def test_pca(n_components, whiten): |
| 440 | """Test PCA equivalence.""" |
| 441 | pytest.importorskip("sklearn") |
| 442 | from sklearn.decomposition import PCA |
| 443 | |
| 444 | n_samples, n_dim = 1000, 10 |
| 445 | X = np.random.RandomState(0).randn(n_samples, n_dim) |
| 446 | X[:, -1] = np.mean(X[:, :-1], axis=-1) # true X dim is ndim - 1 |
| 447 | X_orig = X.copy() |
| 448 | pca_skl = PCA(n_components, whiten=whiten, svd_solver="full") |
| 449 | pca_mne = _PCA(n_components, whiten=whiten) |
| 450 | X_skl = pca_skl.fit_transform(X) |
| 451 | assert_array_equal(X, X_orig) |
| 452 | X_mne = pca_mne.fit_transform(X) |
| 453 | assert_array_equal(X, X_orig) |
| 454 | assert_allclose(X_skl, X_mne * np.sign(np.sum(X_skl * X_mne, axis=0))) |
| 455 | assert pca_mne.n_components_ == pca_skl.n_components_ |
| 456 | for key in ( |
| 457 | "mean_", |
| 458 | "components_", |
| 459 | "explained_variance_", |
| 460 | "explained_variance_ratio_", |
| 461 | ): |
| 462 | val_skl, val_mne = getattr(pca_skl, key), getattr(pca_mne, key) |
| 463 | if key == "components_": |
| 464 | val_mne = val_mne * np.sign( |
| 465 | np.sum(val_skl * val_mne, axis=1, keepdims=True) |
| 466 | ) |
| 467 | assert_allclose(val_skl, val_mne) |
| 468 | if isinstance(n_components, float): |
| 469 | assert pca_mne.n_components_ == n_dim - 1 |
| 470 | elif isinstance(n_components, int): |
| 471 | assert pca_mne.n_components_ == n_components |
| 472 | elif n_components == "mle": |
| 473 | assert pca_mne.n_components_ == n_dim - 1 |
| 474 | else: |
| 475 | assert n_components is None |
| 476 | assert pca_mne.n_components_ == n_dim |
| 477 | |
| 478 | |
| 479 | def test_array_equal_nan(): |
nothing calls this directly
no test coverage detected