#NEWLINE# def pca( data , keepdim = 0 , normalize = 0 , demean = True ) : #NEWLINE# #INDENT# 'principal components with eigenvector decomposition\n    similar to princomp in matlab\n\n    Parameters\n    ----------\n    data : ndarray, 2d\n        data with observations by rows and variables in columns\n    keepdim : integer\n        number of eigenvectors to keep\n        if keepdim is zero, then all eigenvectors are included\n    normalize : boolean\n        if true, then eigenvectors are normalized by sqrt of eigenvalues\n    demean : boolean\n        if true, then the column mean is subtracted from the data\n\n    Returns\n    -------\n    xreduced : ndarray, 2d, (nobs, nvars)\n        projection of the data x on the kept eigenvectors\n    factors : ndarray, 2d, (nobs, nfactors)\n        factor matrix, given by np.dot(x, evecs)\n    evals : ndarray, 2d, (nobs, nfactors)\n        eigenvalues\n    evecs : ndarray, 2d, (nobs, nfactors)\n        eigenvectors, normalized if normalize is true\n\n    Notes\n    -----\n\n    See Also\n    --------\n    pcasvd : principal component analysis using svd\n\n    ' #NEWLINE# x = np . array ( data ) #NEWLINE# if demean : #NEWLINE# #INDENT# m = x . mean ( 0 ) #NEWLINE# #UNINDENT# else : #NEWLINE# #INDENT# m = np . zeros ( x . shape [ 1 ] ) #NEWLINE# #UNINDENT# x -= m #NEWLINE# xcov = np . cov ( x , rowvar = 0 ) #NEWLINE# ( evals , evecs ) = np . linalg . eig ( xcov ) #NEWLINE# indices = np . argsort ( evals ) #NEWLINE# indices = indices [ : : ( - 1 ) ] #NEWLINE# evecs = evecs [ : , indices ] #NEWLINE# evals = evals [ indices ] #NEWLINE# if ( ( keepdim > 0 ) and ( keepdim < x . shape [ 1 ] ) ) : #NEWLINE# #INDENT# evecs = evecs [ : , : keepdim ] #NEWLINE# evals = evals [ : keepdim ] #NEWLINE# #UNINDENT# if normalize : #NEWLINE# #INDENT# evecs = ( evecs / np . sqrt ( evals ) ) #NEWLINE# #UNINDENT# factors = np . dot ( x , evecs ) #NEWLINE# xreduced = ( np . dot ( evecs , evecs . T ) + m ) #NEWLINE# return ( xreduced , factors , evals , evecs )