scirs2-cluster 0.3.4

Clustering algorithms module for SciRS2 (scirs2-cluster)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
//! Cross-validation implementations for clustering algorithms
//!
//! This module provides cross-validation methods for different clustering
//! algorithms to evaluate hyperparameter configurations.

use scirs2_core::ndarray::{Array1, Array2, ArrayView2, Axis};
use scirs2_core::numeric::{Float, FromPrimitive};
use std::collections::HashMap;
use std::fmt::Debug;

use crate::affinity::{affinity_propagation, AffinityPropagationOptions};
use crate::birch::{birch, BirchOptions};
use crate::density::{dbscan, optics};
use crate::error::{ClusteringError, Result};
use crate::gmm::{gaussian_mixture, CovarianceType, GMMInit, GMMOptions};
use crate::metrics::{calinski_harabasz_score, davies_bouldin_score, silhouette_score};
use crate::spectral::{spectral_clustering, AffinityMode, SpectralClusteringOptions};
use crate::vq::{kmeans, kmeans2};

use super::config::{CVStrategy, CrossValidationConfig, EvaluationMetric};
use super::utilities::calculate_inertia;

use statrs::statistics::Statistics;

/// Cross-validation engine for clustering algorithms
pub struct CrossValidator {
    config: CrossValidationConfig,
}

impl CrossValidator {
    /// Create a new cross-validator with specified configuration
    pub fn new(config: &CrossValidationConfig) -> Self {
        Self {
            config: config.clone(),
        }
    }

    /// Cross-validate K-means clustering
    pub fn cross_validate_kmeans<F>(
        &self,
        data: ArrayView2<F>,
        k: usize,
        max_iter: Option<usize>,
        tol: Option<f64>,
        seed: Option<u64>,
        metric: &EvaluationMetric,
    ) -> Result<Vec<f64>>
    where
        F: Float
            + FromPrimitive
            + Debug
            + 'static
            + std::iter::Sum
            + std::fmt::Display
            + Send
            + Sync
            + scirs2_core::ndarray::ScalarOperand
            + std::ops::AddAssign
            + std::ops::SubAssign
            + std::ops::MulAssign
            + std::ops::DivAssign
            + std::ops::RemAssign
            + PartialOrd,
        f64: From<F>,
    {
        let mut scores = Vec::new();
        let n_samples = data.shape()[0];

        match self.config.strategy {
            CVStrategy::KFold => {
                let fold_size = n_samples / self.config.n_folds;

                for fold in 0..self.config.n_folds {
                    let start_idx = fold * fold_size;
                    let end_idx = if fold == self.config.n_folds - 1 {
                        n_samples
                    } else {
                        (fold + 1) * fold_size
                    };

                    let mut train_indices = Vec::new();
                    let mut test_indices = Vec::new();

                    for i in 0..n_samples {
                        if i >= start_idx && i < end_idx {
                            test_indices.push(i);
                        } else {
                            train_indices.push(i);
                        }
                    }

                    if train_indices.is_empty() || test_indices.is_empty() {
                        continue;
                    }

                    let train_data = extract_subset(data, &train_indices)?;

                    match kmeans2(
                        train_data.view(),
                        k,
                        Some(max_iter.unwrap_or(100)),
                        tol.map(|t| F::from(t).expect("Failed to convert to float")),
                        None,
                        None,
                        Some(false),
                        seed,
                    ) {
                        Ok((centroids, labels)) => {
                            let score = calculate_metric_score(
                                train_data.view(),
                                &labels.mapv(|x| x),
                                Some(&centroids),
                                metric,
                            )?;
                            scores.push(score);
                        }
                        Err(_) => continue,
                    }
                }
            }
            _ => {
                match kmeans2(
                    data,
                    k,
                    Some(max_iter.unwrap_or(100)),
                    tol.map(|t| F::from(t).expect("Failed to convert to float")),
                    None,
                    None,
                    Some(false),
                    seed,
                ) {
                    Ok((centroids, labels)) => {
                        let score = calculate_metric_score(
                            data,
                            &labels.mapv(|x| x),
                            Some(&centroids),
                            metric,
                        )?;
                        scores.push(score);
                    }
                    Err(_) => {
                        scores.push(f64::NEG_INFINITY);
                    }
                }
            }
        }

        if scores.is_empty() {
            scores.push(f64::NEG_INFINITY);
        }

        Ok(scores)
    }

