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
//! Module for linear regression.
//!
extern crate rand;
extern crate libc;

use self::rand::{thread_rng, Rng};
use std::iter::repeat;

use matrix::*;
use ops::{MatrixVectorMul, MatrixVectorOps};

/// Hypothesis for linear regression.
///
/// <script type="text/javascript"
///   src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML">
/// </script>
/// <script type="text/x-mathjax-config">
///   MathJax.Hub.Config({tex2jax: {inlineMath: [['$','$'], ['\\(','\\)']]}});
/// </script>
pub struct Hypothesis {
    /// Parameters of the hypothesis.
    thetas: Vec<f64>
}

impl Hypothesis {

    /// Creates a hypothesis with parameters initialized with random values in the
    /// interval [0,1).
    ///
    /// The parameter `n` denotes the number of parameters of the hypothesis.
    ///
    /// # Example
    ///
    /// ```
    /// # extern crate rustml;
    /// use rustml::regression::*;
    ///
    /// # fn main() {
    /// let h = Hypothesis::random(5);
    /// assert_eq!(h.params().len(), 5);
    /// assert!(h.params().iter().all(|&x| x < 1.0));
    /// # }
    /// ```
    pub fn random(n: usize) -> Hypothesis {
        Hypothesis {
            thetas: thread_rng().gen_iter::<f64>().take(n).collect()
        }
    }

    /// Creates a new hypothesis with the given parameters.
    ///
    /// # Example
    ///
    /// ```
    /// # extern crate rustml;
    /// use rustml::regression::*;
    ///
    /// # fn main() {
    /// let h = Hypothesis::from_params(&[0.1, 0.2, 0.3]);
    /// assert_eq!(h.params().len(), 3);
    /// assert_eq!(h.params(), vec![0.1, 0.2, 0.3]);
    /// # }
    /// ```
    pub fn from_params(params: &[f64]) -> Hypothesis {
        Hypothesis {
            thetas: params.to_vec()
        }
    }

    /// Returns the parameters for this hypothesis.
    ///
    /// # Example
    ///
    /// ```
    /// # extern crate rustml;
    /// use rustml::regression::*;
    ///
    /// # fn main() {
    /// let h = Hypothesis::from_params(&[0.1, 0.2, 0.3]);
    /// assert_eq!(h.params(), vec![0.1, 0.2, 0.3]);
    /// # }
    /// ```
    pub fn params(&self) -> Vec<f64> {
        self.thetas.clone()
    }

    /// Computes the hypothesis for the given design matrix using the underlying
    /// BLAS implementation for high performance.
    ///
    /// The following equation is used to compute the hypothesis: 
    /// $h_\theta (X) = X\theta$ where $\theta$ is the row vector of
    /// the parameters.
    /// The result is a vector $y$ where the component $y_i$ is the result
    /// of the hypothesis evaluated for the example at row $i$ of the
    /// matrix, i.e.
    /// $y_i = h_\theta(x\^{(i)}) = \theta\^Tx\^{(i)}$
    ///
    /// # Example
    ///
    /// ```
    /// # #[macro_use] extern crate rustml;
    /// use rustml::*;
    /// use rustml::regression::*;
    ///
    /// # fn main() {
    /// let x = mat![
    ///     1.0, 2.0, 3.0;
    ///     1.0, 5.0, 4.0
    /// ];
    /// let h = Hypothesis::from_params(&[0.1, 0.2, 0.3]);
    /// assert_eq!(
    ///     h.eval(&x), 
    ///     vec![0.1 + 0.4 + 0.9, 0.1 + 1.0 + 1.2]
    /// );
    /// # }
    /// ```

    pub fn eval(&self, x: &Matrix<f64>) -> Vec<f64> {
        x.mul_vec(&self.thetas)
    }

    /// Computes the error of the hypothesis for the examples in the
    /// design matrix `x` and the target values `y`. 
    ///
    /// $$\frac{1}{m}(X\theta-y)\^T(X\theta-y)$$
    pub fn error(&self, x: &Matrix<f64>, y: &[f64]) -> f64 {

        x.mul_vec_minus_vec(&self.thetas, y)
            .iter()
            .fold(0.0, |acc, &x| acc + x*x) / 2.0 / (x.rows() as f64)
    }

    pub fn derivatives(&self, x: &Matrix<f64>, y: &[f64]) -> Vec<f64> {

        let v = x.mul_vec_minus_vec(&self.thetas, &y);
        x.mul_scalar_vec(
            true,
            1.0 / (x.rows() as f64),
            &v
        )
    }
}

/// Trait to create the design matrix of a matrix of features, i.e. a new column is
/// inserted at the left of the matrix where all elements are equal to one.
///
/// ```
/// # #[macro_use] extern crate rustml;
/// use rustml::*;
/// use rustml::regression::DesignMatrix;
///
/// # fn main() {
/// let m = mat![
///     2.0, 3.0, 4.0;
///     5.0, 6.0, 7.0
/// ];
/// let d = m.design_matrix();
/// assert!(
///     d.eq(
///         &mat![
///             1.0, 2.0, 3.0, 4.0;
///             1.0, 5.0, 6.0, 7.0
///         ]
///     )
/// );
/// # }
/// ```
pub trait DesignMatrix<T> {
    fn design_matrix(&self) -> Self;
}

impl DesignMatrix<f64> for Matrix<f64> {
    fn design_matrix(&self) -> Self {
        self.insert_column(0, 
            &repeat(1.0).take(self.rows()).collect::<Vec<f64>>()
        )
    }
}

impl DesignMatrix<f32> for Matrix<f32> {
    fn design_matrix(&self) -> Self {
        self.insert_column(0, 
            &repeat(1.0).take(self.rows()).collect::<Vec<f32>>()
        )
    }
}

// ----------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use matrix::*;

    #[test]
    fn test_hypothesis() {
        let h = Hypothesis::random(5);
        assert!(h.thetas.iter().all(|&x| x < 1.0));

        let i = Hypothesis::from_params(&[0.1, 0.2, 0.3, 0.4]);
        assert_eq!(i.params(), vec![0.1, 0.2, 0.3, 0.4]);
    }

    #[test]
    fn test_eval() {
        let x = mat![1.0, 2.0, 3.0; 4.0, 2.0, 5.0];
        let h = Hypothesis::from_params(&[2.0, 6.0, 3.0]);
        let y = h.eval(&x);
        assert_eq!(y, vec![23.0, 35.0]);
    }

    #[test]
    fn test_design_matrix() {
        let x = mat![
            7.0, 2.0, 3.0; 
            4.0, 8.0, 5.0
        ];
        let y = x.design_matrix();
        assert_eq!(
            y.buf(),
            &[1.0, 7.0, 2.0, 3.0, 1.0, 4.0, 8.0, 5.0]
        );
    }

    #[test]
    fn test_error() {
        let x = mat![
            1.0, 2.0, 3.0; 
            4.0, 2.0, 5.0
        ];
        let h = Hypothesis::from_params(&[2.0, 6.0, 3.0]);
        let y = [7.0, 2.0];

        assert_eq!(
            h.error(&x, &y),
            336.25
        );
    }

    #[test]
    fn test_derivatives() {
        let x = mat![
            1.0, 2.0, 3.0; 
            4.0, 2.0, 5.0
        ];
        let h = Hypothesis::from_params(&[2.0, 6.0, 3.0]);
        let y = [7.0, 2.0];

        assert_eq!(
            h.derivatives(&x, &y),
            vec![74.0, 49.0, 106.5]
        );
    }
}