Skip to content

Instantly share code, notes, and snippets.

@theWrongCode-dev
Created February 5, 2020 15:45
Show Gist options
  • Save theWrongCode-dev/a0db6dc77674e9e31904fef7fdd6cd1f to your computer and use it in GitHub Desktop.
Save theWrongCode-dev/a0db6dc77674e9e31904fef7fdd6cd1f to your computer and use it in GitHub Desktop.
PCA Implemented using Python 3
import numpy as np
class PCA:
def __init__(self,n_component=None):
"""Principal component analysis (PCA) implementation.
Transforms a dataset of possibly correlated values into n linearly
uncorrelated components. The components are ordered such that the first
has the largest possible variance and each following component as the
largest possible variance given the previous components. This causes
the early components to contain most of the variability in the dataset.
Parameters
----------
n_components : int
"""
self.n_component =n_component
self.components_ =None
self.explained_variance_ = None
self.mean = None
def fit(self,data):
global values,vectors
#mean
meandata= np.mean(data.T,axis=1)
self.mean = meandata.round(2)
C = data - self.mean
# calculate covariance matrix of centered matrix
V = np.cov(C.T)
# eigendecomposition of covariance matrix
values, vectors = np.linalg.eig(V)
key = np.argsort(values)[::-1][:self.n_component]
values, vectors = values[key], vectors[:, key]
self.components_ = vectors[0:self.n_component]
self.explained_variance_ = values
@property
def variance_ratio(self):
if len(vectors)!=0:
s_squared = values** 2
variance_ratio = s_squared / (s_squared).sum()
return variance_ratio[0:self.n_component]
def transform(self, data):
meandata= np.mean(data.T,axis=1)
self.mean = meandata.round(2)
C = data - self.mean
return np.dot(C, self.components_.T)
@theWrongCode-dev
Copy link
Author

pca implemented only using python

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment