from _api_doc_utils import *PCA
Principal-components transformer
1 Where it fits
Group: Transforms
PCA learns an orthogonal low-rank basis from a design matrix. It centers the training data, computes principal directions, and maps observations to component scores:
\[ Z = (X - \bar X) V_k. \]
With whiten=True, scores are rescaled by the singular values.
2 Python API
Constructor: cm.PCA
Use PCA(n_components, whiten=False). fit(x) stores the basis, transform(x) maps new data to scores, fit_transform(x) combines both, and inverse_transform(scores) reconstructs approximate original features. summary() exposes components, means, explained variance, ratios, and singular values.
print(inspect.signature(cm.PCA))(n_components, whiten=False)
cls = cm.PCA
display(HTML(html_table(["Public method"], public_methods(cls))))| Public method |
|---|
fit(self, /, x) |
fit_transform(self, /, x) |
inverse_transform(self, /, scores) |
summary(self, /) |
transform(self, /, x) |
3 Minimal example
rng=np.random.default_rng(22)
x=rng.normal(size=(150,5)) @ np.array([[1,.2,.1,0,0],[0,.8,.3,.1,0],[0,0,.5,.2,.1],[0,0,0,.3,.2],[0,0,0,0,.1]])
model=cm.PCA(n_components=2); scores=model.fit_transform(x)
print(scores.shape)
print(model.summary()["explained_variance_ratio"])
print(model.inverse_transform(scores[:2]))(150, 2)
[0.62644017 0.37355983]
[[-1.40550383 -1.36130695 -1.01359223 -0.47915055 -0.19206572]
[-1.57694267 0.65071588 0.38647668 0.29693871 0.11740384]]
4 summary() contract
The table below is generated by fitting the live class in this repository and then inspecting summary(). Shapes are shown because most values are plain NumPy arrays or scalars.
rng=np.random.default_rng(122); x=rng.normal(size=(80,5)); model=cm.PCA(n_components=2); model.fit(x)
summary = model.summary()
display(HTML(html_table(["summary() key", "shape"], summary_shape_rows(summary))))| summary() key | shape |
|---|---|
n_components |
() |
n_features |
() |
whiten |
() |
components |
(2, 5) |
mean |
(5,) |
explained_variance |
(2,) |
explained_variance_ratio |
(2,) |
singular_values |
(2,) |