Skip to content

valueAndGrad

valueAndGrad(f): (x, inputs?) => object

Defined in: api.js:154

Differentiate a scalar objective, returning both value and gradient.

Parameters

f

(x, inputs?) => Var

objective, built from this package’s ops. It receives Vars in the same structure as the parameters, and, when the returned function is called with a second argument, a map of input Vars as its own second argument. It must return a scalar Var.

Returns

with a .value(x, inputs) that evaluates the objective alone, and may return a non-scalar in the boundary currency.

(x, inputs?) => object

Examples

const f = (p) => add(square(p.mu), square(p.sigma));
valueAndGrad(f)({ mu: 3, sigma: 4 });
// { value: 25, gradient: { mu: 6, sigma: 8 } }
// Data as inputs rather than closed-over constants: the same objective
// evaluates on any batch.
const sse = (p, d) => sum(square(sub(d.y, mul(p.slope, d.x))));
valueAndGrad(sse)({ slope: 2 }, { x: [1, 2], y: [2, 5] });