quantrs2-ml 0.1.3

Quantum Machine Learning module for QuantRS2
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
//! Sklearn-compatible preprocessing utilities

use super::SklearnEstimator;
use crate::error::{MLError, Result};
use scirs2_core::ndarray::{Array1, Array2, Axis};
use std::collections::HashMap;

/// Standard Scaler (sklearn-compatible)
pub struct StandardScaler {
    mean_: Option<Array1<f64>>,
    scale_: Option<Array1<f64>>,
    fitted: bool,
}

impl StandardScaler {
    pub fn new() -> Self {
        Self {
            mean_: None,
            scale_: None,
            fitted: false,
        }
    }
}

impl Default for StandardScaler {
    fn default() -> Self {
        Self::new()
    }
}

impl SklearnEstimator for StandardScaler {
    #[allow(non_snake_case)]
    fn fit(&mut self, X: &Array2<f64>, _y: Option<&Array1<f64>>) -> Result<()> {
        let mean = X.mean_axis(Axis(0)).ok_or_else(|| {
            MLError::InvalidInput("Cannot compute mean of empty array".to_string())
        })?;
        let std = X.std_axis(Axis(0), 0.0);

        self.mean_ = Some(mean);
        self.scale_ = Some(std);
        self.fitted = true;

        Ok(())
    }

    fn get_params(&self) -> HashMap<String, String> {
        HashMap::new()
    }

    fn set_params(&mut self, _params: HashMap<String, String>) -> Result<()> {
        Ok(())
    }

    fn is_fitted(&self) -> bool {
        self.fitted
    }
}

/// MinMax scaler
pub struct MinMaxScaler {
    min: Option<Array1<f64>>,
    max: Option<Array1<f64>>,
    feature_range: (f64, f64),
    fitted: bool,
}

impl MinMaxScaler {
    /// Create new MinMaxScaler
    pub fn new() -> Self {
        Self {
            min: None,
            max: None,
            feature_range: (0.0, 1.0),
            fitted: false,
        }
    }

    /// Set feature range
    pub fn feature_range(mut self, min_val: f64, max_val: f64) -> Self {
        self.feature_range = (min_val, max_val);
        self
    }

    /// Fit the scaler
    #[allow(non_snake_case)]
    pub fn fit(&mut self, X: &Array2<f64>) -> Result<()> {
        let n_features = X.ncols();
        let mut min = Array1::zeros(n_features);
        let mut max = Array1::zeros(n_features);

        for j in 0..n_features {
            let col = X.column(j);
            min[j] = col.iter().cloned().fold(f64::INFINITY, f64::min);
            max[j] = col.iter().cloned().fold(f64::NEG_INFINITY, f64::max);
        }

        self.min = Some(min);
        self.max = Some(max);
        self.fitted = true;
        Ok(())
    }

    /// Transform data
    #[allow(non_snake_case)]
    pub fn transform(&self, X: &Array2<f64>) -> Result<Array2<f64>> {
        let min = self
            .min
            .as_ref()
            .ok_or_else(|| MLError::ModelNotTrained("Scaler not fitted".to_string()))?;
        let max = self
            .max
            .as_ref()
            .ok_or_else(|| MLError::ModelNotTrained("Scaler not fitted".to_string()))?;

        let (range_min, range_max) = self.feature_range;
        let mut result = X.clone();

        for j in 0..X.ncols() {
            let scale = if (max[j] - min[j]).abs() > 1e-10 {
                (range_max - range_min) / (max[j] - min[j])
            } else {
                1.0
            };

            for i in 0..X.nrows() {
                result[[i, j]] = (X[[i, j]] - min[j]) * scale + range_min;
            }
        }

        Ok(result)
    }

    /// Fit and transform
    #[allow(non_snake_case)]
    pub fn fit_transform(&mut self, X: &Array2<f64>) -> Result<Array2<f64>> {
        self.fit(X)?;
        self.transform(X)
    }
}

impl Default for MinMaxScaler {
    fn default() -> Self {
        Self::new()
    }
}

impl SklearnEstimator for MinMaxScaler {
    #[allow(non_snake_case)]
    fn fit(&mut self, X: &Array2<f64>, _y: Option<&Array1<f64>>) -> Result<()> {
        MinMaxScaler::fit(self, X)
    }

