Untitled

Anonymous
Plain Text
09/10/2025 7:52 AM
939 B
14
Indexable
Never
import numpy as np

X = np.array([
        [2.5, 2.4],
            [0.5, 0.7],
                [2.2, 2.9],
                    [1.9, 2.2],
                        [3.1, 3.0],
                            [2.3, 2.7],
                                [2.0, 1.6],
                                    [1.0, 1.1],
                                        [1.5, 1.6],
                                            [1.1, 0.9]
])

# 1) Standardize (zero-mean, unit-variance)
X_std = (X - X.mean(axis=0)) / X.std(axis=0, ddof=1)

# 2) Covariance matrix
C = np.cov(X_std, rowvar=False)

# 3) Eigen-decomposition
eigvals, eigvecs = np.linalg.eigh(C)   # returns ascending order
pc1 = eigvecs[:, np.argmax(eigvals)]   # principal component (2,)

# 4) Project to 1-D
X_1d = X_std @ pc1                     # (n_samples,)

print("PC1 direction:", pc1)
print("1-D scores:", X_1d)
print("Explained variance ratio of PC1:", np.max(eigvals) / np.sum(eigvals))
])
Editor is loading...
Leave a Comment