Untitled

 avatar
unknown
python
3 years ago
548 B
2
Indexable
import numpy as np

def foo(data, n=None):
    num_examples, example_dim = data.shape
    # center data
    data_mean = data.mean(axis=0)[None, :]
    centered_data = data - data_mean
    # Singular Value Decomposition (SVD)
    U, S, VT = np.linalg.svd(centered_data, full_matrices=False)
    # singular values of M
    DiagS = np.diag(S)
    if n is None:
        n = example_dim
    # PCA: calculate principal components
    PCs = U[:, :n].dot(DiagS[:n, :n])
    # transform data
    new_data = PCs.dot(VT[:n, :]) + data_mean
    return new_data