use crate::clustering::{ClusteringError, ClusteringResult};
use linfa::prelude::*;
use linfa_clustering::GaussianMixtureModel as LinfaGmm;
use ndarray::Array2;
#[derive(Debug, Clone)]
pub struct GmmConfig {
pub n_components: usize,
pub max_iterations: usize,
pub tolerance: f64,
pub seed: Option<u64>,
}
impl Default for GmmConfig {
fn default() -> Self {
Self {
n_components: 2,
max_iterations: 100,
tolerance: 1e-3,
seed: None,
}
}
}
#[derive(Debug, Clone)]
pub struct GmmResult {
pub assignments: Vec<usize>,
pub means: Array2<f64>,
pub iterations: usize,
pub log_likelihood: f64,
}
pub struct Gmm;
impl Gmm {
pub fn fit_from_rows(data_rows: Vec<Vec<f64>>, config: &GmmConfig) -> ClusteringResult<GmmResult> {
if data_rows.is_empty() {
return Err(ClusteringError::EmptyData);
}
let n_features = data_rows[0].len();
let n_samples = data_rows.len();
let flat: Vec<f64> = data_rows.into_iter().flatten().collect();
let data = Array2::from_shape_vec((n_samples, n_features), flat)
.map_err(|e| ClusteringError::ClusteringFailed(format!("Failed to create array: {:?}", e)))?;
Self::fit(&data, config)
}
pub fn fit(data: &Array2<f64>, config: &GmmConfig) -> ClusteringResult<GmmResult> {
if data.nrows() == 0 {
return Err(ClusteringError::EmptyData);
}
if data.nrows() < config.n_components {
return Err(ClusteringError::InsufficientData {
min: config.n_components,
actual: data.nrows(),
});
}
let dataset = DatasetBase::new(data.clone(), ());
let model = LinfaGmm::params(config.n_components)
.max_n_iterations(config.max_iterations as u64)
.tolerance(config.tolerance)
.fit(&dataset)
.map_err(|e| ClusteringError::ClusteringFailed(format!("{}", e)))?;
let assignments: Vec<usize> = (0..data.nrows())
.map(|i| {
let point = data.row(i);
let mut max_prob = f64::NEG_INFINITY;
let mut best_component = 0;
for (j, mean) in model.means().rows().into_iter().enumerate() {
let dist: f64 = point
.iter()
.zip(mean.iter())
.map(|(a, b)| (a - b).powi(2))
.sum();
let prob = (-dist).exp(); if prob > max_prob {
max_prob = prob;
best_component = j;
}
}
best_component
})
.collect();
let means = model.means().to_owned();
Ok(GmmResult {
assignments,
means,
iterations: config.max_iterations, log_likelihood: 0.0, })
}
}