Loading…
DS · Recommenders & reduction · Program 28 · Bonus
SVD for dimensionality reduction.
1import numpy as np2from sklearn.datasets import load_digits3from sklearn.decomposition import TruncatedSVD4 5A = np.array([[3, 1, 1], [-1, 3, 1], [2, 2, 2], [1, 0, 4]], dtype=float)6U, S, Vt = np.linalg.svd(A, full_matrices=False)7print("Singular Values:", S.round(4))8print("Rank-2 Approximation:\n", (U[:, :2] @ np.diag(S[:2]) @ Vt[:2]).round(4))9 10X = load_digits().data11svd = TruncatedSVD(n_components=20, random_state=42)12X_reduced = svd.fit_transform(X)13print("\nOriginal Shape:", X.shape)14print("Reduced Shape:", X_reduced.shape)15print("Variance Kept:", svd.explained_variance_ratio_.sum())Singular Values: [5.7605 3.2422 2.7027] Rank-2 Approximation: [[ 1.9225 0.3353 2.0951] [-0.9314 3.0423 0.9303] [ 1.5023 1.693 2.5058] [ 2.2701 0.7835 2.7092]] Original Shape: (1797, 64) Reduced Shape: (1797, 20) Variance Kept: 0.8940622384867832
Run program 28 in your browser
Python 3.14 · Pyodide. Change the code or the input, run it, break it, and see what happens.