Minimizes an objective using gradient descent. The objective `f` is minimized using a standard gradient descent algorithm. The argument `fd` must return the values of the derivatives for each parameter and is executed in each iteration for the current parameters. The argument `init` contains the initial parameters and `opts` contains the options for the gradient descent algorithm. <script type="
(f: &O, fd: &D, init: &[f64], opts: OptParams<f64>)
| 236 | /// # } |
| 237 | /// ``` |
| 238 | pub fn opt<O, D>(f: &O, fd: &D, init: &[f64], opts: OptParams<f64>) -> OptResult<f64> |
| 239 | where O: Fn(&[f64]) -> f64, D: Fn(&[f64]) -> Vec<f64> { |
| 240 | |
| 241 | let alpha = opts.alpha.unwrap_or(0.1); |
| 242 | let iter = opts.iter.unwrap_or(1000); |
| 243 | let eps = opts.eps; |
| 244 | |
| 245 | let mut r = vec![]; |
| 246 | let mut p = init.to_vec(); |
| 247 | let mut stopped = false; |
| 248 | |
| 249 | for _ in (0..iter) { |
| 250 | let i = p.sub(&fd(&p).mul_scalar(alpha)); |
| 251 | r.push((i.clone(), f(&i))); |
| 252 | stopped = eps.is_some() && i.iter().zip(p.iter()).all(|(&x, &y)| num::abs(x - y) <= eps.unwrap()); |
| 253 | p = i; |
| 254 | if stopped { |
| 255 | break; |
| 256 | } |
| 257 | } |
| 258 | |
| 259 | OptResult { |
| 260 | params: p.to_vec(), |
| 261 | fvals: r, |
| 262 | stopped: stopped |
| 263 | } |
| 264 | } |
| 265 | |
| 266 | // TODO duplicated code |
| 267 | pub fn opt_hypothesis(h: &Hypothesis, x: &Matrix<f64>, y: &[f64], opts: OptParams<f64>) -> OptResult<f64> { |