    /// Cross-validate DBSCAN clustering
    pub fn cross_validate_dbscan<F>(
        &self,
        data: ArrayView2<F>,
        eps: f64,
        min_samples: usize,
        metric: &EvaluationMetric,
    ) -> Result<Vec<f64>>
    where
        F: Float + FromPrimitive + Debug + Send + Sync + scirs2_core::ndarray::ScalarOperand,
        f64: From<F>,
    {
        let mut scores = Vec::new();
        let data_f64 = data.mapv(|x| x.to_f64().unwrap_or(0.0));

        match dbscan(data_f64.view(), eps, min_samples, None) {
            Ok(labels) => {
                let labels_usize = labels.mapv(|x| if x < 0 { usize::MAX } else { x as usize });
                let score = calculate_metric_score(data, &labels_usize, None, metric)?;
                scores.push(score);
            }
            Err(_) => {
                scores.push(f64::NEG_INFINITY);
            }
        }

        Ok(scores)
    }

    /// Cross-validate OPTICS clustering
    pub fn cross_validate_optics<F>(
        &self,
        data: ArrayView2<F>,
        min_samples: usize,
        max_eps: Option<F>,
        metric: &EvaluationMetric,
    ) -> Result<Vec<f64>>
    where
        F: Float + FromPrimitive + Debug + Send + Sync + scirs2_core::ndarray::ScalarOperand,
        f64: From<F>,
    {
        let n_samples = data.nrows();
        let n_folds = self.config.n_folds.min(n_samples);
        let fold_size = n_samples / n_folds;
        let mut scores = Vec::new();

        for fold in 0..n_folds {
            let start_idx = fold * fold_size;
            let end_idx = if fold == n_folds - 1 {
                n_samples
            } else {
                (fold + 1) * fold_size
            };

            let train_indices: Vec<usize> = (0..start_idx).chain(end_idx..n_samples).collect();
            let train_data = data.select(Axis(0), &train_indices);

            match optics(train_data.view(), min_samples, max_eps, None) {
                Ok(result) => {
                    let cluster_labels = result;

                    if cluster_labels.iter().all(|&label| label == -1) {
                        scores.push(f64::NEG_INFINITY);
                        continue;
                    }

                    let n_clusters =
                        (*cluster_labels.iter().max().unwrap_or(&-1i32) + 1i32) as usize;
                    if n_clusters < 2usize {
                        scores.push(f64::NEG_INFINITY);
                        continue;
                    }

                    let labels: Vec<usize> = cluster_labels
                        .iter()
                        .map(|&label| {
                            if label == -1i32 {
                                0usize
                            } else {
                                (label as usize) + 1usize
                            }
                        })
                        .collect();
                    let labels_array = Array1::from_vec(labels);

                    let score =
                        calculate_metric_score(train_data.view(), &labels_array, None, metric)?;
                    scores.push(score);
                }
                Err(_) => {
                    scores.push(f64::NEG_INFINITY);
                }
            }
        }

        Ok(scores)
    }

