Principal Component Analysis
medium· Machine Learningruns: 0Implement PCA for dimensionality reduction. Center the data, compute the covariance matrix, find its eigenvectors, sort them by eigenvalue in descending order, and use the top k as the projection. Provide fit, transform, and fit_transform.
sign in to paste and practice your own solution
wpm 0acc 100%time 0:000 / 689
import numpy as np
class PCA:
def __init__(self, n_components: int):
self.n_components = n_components
self.components = None
self.mean = None
def fit(self, X):
self.mean = X.mean(axis=0)
centered = X - self.mean
cov = np.cov(centered, rowvar=False)
eigenvalues, eigenvectors = np.linalg.eigh(cov)
order = np.argsort(eigenvalues)[::-1]
eigenvectors = eigenvectors[:, order]
self.components = eigenvectors[:, : self.n_components]
return self
def transform(self, X):
return (X - self.mean) @ self.components
def fit_transform(self, X):
return self.fit(X).transform(X)
click the box to focus · tab inserts 4 spaces · backspace to correct · esc to pause
desktop only
codedrill is a typing game and needs a real keyboard. open this on a laptop or desktop to practice.
you can still browse problems and sections from your phone.