flow_clustering/clustering/
gmm.rs1use crate::clustering::{ClusteringError, ClusteringResult};
4use linfa::prelude::*;
5use linfa_clustering::GaussianMixtureModel as LinfaGmm;
6use ndarray::Array2;
7
8#[derive(Debug, Clone)]
10pub struct GmmConfig {
11 pub n_components: usize,
13 pub max_iterations: usize,
15 pub tolerance: f64,
17 pub seed: Option<u64>,
19}
20
21impl Default for GmmConfig {
22 fn default() -> Self {
23 Self {
24 n_components: 2,
25 max_iterations: 100,
26 tolerance: 1e-3,
27 seed: None,
28 }
29 }
30}
31
32#[derive(Debug, Clone)]
34pub struct GmmResult {
35 pub assignments: Vec<usize>,
37 pub means: Array2<f64>,
39 pub iterations: usize,
41 pub log_likelihood: f64,
43}
44
45pub struct Gmm;
47
48impl Gmm {
49 pub fn fit_from_rows(
60 data_rows: Vec<Vec<f64>>,
61 config: &GmmConfig,
62 ) -> ClusteringResult<GmmResult> {
63 if data_rows.is_empty() {
64 return Err(ClusteringError::EmptyData);
65 }
66 let n_features = data_rows[0].len();
67 let n_samples = data_rows.len();
68
69 let flat: Vec<f64> = data_rows.into_iter().flatten().collect();
71 let data = Array2::from_shape_vec((n_samples, n_features), flat).map_err(|e| {
72 ClusteringError::ClusteringFailed(format!("Failed to create array: {:?}", e))
73 })?;
74
75 Self::fit(&data, config)
76 }
77
78 pub fn fit(data: &Array2<f64>, config: &GmmConfig) -> ClusteringResult<GmmResult> {
87 if data.nrows() == 0 {
88 return Err(ClusteringError::EmptyData);
89 }
90
91 if data.nrows() < config.n_components {
92 return Err(ClusteringError::InsufficientData {
93 min: config.n_components,
94 actual: data.nrows(),
95 });
96 }
97
98 let dataset = DatasetBase::new(data.clone(), ());
101 let model = LinfaGmm::params(config.n_components)
102 .max_n_iterations(config.max_iterations as u64)
103 .tolerance(config.tolerance)
104 .fit(&dataset)
105 .map_err(|e| ClusteringError::ClusteringFailed(format!("{}", e)))?;
106
107 let assignments: Vec<usize> = (0..data.nrows())
110 .map(|i| {
111 let point = data.row(i);
112 let mut max_prob = f64::NEG_INFINITY;
113 let mut best_component = 0;
114 for (j, mean) in model.means().rows().into_iter().enumerate() {
116 let dist: f64 = point
117 .iter()
118 .zip(mean.iter())
119 .map(|(a, b)| (a - b).powi(2))
120 .sum();
121 let prob = (-dist).exp(); if prob > max_prob {
123 max_prob = prob;
124 best_component = j;
125 }
126 }
127 best_component
128 })
129 .collect();
130
131 let means = model.means().to_owned();
133
134 Ok(GmmResult {
135 assignments,
136 means,
137 iterations: config.max_iterations, log_likelihood: 0.0, })
140 }
141}