    /// Cross-validate Spectral clustering
    pub fn cross_validate_spectral<F>(
        &self,
        data: ArrayView2<F>,
        n_clusters: usize,
        n_neighbors: usize,
        gamma: F,
        max_iter: usize,
        metric: &EvaluationMetric,
    ) -> Result<Vec<f64>>
    where
        F: Float
            + FromPrimitive
            + Debug
            + Send
            + Sync
            + scirs2_core::ndarray::ScalarOperand
            + std::ops::MulAssign
            + std::ops::DivAssign
            + std::ops::RemAssign
            + std::fmt::Display
            + std::iter::Sum
            + std::ops::AddAssign
            + std::ops::SubAssign,
        f64: From<F>,
    {
        let n_samples = data.nrows();
        let n_folds = self.config.n_folds.min(n_samples);
        let fold_size = n_samples / n_folds;
        let mut scores = Vec::new();

        for fold in 0..n_folds {
            let start_idx = fold * fold_size;
            let end_idx = if fold == n_folds - 1 {
                n_samples
            } else {
                (fold + 1) * fold_size
            };

            let train_indices: Vec<usize> = (0..start_idx).chain(end_idx..n_samples).collect();
            let train_data = data.select(Axis(0), &train_indices);

            let options = SpectralClusteringOptions {
                affinity: AffinityMode::RBF,
                n_neighbors,
                gamma,
                normalized_laplacian: true,
                max_iter,
                n_init: 1,
                tol: F::from(1e-4).expect("Failed to convert constant to float"),
                random_seed: None,
                eigen_solver: "arpack".to_string(),
                auto_n_clusters: false,
            };

            match spectral_clustering(train_data.view(), n_clusters, Some(options)) {
                Ok((_, labels)) => {
                    let score = calculate_metric_score(train_data.view(), &labels, None, metric)?;
                    scores.push(score);
                }
                Err(_) => {
                    scores.push(f64::NEG_INFINITY);
                }
            }
        }

        Ok(scores)
    }

    /// Cross-validate Affinity Propagation clustering
    pub fn cross_validate_affinity_propagation<F>(
        &self,
        data: ArrayView2<F>,
        damping: F,
        max_iter: usize,
        convergence_iter: usize,
        metric: &EvaluationMetric,
    ) -> Result<Vec<f64>>
    where
        F: Float + FromPrimitive + Debug + Send + Sync + scirs2_core::ndarray::ScalarOperand,
        f64: From<F>,
    {
        let n_samples = data.nrows();
        let n_folds = self.config.n_folds.min(n_samples);
        let fold_size = n_samples / n_folds;
        let mut scores = Vec::new();

        for fold in 0..n_folds {
            let start_idx = fold * fold_size;
            let end_idx = if fold == n_folds - 1 {
                n_samples
            } else {
                (fold + 1) * fold_size
            };

            let train_indices: Vec<usize> = (0..start_idx).chain(end_idx..n_samples).collect();
            let train_data = data.select(Axis(0), &train_indices);

            let options = AffinityPropagationOptions {
                damping,
                max_iter,
                convergence_iter,
                preference: None,
                affinity: "euclidean".to_string(),
                verbose: false,
            };

            match affinity_propagation(train_data.view(), false, Some(options)) {
                Ok((_, labels)) => {
                    let usize_labels: Vec<usize> = labels.iter().map(|&x| x as usize).collect();
                    let labels_array = Array1::from_vec(usize_labels);

                    let score =
                        calculate_metric_score(train_data.view(), &labels_array, None, metric)?;
                    scores.push(score);
                }
                Err(_) => {
                    scores.push(f64::NEG_INFINITY);
                }
            }
        }

        Ok(scores)
    }

    /// Cross-validate BIRCH clustering
    pub fn cross_validate_birch<F>(
        &self,
        data: ArrayView2<F>,
        branching_factor: usize,
        threshold: F,
        metric: &EvaluationMetric,
    ) -> Result<Vec<f64>>
    where
        F: Float + FromPrimitive + Debug + Send + Sync + scirs2_core::ndarray::ScalarOperand,
        f64: From<F>,
    {
        let n_samples = data.nrows();
        let n_folds = self.config.n_folds.min(n_samples);
        let fold_size = n_samples / n_folds;
        let mut scores = Vec::new();

        for fold in 0..n_folds {
            let start_idx = fold * fold_size;
            let end_idx = if fold == n_folds - 1 {
                n_samples
            } else {
                (fold + 1) * fold_size
            };

            let train_indices: Vec<usize> = (0..start_idx).chain(end_idx..n_samples).collect();
            let train_data = data.select(Axis(0), &train_indices);

            let options = BirchOptions {
                branching_factor,
                threshold,
                n_clusters: None,
                max_leaf_entries: None,
                n_refinement_iter: 5,
            };

            match birch(train_data.view(), options) {
                Ok((_, labels)) => {
                    let usize_labels: Vec<usize> = labels.iter().map(|&x| x as usize).collect();
                    let labels_array = Array1::from_vec(usize_labels);

                    let score =
                        calculate_metric_score(train_data.view(), &labels_array, None, metric)?;
                    scores.push(score);
                }
                Err(_) => {
                    scores.push(f64::NEG_INFINITY);
                }
            }
        }

        Ok(scores)
    }

