datarust 0.6.0

Scikit-learn-style preprocessing and classical ML in Rust
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
//! Core traits shared by the numeric and categorical transformers.

use crate::error::{DatarustError, Result};
use crate::matrix::{Matrix, StrMatrix};

/// Shared base contract for every estimator in datarust.
///
/// `Estimator` is the common base for transformers and supervised predictors.
/// It deliberately does not prescribe input or output types; those belong to
/// the more specific [`Transformer`], [`Regressor`], and [`Classifier`] traits.
pub trait Estimator {}

/// A type-erased scalar parameter value, used by [`Params`] for hyperparameter
/// introspection.
///
/// This enables [`GridSearchCV`](crate::model_selection)-style hyperparameter
/// search without runtime reflection: estimators enumerate their tunable
/// parameters as `(name, value)` pairs that the search driver can read and
/// write back before each refit.
#[derive(Debug, Clone, PartialEq)]
pub enum ParamValue {
    /// A floating-point hyperparameter (e.g. `alpha`, `tol`).
    Float(f64),
    /// An integer hyperparameter (e.g. `n_clusters`, `max_iter`).
    Int(usize),
    /// A boolean hyperparameter (e.g. `fit_intercept`).
    Bool(bool),
}

/// Hyperparameter introspection for estimators that support tuning.
///
/// Estimators opt into this trait to expose their tunable hyperparameters as a
/// flat `(name, value)` map. This is the foundation for
/// [`GridSearchCV`](crate::model_selection)-style hyperparameter search: the
/// search driver reads the current parameters via [`get_params`](Params::get_params),
/// applies a candidate combination via [`set_params`](Params::set_params), then
/// refits and scores the model.
///
/// Not every estimator needs to implement `Params` — only those whose
/// hyperparameters should be searchable.
pub trait Params {
    /// Returns the current hyperparameters as `(name, value)` pairs.
    fn get_params(&self) -> Vec<(&'static str, ParamValue)>;

    /// Applies a named hyperparameter. Returns an error if `name` is unknown or
    /// `value` is the wrong type for that parameter.
    fn set_params(&mut self, name: &str, value: ParamValue) -> Result<()>;
}

/// Trait for numeric transformers operating on `Matrix -> Matrix`.
///
/// All scalers, decompositions, and other numeric transformers implement this
/// trait.  Call [`fit`](Transformer::fit) to learn parameters from training
/// data, then [`transform`](Transformer::transform) to apply the learned
/// transformation to new data.
///
/// ```rust
/// use datarust::scaler::StandardScaler;
/// use datarust::traits::Transformer;
/// use datarust::Matrix;
///
/// let x = Matrix::new(vec![
///     vec![1.0, 10.0],
///     vec![2.0, 20.0],
///     vec![3.0, 30.0],
/// ])?;
/// let mut s = StandardScaler::new();
/// let out = s.fit_transform(&x)?;
/// assert_eq!(out.ncols(), 2);
/// // Inverse supported on StandardScaler
/// let back = s.inverse_transform(&out)?;
/// for i in 0..3 {
///     for j in 0..2 {
///         assert!((back.get(i, j) - x.get(i, j)).abs() < 1e-9);
///     }
/// }
/// # Ok::<_, Box<dyn std::error::Error>>(())
/// ```
pub trait Transformer: Estimator {
    /// Name of the transformer, used for diagnostics.
    fn name(&self) -> &'static str;

    /// Fit the transformer on training data.
    fn fit(&mut self, x: &Matrix) -> Result<()>;

    /// Transform data using fitted parameters.
    fn transform(&self, x: &Matrix) -> Result<Matrix>;

    /// Convenience: fit then transform.
    fn fit_transform(&mut self, x: &Matrix) -> Result<Matrix> {
        self.fit(x)?;
        self.transform(x)
    }

    /// Fit the transformer with supervised target values when they are
    /// available. Unsupervised transformers ignore `y` by default. Supervised
    /// feature selectors override this method, allowing them to live safely in
    /// a [`SupervisedPipeline`](crate::pipeline::SupervisedPipeline).
    fn fit_with_target(&mut self, x: &Matrix, _y: &[f64]) -> Result<()> {
        self.fit(x)
    }

    /// Reverse the transformation, recovering an approximation of the
    /// original input.  Not all transformers support this; the default
    /// implementation returns an error.
    fn inverse_transform(&self, _x: &Matrix) -> Result<Matrix> {
        Err(DatarustError::InvalidInput(format!(
            "{} does not support inverse_transform",
            Transformer::name(self)
        )))
    }

    /// Whether the transformer has been fitted.
    fn is_fitted(&self) -> bool;
}

/// Trait for transformers that can report their output feature names.
///
/// `input_features` are the names of the columns fed to `fit`. When `None`,
/// implementations generate synthetic names (e.g. `x0`, `x1`).
pub trait FeatureNames {
    /// Returns the output feature names given the optional input feature names.
    fn feature_names_out(&self, input_features: Option<&[String]>) -> Vec<String>;
}

/// Helper: generate default input names `x0..x{n-1}`.
pub fn default_input_names(n: usize) -> Vec<String> {
    (0..n).map(|i| format!("x{}", i)).collect()
}

/// Trait for categorical (string) transformers operating on `StrMatrix -> Matrix`.
///
/// All categorical encoders that accept a [`StrMatrix`] and
/// produce a [`Matrix`] implement this trait.
pub trait CategoricalTransformer: Estimator {
    /// Human-readable name of the transformer.
    fn name(&self) -> &'static str;

    /// Fit the transformer on categorical training data.
    fn fit(&mut self, x: &StrMatrix) -> Result<()>;

    /// Transform categorical data using fitted parameters, returning a numeric
    /// [`Matrix`].
    fn transform(&self, x: &StrMatrix) -> Result<Matrix>;

    /// Convenience: fit then transform.
    fn fit_transform(&mut self, x: &StrMatrix) -> Result<Matrix> {
        self.fit(x)?;
        self.transform(x)
    }

    /// Reverse the transformation, recovering category strings from numeric
    /// codes.  Not all encoders support this; the default implementation
    /// returns an error.
    fn inverse_transform(&self, _y: &Matrix) -> Result<StrMatrix> {
        Err(DatarustError::InvalidInput(format!(
            "{} does not support inverse_transform",
            CategoricalTransformer::name(self)
        )))
    }

    /// Whether the transformer has been fitted.
    fn is_fitted(&self) -> bool;
}

/// Trait for supervised encoders that require target values during `fit`.
///
/// Input is a [`StrMatrix`] of categorical features and a slice of target
/// values `&[f64]`.  Output is a numeric [`Matrix`].
pub trait TargetTransformer: Estimator {
    /// Human-readable name of the transformer.
    fn name(&self) -> &'static str;

    /// Fit the transformer on categorical features and target values.
    fn fit(&mut self, x: &StrMatrix, y: &[f64]) -> Result<()>;

    /// Transform categorical data using fitted parameters.
    fn transform(&self, x: &StrMatrix) -> Result<Matrix>;

    /// Convenience: fit then transform.
    fn fit_transform(&mut self, x: &StrMatrix, y: &[f64]) -> Result<Matrix> {
        self.fit(x, y)?;
        self.transform(x)
    }

    /// Reverse the transformation.  Not all supervised encoders support this;
    /// the default implementation returns an error.
    fn inverse_transform(&self, _y: &Matrix) -> Result<StrMatrix> {
        Err(DatarustError::InvalidInput(format!(
            "{} does not support inverse_transform",
            TargetTransformer::name(self)
        )))
    }

    /// Whether the transformer has been fitted.
    fn is_fitted(&self) -> bool;
}

/// Shared fitting and prediction contract for supervised estimators operating
/// on numeric features and targets.
pub trait Predictor: Estimator {
    /// Fit the estimator on training features and target values.
    fn fit(&mut self, x: &Matrix, y: &[f64]) -> Result<()>;

    /// Predict one numeric value per input row. For classifiers this is the
    /// predicted class label; probability estimates are exposed separately by
    /// [`PredictProba`].
    fn predict(&self, x: &Matrix) -> Result<Vec<f64>>;

    /// Convenience: fit then predict on the same data.
    fn fit_predict(&mut self, x: &Matrix, y: &[f64]) -> Result<Vec<f64>> {
        self.fit(x, y)?;
        self.predict(x)
    }

    /// Whether the estimator has learned fitted state.
    fn is_fitted(&self) -> bool;
}

/// Trait for regression estimators operating on `Matrix` features and
/// `&[f64]` targets.
///
/// Regression models (e.g. [`LinearRegression`]) implement this trait.
/// Call [`fit`](Predictor::fit) to learn coefficients from training data and
/// targets, then [`predict`](Predictor::predict) to generate predictions for
/// new data.
///
/// [`LinearRegression`]: crate::linear_model::LinearRegression
///
/// ```rust
/// use datarust::linear_model::LinearRegression;
/// use datarust::traits::Predictor;
/// use datarust::Matrix;
///
/// let x = Matrix::new(vec![
///     vec![1.0],
///     vec![2.0],
///     vec![3.0],
///     vec![4.0],
/// ])?;
/// let y = vec![3.0, 5.0, 7.0, 9.0]; // y = 2x + 1
///
/// let mut model = LinearRegression::new();
/// model.fit(&x, &y)?;
/// let pred = model.predict(&x)?;
/// assert!((pred[0] - 3.0).abs() < 1e-9);
/// assert!((pred[3] - 9.0).abs() < 1e-9);
/// # Ok::<_, Box<dyn std::error::Error>>(())
/// ```
pub trait Regressor: Predictor {
    /// Name of the estimator, used for diagnostics.
    ///
    /// Kept on `Regressor` for backwards compatibility with code that uses
    /// regression estimators through this trait.
    fn name(&self) -> &'static str;

    /// R² (coefficient of determination) of the prediction.
    fn score(&self, x: &Matrix, y: &[f64]) -> Result<f64> {
        let prediction = Predictor::predict(self, x)?;
        crate::metrics::regression::r2_score(y, &prediction)
    }
}

/// Trait for classifiers that return one class label per input row.
pub trait Classifier: Predictor {
    /// Mean classification accuracy, mirroring sklearn's default classifier
    /// score.
    fn score(&self, x: &Matrix, y: &[f64]) -> Result<f64> {
        let prediction = self.predict(x)?;
        crate::metrics::classification::accuracy_score(y, &prediction)
    }
}

/// Trait for classifiers that expose a probability for every class.
///
/// The returned matrix is shaped `(n_samples, n_classes)` and follows the
/// estimator's class order. Binary [`LogisticRegression`](crate::LogisticRegression)
/// returns columns `[P(class=0), P(class=1)]`.
pub trait PredictProba: Classifier {
    /// Return per-class probability estimates.
    fn predict_proba(&self, x: &Matrix) -> Result<Matrix>;
}

/// Trait for 1-D label encoders that map `&[String]` to `Vec<usize>`.
///
/// Used to encode target labels for supervised learning.
pub trait LabelTransformer: Estimator {
    /// Human-readable name of the transformer.
    fn name(&self) -> &'static str;

    /// Fit on label data, learning the unique sorted classes.
    fn fit(&mut self, x: &[String]) -> Result<()>;

    /// Transform labels to integer indices.
    fn transform(&self, x: &[String]) -> Result<Vec<usize>>;

    /// Reverses the transformation: indices back to strings.
    fn inverse_transform(&self, x: &[usize]) -> Result<Vec<String>>;

    /// Convenience: fit then transform.
    fn fit_transform(&mut self, x: &[String]) -> Result<Vec<usize>> {
        self.fit(x)?;
        self.transform(x)
    }

