Question: def my _ pca ( X , n _ components ) : ' ' ' Performs PCA on X to reduce it to ` n
def mypcaX ncomponents:
Performs PCA on X to reduce it to ncomponents using the method
described in lecture but with the 'centering' of X before SVD is done.
Parameters
X: npdarray
An m n matrix where m is the number of samples and n is the
number of features which each sample has. In other words, the ith sample
is given by Xi
ncomponents: int
No of components that the reduced space has.
Returns
The tuple components singularvalues Here, components is an
ncomponents n matrix such that componentsi returns the ith
principal axis that has the ith largest singular value. In addition,
singularvalues is a D numpy array with ncomponents entries such that
singularvaluesi returns the ith singular value.
Note
'centering' here refers to subtracting the mean from X such that the resulting
X has a mean of for each feature.
# TODO: add your solution here and remove raise NotImplementedError
# no loop allowed
Xcentered X npmeanX axis
# Performing SVD
U S Vt nplinalg.svdXcentered.T
# Extracting the first ncomponents principal components
components Vt:ncomponents, :
# Extracting the corresponding singular values
singularvalues S:ncomponents
return components, singularvalues
Xtest nparray
expectedpca mypcaXtest
# Public test case
assertnot npallexpectedpca nparray
# Public test case
assertnot npallexpectedpca nparray
# Public test case
diffsingularvalues npabsexpectedpca nparray
printDifference in singular values:", diffsingularvalues
assertnpalldiffsingularvalues
# Public test case
Xtest nparray
diffsingularvalues npabsmypcaXtest nparray
assertnpalldiffsingularvalues
# Public test case
Xtest nparray
diffsingularvalues npabsmypcaXtest nparray
assertnpalldiffsingularvalues
# Public test case
Xtest nparray
