Skip to content

Instantly share code, notes, and snippets.

@tanveer-sayyed
Last active May 15, 2019 09:34
Show Gist options
  • Save tanveer-sayyed/3c17d6f7e885990b1d97b23f42acb425 to your computer and use it in GitHub Desktop.
Save tanveer-sayyed/3c17d6f7e885990b1d97b23f42acb425 to your computer and use it in GitHub Desktop.
draw edits
import matplotlib.pyplot as plt
import numpy as np
from numpy import array
from sklearn.decomposition import PCA
D = array([[1, 1],[2, 2],[3, 3],[4, 4],[5, 5], # Matrix D has all the
[6, 6],[7, 7],[8, 8],[9, 9]]) # points on line x = y
# Adding noise:
E = np.zeros(np.shape(D))
E = D + np.random.rand(np.shape(D)[0], np.shape(D)[1])
from sklearn.preprocessing import MinMaxScaler
E = MinMaxScaler().fit_transform(E)
D = MinMaxScaler().fit_transform(D.astype(float))
# create the transform
pca = PCA(1)
# fit transform
pca.fit(E)
# access values and vectors
print('EigenVector(PCA component): ', pca.components_)
print('Explained variance: ', pca.explained_variance_)
F = pca.transform(E)
E_projected = pca.inverse_transform(F)
plt.figure(figsize=(15,5))
plt.subplot(1,2,1)
plt.scatter(D[:,0], D[:,1], color= 'lime', label = 'true data')
plt.scatter(E[:,0], E[:,1], color= 'black', label= 'after noise addition')
plt.xticks(np.arange(0, 1.1, .1))
plt.yticks(np.arange(0, 1.1, .1))
plt.legend()
plt.subplot(1,2,2)
plt.scatter(D[:,0], D[:,1], color= 'lime', label = 'true data')
plt.scatter(E_projected[:, 0], E_projected[:, 1],
color = 'red', label= 'PCA projection of noisy data')
pca.components_[0] = pca.components_[0] / min(pca.components_[0])
plt.quiver(*([0,0]), pca.components_[0][0], pca.components_[0][1],
angles='xy', scale_units='xy', scale=1, color='pink',
alpha = 0.6, label= 'Principle Component(Rescaled Eigenvector)')
plt.xticks(np.arange(0, 1.1, .1))
plt.yticks(np.arange(0, 1.1, .1))
plt.legend()
plt.show()
Output:
EigenVector(PCA component): [[0.73552669 0.67749575]]
Explained variance: [0.22817895]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment