MCPcopy Create free account
hub / github.com/daniel-e/rustml / opt

Function opt

src/opt.rs:238–264  ·  view source on GitHub ↗

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>)

Source from the content-addressed store, hash-verified

236/// # }
237/// ```
238pub 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
267pub fn opt_hypothesis(h: &Hypothesis, x: &Matrix<f64>, y: &[f64], opts: OptParams<f64>) -> OptResult<f64> {

Callers 1

mainFunction · 0.85

Calls 3

subMethod · 0.80
to_vecMethod · 0.45
iterMethod · 0.45

Tested by

no test coverage detected