quantrs2_ml/
classification.rs

1use crate::error::{MLError, Result};
2use scirs2_core::ndarray::{Array1, Array2};
3
4/// Metrics for evaluating classification performance
5#[derive(Debug, Clone)]
6pub struct ClassificationMetrics {
7    /// Accuracy (ratio of correctly classified samples)
8    pub accuracy: f64,
9
10    /// Precision (ratio of correctly predicted positive observations to the total predicted positives)
11    pub precision: f64,
12
13    /// Recall (ratio of correctly predicted positive observations to all actual positives)
14    pub recall: f64,
15
16    /// F1 score (harmonic mean of precision and recall)
17    pub f1_score: f64,
18
19    /// Area under the ROC curve
20    pub auc: f64,
21
22    /// Confusion matrix
23    pub confusion_matrix: Array2<f64>,
24
25    /// Per-class accuracy values
26    pub class_accuracies: Vec<f64>,
27
28    /// Class labels
29    pub class_labels: Vec<String>,
30
31    /// Average loss value
32    pub average_loss: f64,
33}
34
35/// Trait for classification models
36pub trait Classifier {
37    /// Trains the classifier on a dataset
38    fn train(&mut self, x_train: &Array2<f64>, y_train: &Array1<f64>) -> Result<()>;
39
40    /// Predicts the class for a sample
41    fn predict(&self, x: &Array1<f64>) -> Result<usize>;
42
43    /// Predicts classes for a batch of samples
44    fn predict_batch(&self, x: &Array2<f64>) -> Result<Array1<usize>> {
45        let mut predictions = Array1::zeros(x.nrows());
46
47        for i in 0..x.nrows() {
48            predictions[i] = self.predict(&x.row(i).to_owned())?;
49        }
50
51        Ok(predictions)
52    }
53
54    /// Computes prediction probabilities for a sample
55    fn predict_proba(&self, x: &Array1<f64>) -> Result<Array1<f64>>;
56
57    /// Evaluates the classifier on a dataset
58    fn evaluate(&self, x_test: &Array2<f64>, y_test: &Array1<f64>)
59        -> Result<ClassificationMetrics>;
60}