Skip to main content

lib_jsl_machine_learning/unsupervised/reduction/
principal_component_analysis.rs

1//! Principal component analysis.
2//!
3//! See the book entry [Principal component analysis and kernel PCA](https://jwkunz.github.io/lib_jsl/book/unsupervised/pca.html).
4
5use crate::common::{Transformer, check_features};
6use lib_jsl_core::{ErrorsJSL, R1D, R2D, VR2D};
7use lib_jsl_linalg::{Eigh, UPLO};
8
9/// PCA: finds orthogonal directions (principal components) of greatest variance and projects the
10/// data onto the first `components` of them. Computed from the eigendecomposition of the
11/// covariance matrix of the centred data. The leading components capture most of the structure in
12/// correlated data, so a few of them often summarise many features.
13#[derive(Debug, Clone)]
14pub struct Pca {
15    components: usize,
16    mean: R1D,
17    /// Rows are the principal axes (unit vectors), in order of decreasing variance.
18    axes: R2D,
19    variances: Vec<f64>,
20    total_variance: f64,
21}
22
23impl Pca {
24    /// Keeps `components` principal components.
25    pub fn new(components: usize) -> Self {
26        Pca { components, mean: R1D::zeros(0), axes: R2D::zeros((0, 0)), variances: Vec::new(), total_variance: 0.0 }
27    }
28
29    /// The principal axes, one per row.
30    pub fn components(&self) -> &R2D {
31        &self.axes
32    }
33
34    /// The variance along each kept component.
35    pub fn explained_variance(&self) -> &[f64] {
36        &self.variances
37    }
38
39    /// The fraction of the total variance each kept component explains.
40    pub fn explained_variance_ratio(&self) -> Vec<f64> {
41        self.variances.iter().map(|v| if self.total_variance > 0.0 { v / self.total_variance } else { 0.0 }).collect()
42    }
43
44    pub fn mean(&self) -> &R1D {
45        &self.mean
46    }
47
48    /// Maps component scores back to the original feature space (a lossy reconstruction when
49    /// fewer components than features were kept).
50    pub fn inverse_transform(&self, z: VR2D) -> Result<R2D, ErrorsJSL> {
51        if self.axes.nrows() == 0 {
52            return Err(ErrorsJSL::Misconfiguration("The model has not been fitted."));
53        }
54        if z.ncols() != self.axes.nrows() {
55            return Err(ErrorsJSL::IncompatibleArraySizes((z.ncols(), self.axes.nrows())));
56        }
57        Ok(z.dot(&self.axes) + &self.mean)
58    }
59}
60
61impl Transformer for Pca {
62    fn fit(&mut self, x: VR2D) -> Result<(), ErrorsJSL> {
63        check_features(x)?;
64        let (n, p) = x.dim();
65        if n < 2 || self.components == 0 || self.components > p {
66            return Err(ErrorsJSL::InvalidInputRange("Need at least two samples and 1 <= components <= features."));
67        }
68        // ANCHOR: pca_fit
69        self.mean = x.mean_axis(ndarray::Axis(0)).expect("non-empty");
70        let centred = &x - &self.mean;
71        let cov = centred.t().dot(&centred) / (n as f64 - 1.0);
72        let (vals, vecs) = cov.eigh(UPLO::Lower).map_err(|_| ErrorsJSL::RuntimeError("The covariance eigendecomposition failed."))?;
73        // eigh returns ascending eigenvalues; take the largest.
74        let order: Vec<usize> = (0..p).rev().take(self.components).collect();
75        self.variances = order.iter().map(|&i| vals[i].max(0.0)).collect();
76        self.total_variance = vals.iter().map(|v| v.max(0.0)).sum();
77        self.axes = R2D::from_shape_fn((self.components, p), |(c, j)| vecs[[j, order[c]]]);
78        // ANCHOR_END: pca_fit
79        // Sign convention: make the largest-magnitude loading of each axis positive, so results
80        // are reproducible.
81        for mut axis in self.axes.rows_mut() {
82            let big = axis.iter().copied().fold(0.0f64, |m, v| if v.abs() > m.abs() { v } else { m });
83            if big < 0.0 {
84                axis.mapv_inplace(|v| -v);
85            }
86        }
87        Ok(())
88    }
89
90    fn transform(&self, x: VR2D) -> Result<R2D, ErrorsJSL> {
91        if self.axes.nrows() == 0 {
92            return Err(ErrorsJSL::Misconfiguration("The model has not been fitted."));
93        }
94        check_features(x)?;
95        if x.ncols() != self.mean.len() {
96            return Err(ErrorsJSL::IncompatibleArraySizes((x.ncols(), self.mean.len())));
97        }
98        Ok((&x - &self.mean).dot(&self.axes.t()))
99    }
100}
101
102#[cfg(test)]
103mod tests {
104    use super::*;
105    use crate::common::MlRng;
106    use ndarray::{Array2, arr2};
107
108    /// Data stretched along (1, 1)/√2 with standard deviation 3, and 0.3 across it.
109    fn stretched(n: usize, seed: u64) -> Array2<f64> {
110        let mut rng = MlRng::new(seed);
111        let pts: Vec<(f64, f64)> = (0..n).map(|_| (rng.gaussian(0.0, 3.0), rng.gaussian(0.0, 0.3))).collect();
112        let s = std::f64::consts::FRAC_1_SQRT_2;
113        Array2::from_shape_fn((n, 2), |(i, j)| if j == 0 { s * (pts[i].0 - pts[i].1) + 5.0 } else { s * (pts[i].0 + pts[i].1) - 2.0 })
114    }
115
116    #[test]
117    fn finds_the_dominant_axis_and_variances() {
118        let x = stretched(2000, 1);
119        let mut p = Pca::new(2);
120        p.fit(x.view()).unwrap();
121        let axis = p.components().row(0);
122        assert!((axis[0].abs() - std::f64::consts::FRAC_1_SQRT_2).abs() < 0.02 && axis[0] * axis[1] > 0.0);
123        assert!((p.explained_variance()[0] - 9.0).abs() < 0.8 && (p.explained_variance()[1] - 0.09).abs() < 0.02);
124        let ratio = p.explained_variance_ratio();
125        assert!((ratio.iter().sum::<f64>() - 1.0).abs() < 1e-12 && ratio[0] > 0.98);
126        assert!((p.mean()[0] - 5.0).abs() < 0.2 && (p.mean()[1] + 2.0).abs() < 0.2);
127    }
128
129    #[test]
130    fn projection_is_decorrelated_and_reconstruction_is_exact_with_all_components() {
131        let x = stretched(500, 2);
132        let mut p = Pca::new(2);
133        let z = p.fit_transform(x.view()).unwrap();
134        let cz = z.t().dot(&z) / 499.0;
135        assert!(cz[[0, 1]].abs() < 1e-9); // scores are uncorrelated
136        let back = p.inverse_transform(z.view()).unwrap();
137        assert!(back.iter().zip(x.iter()).all(|(a, b)| (a - b).abs() < 1e-9));
138        // One component: lossy but close, since almost all variance lies on one axis.
139        let mut one = Pca::new(1);
140        let z1 = one.fit_transform(x.view()).unwrap();
141        assert_eq!(z1.dim(), (500, 1));
142        let approx = one.inverse_transform(z1.view()).unwrap();
143        let err = approx.iter().zip(x.iter()).map(|(a, b)| (a - b).powi(2)).sum::<f64>() / 500.0;
144        assert!(err < 0.3, "{err}");
145        // Axes are orthonormal.
146        let g = p.components().dot(&p.components().t());
147        assert!((g[[0, 0]] - 1.0).abs() < 1e-12 && g[[0, 1]].abs() < 1e-12);
148    }
149
150    #[test]
151    fn errors() {
152        let x = arr2(&[[1.0, 2.0], [3.0, 4.0], [5.0, 7.0]]);
153        assert!(Pca::new(0).fit(x.view()).is_err() && Pca::new(3).fit(x.view()).is_err());
154        assert!(Pca::new(1).fit(arr2(&[[1.0, 2.0]]).view()).is_err());
155        assert!(Pca::new(1).transform(x.view()).is_err());
156        assert!(Pca::new(1).inverse_transform(x.view()).is_err());
157        let mut p = Pca::new(1);
158        p.fit(x.view()).unwrap();
159        assert!(p.transform(arr2(&[[1.0, 2.0, 3.0]]).view()).is_err());
160        assert!(p.inverse_transform(arr2(&[[1.0, 2.0]]).view()).is_err());
161    }
162}