    /// Cross-validate GMM clustering
    pub fn cross_validate_gmm<F>(
        &self,
        data: ArrayView2<F>,
        n_components: usize,
        max_iter: usize,
        tol: F,
        reg_covar: F,
        metric: &EvaluationMetric,
    ) -> Result<Vec<f64>>
    where
        F: Float + FromPrimitive + Debug + Send + Sync + scirs2_core::ndarray::ScalarOperand,
        f64: From<F>,
    {
        let n_samples = data.nrows();
        let n_folds = self.config.n_folds.min(n_samples);
        let fold_size = n_samples / n_folds;
        let mut scores = Vec::new();

        for fold in 0..n_folds {
            let start_idx = fold * fold_size;
            let end_idx = if fold == n_folds - 1 {
                n_samples
            } else {
                (fold + 1) * fold_size
            };

            let train_indices: Vec<usize> = (0..start_idx).chain(end_idx..n_samples).collect();
            let train_data = data.select(Axis(0), &train_indices);
            let train_data_f64 = train_data.mapv(|x| x.to_f64().unwrap_or(0.0));

            let options = GMMOptions {
                n_components,
                covariance_type: CovarianceType::Full,
                tol: tol.to_f64().unwrap_or(1e-4),
                max_iter,
                n_init: 1,
                init_method: GMMInit::KMeans,
                random_seed: Some(42),
                reg_covar: reg_covar.to_f64().unwrap_or(1e-6),
            };

            match gaussian_mixture(train_data_f64.view(), options) {
                Ok(labels) => {
                    let usize_labels: Vec<usize> = labels.iter().map(|&x| x as usize).collect();
                    let labels_array = Array1::from_vec(usize_labels);

                    let score =
                        calculate_metric_score(train_data.view(), &labels_array, None, metric)?;
                    scores.push(score);
                }
                Err(_) => {
                    scores.push(f64::NEG_INFINITY);
                }
            }
        }

        Ok(scores)
    }
}

/// Extract subset of data based on indices
fn extract_subset<F>(data: ArrayView2<F>, indices: &[usize]) -> Result<Array2<F>>
where
    F: Clone + scirs2_core::numeric::Zero,
{
    let n_features = data.ncols();
    let mut subset = Array2::zeros((indices.len(), n_features));

    for (new_idx, &old_idx) in indices.iter().enumerate() {
        if old_idx < data.nrows() {
            subset.row_mut(new_idx).assign(&data.row(old_idx));
        }
    }

    Ok(subset)
}

/// Calculate metric score for evaluation
fn calculate_metric_score<F>(
    data: ArrayView2<F>,
    labels: &Array1<usize>,
    centroids: Option<&Array2<F>>,
    metric: &EvaluationMetric,
) -> Result<f64>
where
    F: Float + FromPrimitive + Debug + Send + Sync + scirs2_core::ndarray::ScalarOperand,
    f64: From<F>,
{
    let data_f64 = data.mapv(|x| x.to_f64().unwrap_or(0.0));
    let labels_i32 = labels.mapv(|x| x as i32);

    match metric {
        EvaluationMetric::SilhouetteScore => silhouette_score(data_f64.view(), labels_i32.view()),
        EvaluationMetric::DaviesBouldinIndex => {
            davies_bouldin_score(data_f64.view(), labels_i32.view())
        }
        EvaluationMetric::CalinskiHarabaszIndex => {
            calinski_harabasz_score(data_f64.view(), labels_i32.view())
        }
        EvaluationMetric::Inertia => {
            if let Some(centroids) = centroids {
                let centroids_f64 = centroids.mapv(|x| x.to_f64().unwrap_or(0.0));
                calculate_inertia(&data_f64, labels, &centroids_f64)
            } else {
                Ok(f64::INFINITY)
            }
        }
        _ => Ok(0.0),
    }
}