    /// Whether the transformer has been fitted.
    fn is_fitted(&self) -> bool;
}

/// Trait for clustering estimators operating on `Matrix` features with no target.
///
/// Clustering is unsupervised: `fit` takes only `X`, and [`predict`](Clusterer::predict)
/// returns cluster indices (`Vec<usize>`), not the regression targets or class
/// labels used by [`Predictor`]. This mirrors `sklearn.cluster` estimators such
/// as `KMeans`, which expose `fit_predict` and `predict` returning integer labels.
///
/// Implementors provide [`fit`](Clusterer::fit) and [`predict`](Clusterer::predict);
/// the convenience methods have default implementations.
pub trait Clusterer: Estimator {
    /// Human-readable name of the estimator, used for diagnostics.
    fn name(&self) -> &'static str;

    /// Fit the estimator to the data, learning cluster structure.
    fn fit(&mut self, x: &Matrix) -> Result<()>;

    /// Assign each input row to its nearest fitted cluster, returning the
    /// cluster index per row.
    fn predict(&self, x: &Matrix) -> Result<Vec<usize>>;

    /// Convenience: fit, then return the cluster index assigned to each training
    /// row. Equivalent to `fit` followed by `predict` on the same data, but
    /// implementations may compute the labels more efficiently during fitting.
    fn fit_predict(&mut self, x: &Matrix) -> Result<Vec<usize>> {
        self.fit(x)?;
        self.predict(x)
    }

    /// Convenience: fit then transform. The default implementation returns a
    /// one-hot encoding of the cluster assignments (one column per cluster);
    /// implementations may override it to produce a different embedding (e.g.
    /// spectral clustering's affinity matrix).
    fn fit_transform(&mut self, x: &Matrix) -> Result<Matrix> {
        let labels = self.fit_predict(x)?;
        let k = self.n_clusters();
        let n = x.nrows();
        let mut data = vec![0.0; n * k];
        for (i, &label) in labels.iter().enumerate() {
            data[i * k + label] = 1.0;
        }
        Matrix::from_flat(n, k, data)
    }

    /// Number of clusters learned during `fit`. Available only after fitting.
    fn n_clusters(&self) -> usize;

    /// Whether the estimator has been fitted.
    fn is_fitted(&self) -> bool;
}

macro_rules! impl_estimator_from_transformer {
    ($($ty:path),+ $(,)?) => {
        $(
            impl Estimator for $ty {}
        )+
    };
}

impl_estimator_from_transformer!(
    crate::scaler::StandardScaler,
    crate::scaler::MinMaxScaler,
    crate::scaler::MaxAbsScaler,
    crate::scaler::RobustScaler,
    crate::scaler::Normalizer,
    crate::scaler::Binarizer,
    crate::scaler::KBinsDiscretizer,
    crate::scaler::QuantileTransformer,
    crate::scaler::PowerTransformer,
    crate::polynomial::PolynomialFeatures,
    crate::selection::VarianceThreshold,
    crate::selection::SelectKBest,
    crate::decomposition::PCA,
    crate::decomposition::TruncatedSVD,
    crate::imputer::SimpleImputer,
    crate::imputer::KnnImputer,
    crate::function_transformer::FunctionTransformer,
    crate::transformer_kind::TransformerKind,
    crate::pipeline::Pipeline,
);

macro_rules! impl_estimator_from_categorical_transformer {
    ($($ty:path),+ $(,)?) => {
        $(
            impl Estimator for $ty {}
        )+
    };
}

impl_estimator_from_categorical_transformer!(
    crate::encoder::OneHotEncoder,
    crate::encoder::OrdinalEncoder,
    crate::encoder::FrequencyEncoder,
    crate::categorical_kind::CategoricalTransformerKind,
);

macro_rules! impl_estimator_from_target_transformer {
    ($($ty:path),+ $(,)?) => {
        $(
            impl Estimator for $ty {}
        )+
    };
}

impl_estimator_from_target_transformer!(
    crate::encoder::TargetEncoder,
    crate::target_kind::TargetTransformerKind,
);

impl Estimator for crate::encoder::LabelEncoder {}

macro_rules! impl_estimator_from_clusterer {
    ($($ty:path),+ $(,)?) => {
        $(
            impl Estimator for $ty {}
        )+
    };
}

impl_estimator_from_clusterer!(crate::cluster::KMeans,);