def test_randomized_pca_inverse(self): # Test that randomized PCA is inversible on dense data rng = np.random.RandomState(0) n, p = 50, 3 X = mt.tensor(rng.randn(n, p)) # spherical data X[:, 1] *= .00001 # make middle component relatively small X += [5, 4, 3] # make a large mean # same check that we can find the original data from the transformed signal # (since the data is almost of rank n_components) pca = PCA(n_components=2, svd_solver='randomized', random_state=0).fit(X) Y = pca.transform(X) Y_inverse = pca.inverse_transform(Y) assert_almost_equal(X.to_numpy(), Y_inverse.to_numpy(), decimal=2) # same as above with whitening (approximate reconstruction) pca = PCA(n_components=2, whiten=True, svd_solver='randomized', random_state=0).fit(X) Y = pca.transform(X) Y_inverse = pca.inverse_transform(Y) relative_max_delta = (mt.abs(X - Y_inverse) / mt.abs(X).mean()).max() self.assertLess(relative_max_delta.to_numpy(), 1e-5)
def test_pca_inverse(self): # Test that the projection of data can be inverted rng = np.random.RandomState(0) n, p = 50, 3 X = mt.tensor(rng.randn(n, p)) # spherical data X[:, 1] *= .00001 # make middle component relatively small X += [5, 4, 3] # make a large mean # same check that we can find the original data from the transformed # signal (since the data is almost of rank n_components) pca = PCA(n_components=2, svd_solver='full').fit(X) Y = pca.transform(X) Y_inverse = pca.inverse_transform(Y) assert_almost_equal(X.to_numpy(), Y_inverse.to_numpy(), decimal=3) # same as above with whitening (approximate reconstruction) for solver in self.solver_list: pca = PCA(n_components=2, whiten=True, svd_solver=solver) pca.fit(X) Y = pca.transform(X) Y_inverse = pca.inverse_transform(Y) assert_almost_equal(X.to_numpy(), Y_inverse.to_numpy(), decimal=3)