ml-finance-python

python scripts for finance machine learning

git clone https://9o.is/git/ml-finance-python.git

principal_component_analysis.py

(1247B)


      1 from __future__ import print_function, division
      2 import numpy as np
      3 from mlfromscratch.utils import calculate_covariance_matrix
      4 
      5 
      6 class PCA():
      7     """A method for doing dimensionality reduction by transforming the feature
      8     space to a lower dimensionality, removing correlation between features and
      9     maximizing the variance along each feature axis. This class is also used throughout
     10     the project to plot data.
     11     """
     12     def transform(self, X, n_components):
     13         """ Fit the dataset to the number of principal components specified in the
     14         constructor and return the transformed dataset """
     15         covariance_matrix = calculate_covariance_matrix(X)
     16 
     17         # Where (eigenvector[:,0] corresponds to eigenvalue[0])
     18         eigenvalues, eigenvectors = np.linalg.eig(covariance_matrix)
     19 
     20         # Sort the eigenvalues and corresponding eigenvectors from largest
     21         # to smallest eigenvalue and select the first n_components
     22         idx = eigenvalues.argsort()[::-1]
     23         eigenvalues = eigenvalues[idx][:n_components]
     24         eigenvectors = np.atleast_1d(eigenvectors[:, idx])[:, :n_components]
     25 
     26         # Project the data onto principal components
     27         X_transformed = X.dot(eigenvectors)
     28 
     29         return X_transformed