TODO duplicated code
(h: &Hypothesis, x: &Matrix<f64>, y: &[f64], opts: OptParams<f64>)
| 265 | |
| 266 | // TODO duplicated code |
| 267 | pub fn opt_hypothesis(h: &Hypothesis, x: &Matrix<f64>, y: &[f64], opts: OptParams<f64>) -> OptResult<f64> { |
| 268 | |
| 269 | let alpha = opts.alpha.unwrap_or(0.1); |
| 270 | let iter = opts.iter.unwrap_or(1000); |
| 271 | let eps = opts.eps; |
| 272 | |
| 273 | let mut r = vec![]; |
| 274 | let mut p = h.params(); |
| 275 | let mut stopped = false; |
| 276 | |
| 277 | let mut hx = Hypothesis::from_params(&p); |
| 278 | |
| 279 | for _ in (0..iter) { |
| 280 | let d = hx.derivatives(x, y); |
| 281 | let i = p.sub(&d.mul_scalar(alpha)); |
| 282 | hx = Hypothesis::from_params(&i); |
| 283 | r.push((i.clone(), hx.error(&x, &y))); |
| 284 | stopped = eps.is_some() && i.iter().zip(p.iter()).all(|(&x, &y)| num::abs(x - y) <= eps.unwrap()); |
| 285 | p = i; |
| 286 | if stopped { |
| 287 | break; |
| 288 | } |
| 289 | } |
| 290 | |
| 291 | OptResult { |
| 292 | params: p.to_vec(), |
| 293 | fvals: r, |
| 294 | stopped: stopped |
| 295 | } |
| 296 | } |
| 297 | |
| 298 | /// Plots the learning curve from an optimization result. |
| 299 | /// |