linfa/traits.rs
1//! Provide traits for different classes of algorithms
2//!
3
4use crate::dataset::{DatasetBase, Records};
5use std::convert::From;
6
7/// Transformation algorithms
8///
9/// A transformer takes a dataset and transforms it into a different one. It has no concept of
10/// state and provides therefore no method to predict new data. A typical example are kernel
11/// methods.
12///
13/// It should be implemented for all algorithms, also for those which can be fitted.
14///
15pub trait Transformer<R: Records, T> {
16 fn transform(&self, x: R) -> T;
17}
18
19/// Fittable algorithms
20///
21/// A fittable algorithm takes a dataset and creates a concept of some kind about it. For example
22/// in *KMeans* this would be the mean values for each class, or in *SVM* the separating
23/// hyperplane. It returns a model, which can be used to predict targets for new data.
24pub trait Fit<R: Records, T, E: std::error::Error + From<crate::error::Error>> {
25 type Object;
26
27 fn fit(&self, dataset: &DatasetBase<R, T>) -> Result<Self::Object, E>;
28}
29
30/// Incremental algorithms
31///
32/// An incremental algorithm takes a former model and dataset and returns a new model with updated
33/// parameters. If the former model is `None`, then the function acts like `Fit::fit` and
34/// initializes the model first.
35pub trait FitWith<'a, R: Records, T, E: std::error::Error + From<crate::error::Error>> {
36 type ObjectIn: 'a;
37 type ObjectOut: 'a;
38
39 fn fit_with(
40 &self,
41 model: Self::ObjectIn,
42 dataset: &'a DatasetBase<R, T>,
43 ) -> Result<Self::ObjectOut, E>;
44}
45
46/// Predict with model
47///
48/// This trait assumes the `PredictInplace` implementation and provides additional input/output
49/// combinations.
50///
51/// # Provided implementation
52///
53/// ```rust, ignore
54/// use linfa::traits::Predict;
55///
56/// // predict targets with reference to dataset (&Dataset -> Array)
57/// let pred_targets = model.predict(&dataset);
58/// // predict targets inside dataset (Dataset -> Dataset)
59/// let pred_dataset = model.predict(dataset);
60/// // or use a record datastruct directly (Array -> Dataset)
61/// let pred_targets = model.predict(x);
62/// ```
63pub trait Predict<R: Records, T> {
64 fn predict(&self, x: R) -> T;
65}
66
67/// Predict with model into a mutable reference of targets.
68pub trait PredictInplace<R: Records, T> {
69 /// Predict something in place
70 fn predict_inplace<'a>(&'a self, x: &'a R, y: &mut T);
71
72 /// Create targets that `predict_inplace` works with.
73 fn default_target(&self, x: &R) -> T;
74}