PCA via SVD
Xem dạng PDF
Gửi bài giải
Điểm:
100,00
Giới hạn thời gian:
2.0s
Giới hạn bộ nhớ:
256M
Tác giả:
Dạng bài
Ngôn ngữ cho phép
Python
Problem Statement
Implement Principal Component Analysis (PCA) using Singular Value Decomposition (SVD). Return the top k principal components and their explained variance ratios.
Algorithm:
- Center the data:
X_c = X - mean(X, axis=0) - Compute the thin SVD:
X_c = U S Vᵀ - The top
kprincipal components are the firstkrows ofVᵀ - The variance explained by each component is
S_i² / Σ S_j²
Function signature:
def pca_svd(X: list, k: int) -> tuple:
# returns (components, ratios)
# components: k x d list of lists — principal component vectors
# ratios: list of k floats — explained variance ratios
Input Format
Line 1: n d k — number of points, dimensions, components to return
Lines 2..n+1: space-separated floats — data matrix rows
Output Format
k lines: the principal component vectors (10 significant figures each)
k lines: one explained variance ratio per line (10 significant figures)
Example
Input:
4 2 2
2.0 0.0
0.0 2.0
-2.0 0.0
0.0 -2.0
Output:
-1 -0
-0 -1
0.5
0.5
Notes
- Use
numpy.linalg.svdwithfull_matrices=Falsefor the thin decomposition. - Principal components are rows of
Vᵀ; their signs may vary by implementation (both+vand-vare valid). - The explained variance ratios sum to ≤ 1 for
k < d, and exactly 1 fork = d.
Bình luận