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
use learning::SupModel;
use linalg::Matrix;
use linalg::Vector;
use learning::toolkit::cost_fn::CostFunc;
use learning::toolkit::cost_fn::MeanSqError;
use learning::optim::grad_desc::GradientDesc;
use learning::optim::OptimAlgorithm;
use learning::optim::Optimizable;
#[derive(Debug)]
pub struct LinRegressor {
parameters: Option<Vector<f64>>,
}
impl Default for LinRegressor {
fn default() -> LinRegressor {
LinRegressor { parameters: None }
}
}
impl LinRegressor {
pub fn parameters(&self) -> Option<&Vector<f64>> {
self.parameters.as_ref()
}
}
impl SupModel<Matrix<f64>, Vector<f64>> for LinRegressor {
fn train(&mut self, inputs: &Matrix<f64>, targets: &Vector<f64>) {
let ones = Matrix::<f64>::ones(inputs.rows(), 1);
let full_inputs = ones.hcat(inputs);
let xt = full_inputs.transpose();
self.parameters =
Some(((&xt * full_inputs).inverse().expect("Could not compute (X_T X) inverse.") *
&xt) * targets);
}
fn predict(&self, inputs: &Matrix<f64>) -> Vector<f64> {
if let Some(ref v) = self.parameters {
let ones = Matrix::<f64>::ones(inputs.rows(), 1);
let full_inputs = ones.hcat(inputs);
full_inputs * v
} else {
panic!("Model has not been trained.");
}
}
}
impl Optimizable for LinRegressor {
type Inputs = Matrix<f64>;
type Targets = Vector<f64>;
fn compute_grad(&self,
params: &[f64],
inputs: &Matrix<f64>,
targets: &Vector<f64>)
-> (f64, Vec<f64>) {
let beta_vec = Vector::new(params.to_vec());
let outputs = inputs * beta_vec;
let cost = MeanSqError::cost(&outputs, targets);
let grad = (inputs.transpose() * (outputs - targets)) / (inputs.rows() as f64);
(cost, grad.into_vec())
}
}
impl LinRegressor {
pub fn train_with_optimization(&mut self, inputs: &Matrix<f64>, targets: &Vector<f64>) {
let ones = Matrix::<f64>::ones(inputs.rows(), 1);
let full_inputs = ones.hcat(inputs);
let initial_params = vec![0.; full_inputs.cols()];
let gd = GradientDesc::default();
let optimal_w = gd.optimize(self, &initial_params[..], &full_inputs, targets);
self.parameters = Some(Vector::new(optimal_w));
}
}