    fn get_params(&self) -> HashMap<String, String> {
        let mut params = HashMap::new();
        params.insert(
            "feature_range_min".to_string(),
            self.feature_range.0.to_string(),
        );
        params.insert(
            "feature_range_max".to_string(),
            self.feature_range.1.to_string(),
        );
        params
    }

    fn set_params(&mut self, params: HashMap<String, String>) -> Result<()> {
        if let Some(min_str) = params.get("feature_range_min") {
            if let Some(max_str) = params.get("feature_range_max") {
                let min_val: f64 = min_str.parse().map_err(|_| {
                    MLError::InvalidConfiguration("Invalid feature_range_min".to_string())
                })?;
                let max_val: f64 = max_str.parse().map_err(|_| {
                    MLError::InvalidConfiguration("Invalid feature_range_max".to_string())
                })?;
                self.feature_range = (min_val, max_val);
            }
        }
        Ok(())
    }

    fn is_fitted(&self) -> bool {
        self.fitted
    }
}

/// Robust scaler (uses median and IQR)
pub struct RobustScaler {
    center: Option<Array1<f64>>,
    scale: Option<Array1<f64>>,
    with_centering: bool,
    with_scaling: bool,
    fitted: bool,
}

impl RobustScaler {
    /// Create new RobustScaler
    pub fn new() -> Self {
        Self {
            center: None,
            scale: None,
            with_centering: true,
            with_scaling: true,
            fitted: false,
        }
    }

    /// Fit the scaler
    #[allow(non_snake_case)]
    pub fn fit(&mut self, X: &Array2<f64>) -> Result<()> {
        let n_features = X.ncols();
        let mut center = Array1::zeros(n_features);
        let mut scale = Array1::zeros(n_features);

        for j in 0..n_features {
            let mut col: Vec<f64> = X.column(j).iter().cloned().collect();
            col.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));

            let n = col.len();
            center[j] = col[n / 2]; // Median

            let q1 = col[n / 4];
            let q3 = col[3 * n / 4];
            scale[j] = if (q3 - q1).abs() > 1e-10 {
                q3 - q1
            } else {
                1.0
            };
        }

        self.center = Some(center);
        self.scale = Some(scale);
        self.fitted = true;
        Ok(())
    }

    /// Transform data
    #[allow(non_snake_case)]
    pub fn transform(&self, X: &Array2<f64>) -> Result<Array2<f64>> {
        let center = self
            .center
            .as_ref()
            .ok_or_else(|| MLError::ModelNotTrained("Scaler not fitted".to_string()))?;
        let scale = self
            .scale
            .as_ref()
            .ok_or_else(|| MLError::ModelNotTrained("Scaler not fitted".to_string()))?;

        let mut result = X.clone();

        for j in 0..X.ncols() {
            for i in 0..X.nrows() {
                result[[i, j]] = if self.with_centering {
                    (X[[i, j]] - center[j]) / scale[j]
                } else {
                    X[[i, j]] / scale[j]
                };
            }
        }

        Ok(result)
    }

    /// Fit and transform
    #[allow(non_snake_case)]
    pub fn fit_transform(&mut self, X: &Array2<f64>) -> Result<Array2<f64>> {
        self.fit(X)?;
        self.transform(X)
    }
}

impl Default for RobustScaler {
    fn default() -> Self {
        Self::new()
    }
}

/// Label encoder
pub struct LabelEncoder {
    classes: Vec<String>,
    fitted: bool,
}

impl LabelEncoder {
    /// Create new LabelEncoder
    pub fn new() -> Self {
        Self {
            classes: Vec::new(),
            fitted: false,
        }
    }

    /// Fit the encoder
    pub fn fit(&mut self, y: &[String]) {
        let mut classes: Vec<String> = y.iter().cloned().collect();
        classes.sort();
        classes.dedup();
        self.classes = classes;
        self.fitted = true;
    }

    /// Transform labels to integers
    pub fn transform(&self, y: &[String]) -> Result<Array1<i32>> {
        if !self.fitted {
            return Err(MLError::ModelNotTrained("Encoder not fitted".to_string()));
        }

        let encoded: Vec<i32> = y
            .iter()
            .map(|label| {
                self.classes
                    .iter()
                    .position(|c| c == label)
                    .map(|p| p as i32)
                    .unwrap_or(-1)
            })
            .collect();

        Ok(Array1::from_vec(encoded))
    }

