Author - Mohit Rathore mrmohitrathoremr@gmail.com - markroxor.in
Licensed under The MIT License - https://opensource.org/licenses/MIT
from fromscratchtoml.decomposition import Decomposition
from fromscratchtoml.toolbox import binary_visualize
import numpy as np
# set this to avoid exponential notations
np.set_printoptions(suppress=True)
%matplotlib inline
n = 10
n_dim = 3
nc = 3
X = np.zeros([n, n_dim])
for i in range(n):
X[i,2] = i
X[i,1] = 5*i + 2
# X[i,1] = pow(i,2)
X[i,0] = (5 - 2*X[i,0] - 3*X[i,1])/2
X
xy = np.vstack([X[:, 0], X[:, 1]]).T
binary_visualize(xy, xlabel="x", title="original data",
ylabel="y")
zx = np.vstack([X[:, 2], X[:, 0]]).T
binary_visualize(zx, xlabel="z", title="original data",
ylabel="x")
zy = np.vstack([X[:, 2], X[:, 1]]).T
binary_visualize(zy, xlabel="z", title="original data",
ylabel="y")
principal_components, scaled_X = Decomposition.pca(X, num_components=nc, return_scaled=True)
xy = np.vstack([scaled_X[:, 0], scaled_X[:, 1]]).T
binary_visualize(xy, xlabel="x", title="scaled data",
ylabel="y")
yz = np.vstack([scaled_X[:, 1], scaled_X[:, 2]]).T
binary_visualize(yz, xlabel="y", title="scaled data",
ylabel="z")
xz = np.vstack([scaled_X[:, 0], scaled_X[:, 2]]).T
binary_visualize(xz, xlabel="x", title="scaled data",
ylabel="z")
principal_components
scaled_X
reconstructed_x = np.dot(scaled_X, principal_components.T) + X.mean(axis=0)
print(reconstructed_x)
np.allclose(X, reconstructed_x)