clear_ml/
models.rs

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
use crate::{
    loss_functions::gradient_mse,
    util::{validate_not_empty, validate_same_length},
    Error,
};

/// Linear model.
///
/// # Formula
///
/// y = a0(intercept) + a1*x1 + a2*x2 + ... + an*xn
///
#[derive(Debug)]
pub struct LinearModel {
    pub intercept: f64,
    pub weights: Vec<f64>,
}

impl LinearModel {
    /// Create a new linear model.
    pub fn new() -> Self {
        LinearModel {
            intercept: 0.0,
            weights: Vec::new(),
        }
    }

    /// Fit linear model.
    ///
    /// # Arguments
    ///
    /// * `x` - Matrix of features
    /// * `y` - Vector of actual values
    ///
    /// # Requirements
    ///
    /// * `x` must have the same length as `y`
    /// * `x`'s rows must all be same length
    ///
    /// # Returns
    ///
    /// * `Ok(&Self)` if successful
    /// * `Err(Error)` if unsuccessful
    pub fn fit(&mut self, x: &Vec<Vec<f64>>, y: &Vec<f64>) -> Result<&Self, Error> {
        validate_not_empty(x)?;
        validate_not_empty(y)?;

        validate_same_length(x, y)?;

        // validate all rows have same length
        let first_row = x.first().unwrap();
        x.iter()
            .skip(1)
            .try_for_each(|row| validate_same_length(first_row, row))?;

        Ok(self._fit(x, y, 1000, 0.01, 0.000001))
    }

    fn _fit(
        &mut self,
        x: &Vec<Vec<f64>>,
        y: &Vec<f64>,
        max_iter: u32,
        learning_rate: f64,
        tol: f64,
    ) -> &Self {
        // initialize coefficients to 0
        self.weights = vec![0.0; x.first().unwrap().len()];

        for _ in 0..max_iter {
            let y_hat = self._predict(x);

            let gradient = gradient_mse(x, &y_hat, y).unwrap();
            if gradient.iter().all(|g| g.abs() < tol) {
                break;
            }

            // update coefficients
            self.weights = self
                .weights
                .iter()
                .zip(&gradient)
                .map(|(a, g)| a - learning_rate * g)
                .collect();

            // update intercept
            self.intercept -= learning_rate * gradient.last().unwrap();
        }

        self
    }

    /// Predict using the linear model.
    ///
    /// # Arguments
    ///
    /// * `x` - Matrix of features
    ///
    /// # Requirements
    ///
    /// * `x`'s rows must all match the length of the coefficients of the `LinearModel`
    ///
    /// # Returns
    ///
    /// * `Ok(Vec<f64>)` if successful
    /// * `Err(Error)` if unsuccessful
    pub fn predict(&self, x: &Vec<Vec<f64>>) -> Result<Vec<f64>, Error> {
        validate_not_empty(x)?;

        // validate all rows are same length as coefficients
        x.iter()
            .try_for_each(|row| validate_same_length(row, &self.weights))?;

        Ok(self._predict(x))
    }

    fn _predict(&self, x: &Vec<Vec<f64>>) -> Vec<f64> {
        x.iter()
            .map(|row| {
                row.iter()
                    .zip(&self.weights)
                    .map(|(x, a)| x * a)
                    .sum::<f64>()
                    + self.intercept
            })
            .collect()
    }
}

#[cfg(test)]
mod tests {
    use std::vec;

    use super::*;

    #[test]
    fn test_fit_empty_vector() {
        let x: Vec<Vec<f64>> = vec![];
        let y: Vec<f64> = vec![];

        assert!(LinearModel::new().fit(&x, &y).is_err());
        assert_eq!(
            LinearModel::new().fit(&x, &y).unwrap_err(),
            Error::EmptyVector
        );
    }

    #[test]
    fn test_fit_dimension_mismatch() {
        let x: Vec<Vec<f64>> = vec![vec![1.0, 2.0, 3.0]];
        let y: Vec<f64> = vec![0.0; 3];

        assert!(LinearModel::new().fit(&x, &y).is_err());
        assert_eq!(
            LinearModel::new().fit(&x, &y).unwrap_err(),
            Error::DimensionMismatch
        );
    }

    #[test]
    fn test_fit() {
        let x = vec![vec![1.0], vec![2.0], vec![5.0], vec![6.0]];
        let y = vec![1.0, 2.0, 5.0, 6.0];

        let mut model = LinearModel::new();

        model.fit(&x, &y).unwrap();

        // TODO: write more descriptive tests        
    }

    #[test]
    fn test_fit_with_intercept() {
        let x = vec![vec![1.0], vec![2.0]];
        let y = vec![2.0, 4.0];

        let mut model = LinearModel::new();

        model.fit(&x, &y).unwrap();
    }

    #[test]
    fn test_predict_empty_vector() {
        let x: Vec<Vec<f64>> = vec![];

        assert!(LinearModel::new().predict(&x).is_err());
        assert_eq!(
            LinearModel::new().predict(&x).unwrap_err(),
            Error::EmptyVector
        );
    }

    #[test]
    fn test_predict_different_row_length() {
        let mut model = LinearModel::new();

        model.intercept = 1.0;
        model.weights = vec![1.0, 1.0];

        let x: Vec<Vec<f64>> = vec![vec![1.0, 1.0], vec![1.0]];

        assert!(model.predict(&x).is_err());
        assert_eq!(model.predict(&x).unwrap_err(), Error::DimensionMismatch);
    }

    #[test]
    fn test_predict() {
        let mut model = LinearModel::new();

        model.intercept = 1.0;
        model.weights = vec![1.0];

        let x: Vec<Vec<f64>> = vec![vec![1.0], vec![2.0], vec![3.0]];
        let expected: Vec<f64> = vec![2.0, 3.0, 4.0];

        assert_eq!(model.predict(&x).unwrap(), expected);
    }

    #[test]
    fn test_predict_with_multiple_coefficients() {
        let mut model = LinearModel::new();

        model.intercept = 1.0;
        model.weights = vec![1.0, 2.0];

        let x: Vec<Vec<f64>> = vec![vec![1.0, 1.0], vec![2.0, 2.0], vec![3.0, 3.0]];
        let expected: Vec<f64> = vec![4.0, 7.0, 10.0];

        assert_eq!(model.predict(&x).unwrap(), expected);
    }
}