    /// Inverse transform
    pub fn inverse_transform(&self, y: &Array1<i32>) -> Result<Vec<String>> {
        if !self.fitted {
            return Err(MLError::ModelNotTrained("Encoder not fitted".to_string()));
        }

        let decoded: Vec<String> = y
            .iter()
            .map(|&idx| {
                if idx >= 0 && (idx as usize) < self.classes.len() {
                    self.classes[idx as usize].clone()
                } else {
                    "unknown".to_string()
                }
            })
            .collect();

        Ok(decoded)
    }

    /// Fit and transform
    pub fn fit_transform(&mut self, y: &[String]) -> Result<Array1<i32>> {
        self.fit(y);
        self.transform(y)
    }

    /// Get classes
    pub fn classes(&self) -> &[String] {
        &self.classes
    }

    /// Check if fitted
    pub fn is_fitted(&self) -> bool {
        self.fitted
    }
}

impl Default for LabelEncoder {
    fn default() -> Self {
        Self::new()
    }
}

/// One-hot encoder
pub struct OneHotEncoder {
    categories: Vec<Vec<String>>,
    fitted: bool,
    sparse: bool,
}

impl OneHotEncoder {
    /// Create new OneHotEncoder
    pub fn new() -> Self {
        Self {
            categories: Vec::new(),
            fitted: false,
            sparse: false,
        }
    }

    /// Set sparse output
    pub fn sparse(mut self, sparse: bool) -> Self {
        self.sparse = sparse;
        self
    }

    /// Fit the encoder
    #[allow(non_snake_case)]
    pub fn fit(&mut self, X: &Array2<String>) {
        self.categories = Vec::new();

        for j in 0..X.ncols() {
            let mut cats: Vec<String> = X.column(j).iter().cloned().collect();
            cats.sort();
            cats.dedup();
            self.categories.push(cats);
        }

        self.fitted = true;
    }

    /// Transform to one-hot encoding
    #[allow(non_snake_case)]
    pub fn transform(&self, X: &Array2<String>) -> Result<Array2<f64>> {
        if !self.fitted {
            return Err(MLError::ModelNotTrained("Encoder not fitted".to_string()));
        }

        let total_cols: usize = self.categories.iter().map(|c| c.len()).sum();
        let mut result = Array2::zeros((X.nrows(), total_cols));

        let mut col_offset = 0;
        for j in 0..X.ncols() {
            let cats = &self.categories[j];
            for i in 0..X.nrows() {
                if let Some(idx) = cats.iter().position(|c| c == &X[[i, j]]) {
                    result[[i, col_offset + idx]] = 1.0;
                }
            }
            col_offset += cats.len();
        }

        Ok(result)
    }

    /// Fit and transform
    #[allow(non_snake_case)]
    pub fn fit_transform(&mut self, X: &Array2<String>) -> Result<Array2<f64>> {
        self.fit(X);
        self.transform(X)
    }
}

impl Default for OneHotEncoder {
    fn default() -> Self {
        Self::new()
    }
}

/// Quantum Feature Encoder (sklearn-compatible)
pub struct QuantumFeatureEncoder {
    encoding_type: String,
    normalization: String,
    fitted: bool,
}

impl QuantumFeatureEncoder {
    pub fn new(encoding_type: &str, normalization: &str) -> Self {
        Self {
            encoding_type: encoding_type.to_string(),
            normalization: normalization.to_string(),
            fitted: false,
        }
    }
}

impl SklearnEstimator for QuantumFeatureEncoder {
    #[allow(non_snake_case)]
    fn fit(&mut self, _X: &Array2<f64>, _y: Option<&Array1<f64>>) -> Result<()> {
        self.fitted = true;
        Ok(())
    }

    fn get_params(&self) -> HashMap<String, String> {
        let mut params = HashMap::new();
        params.insert("encoding_type".to_string(), self.encoding_type.clone());
        params.insert("normalization".to_string(), self.normalization.clone());
        params
    }

    fn set_params(&mut self, params: HashMap<String, String>) -> Result<()> {
        for (key, value) in params {
            match key.as_str() {
                "encoding_type" => {
                    self.encoding_type = value;
                }
                "normalization" => {
                    self.normalization = value;
                }
                _ => {}
            }
        }
        Ok(())
    }

    fn is_fitted(&self) -> bool {
        self.fitted
    }
}