Created
January 6, 2021 07:53
-
-
Save saimadhu-polamuri/1e59c715d9eaa01248450793975e1754 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class convers_pca(): | |
def __init__(self, no_of_components): | |
self.no_of_components = no_of_components | |
self.eigen_values = None | |
self.eigen_vectors = None | |
def transform(self, a): | |
return np.dot(a - self.mean, self.projection_matrix.T) | |
def inverse_transform(self, a): | |
return np.dot(a, self.projection_matrix) + self.mean | |
def fit(self, a): | |
self.no_of_components = a.shape[1] if self.no_of_components is None else self.no_of_components | |
self.mean = np.mean(a, axis=0) | |
cov_matrix = np.cov(a - self.mean, rowvar=False) | |
self.eigen_values, self.eigen_vectors = np.linalg.eig(cov_matrix) | |
self.eigen_vectors = self.eigen_vectors.T | |
self.sorted_components = np.argsort(self.eigen_values)[::-1] | |
self.projection_matrix = self.eigen_vectors[ | |
self.sorted_components[ | |
:self.no_of_components]]self.explained_variance = self.eigen_values[ | |
self.sorted_components] | |
self.explained_variance_ratio = self.explained_variance / self.eigen_values.sum() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment