Skip to main content

quantrs2_ml/
classification.rs

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