@tangent.to/opt 0.2.1 → 0.2.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +82 -103
- package/dist/index.js +11 -1
- package/dist/index.js.map +4 -4
- package/llms-full.txt +1369 -0
- package/llms.txt +183 -0
- package/package.json +12 -5
- package/src/bounds.js +12 -4
- package/src/compat.js +121 -23
- package/src/gradient.js +84 -35
- package/src/help.js +76 -0
- package/src/index.js +8 -0
- package/src/lbfgs.js +15 -9
- package/src/leastsq.js +55 -18
- package/src/linesearch.js +8 -6
- package/src/linsolve.js +2 -2
- package/src/minimize.js +51 -9
- package/src/neldermead.js +16 -10
- package/src/numdiff.js +18 -13
- package/src/scalar.js +21 -11
- package/src/steps.js +47 -25
- package/src/version.js +2 -0
- package/types/blas1.d.ts +36 -0
- package/types/bounds.d.ts +48 -0
- package/types/compat.d.ts +259 -0
- package/types/evaluate.d.ts +19 -0
- package/types/gradient.d.ts +201 -0
- package/types/help.d.ts +17 -0
- package/types/index.d.ts +71 -0
- package/types/lbfgs.d.ts +51 -0
- package/types/leastsq.d.ts +125 -0
- package/types/linesearch.d.ts +35 -0
- package/types/linsolve.d.ts +9 -0
- package/types/minimize.d.ts +104 -0
- package/types/neldermead.d.ts +54 -0
- package/types/numdiff.d.ts +42 -0
- package/types/scalar.d.ts +64 -0
- package/types/steps.d.ts +97 -0
- package/types/version.d.ts +2 -0
package/src/help.js
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import { version } from './version.js';
|
|
2
|
+
|
|
3
|
+
const PACKAGE = '@tangent.to/opt';
|
|
4
|
+
const REMOTE = `https://cdn.jsdelivr.net/npm/${PACKAGE}@${version}/llms-full.txt`;
|
|
5
|
+
|
|
6
|
+
let loading;
|
|
7
|
+
|
|
8
|
+
/** llms-full.txt: beside the package when it is on disk, else from the CDN at this version. */
|
|
9
|
+
async function read() {
|
|
10
|
+
// Not `new URL('…', import.meta.url)`, which bundlers would copy into the app.
|
|
11
|
+
const here = import.meta.url;
|
|
12
|
+
if (here.startsWith('file:')) {
|
|
13
|
+
const local = new URL('../llms-full.txt', here);
|
|
14
|
+
try {
|
|
15
|
+
if (globalThis.Deno) return await globalThis.Deno.readTextFile(local);
|
|
16
|
+
if (globalThis.process?.versions?.node) {
|
|
17
|
+
const moduleName = 'node:fs';
|
|
18
|
+
const fs = globalThis.process.getBuiltinModule?.(moduleName) ?? await import(moduleName);
|
|
19
|
+
return fs.readFileSync(local, 'utf8');
|
|
20
|
+
}
|
|
21
|
+
} catch {
|
|
22
|
+
// not built here: the published copy
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
const res = await fetch(REMOTE);
|
|
26
|
+
if (!res.ok) throw new Error(`help: ${REMOTE} answered ${res.status}`);
|
|
27
|
+
return res.text();
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* The entry for `name` in an llms-full.txt, or the overview without a name.
|
|
32
|
+
* @internal
|
|
33
|
+
*/
|
|
34
|
+
export function lookup(text, name) {
|
|
35
|
+
const at = text.indexOf('\n## Reference\n');
|
|
36
|
+
const overview = at < 0 ? text : text.slice(0, at);
|
|
37
|
+
if (name === undefined) return overview;
|
|
38
|
+
const entries = (at < 0 ? '' : text.slice(at)).split('\n### ').slice(1).map((s) => ({
|
|
39
|
+
name: s.slice(0, s.indexOf('\n')).trim(),
|
|
40
|
+
body: `### ${s.trimEnd()}`,
|
|
41
|
+
}));
|
|
42
|
+
const short = PACKAGE.split('/')[1];
|
|
43
|
+
const key = String(name).replace(new RegExp(`^${short}\\.`), '');
|
|
44
|
+
const exact = entries.filter((e) => e.name === key);
|
|
45
|
+
if (exact.length) return exact.map((e) => e.body).join('\n\n');
|
|
46
|
+
const k = key.toLowerCase();
|
|
47
|
+
const named = entries.filter((e) => e.name.toLowerCase() === k || e.name.toLowerCase().endsWith(`.${k}`));
|
|
48
|
+
if (named.length) return named.map((e) => e.body).join('\n\n');
|
|
49
|
+
// A method: the classes that declare it.
|
|
50
|
+
const method = new RegExp(`\\n\\s+(?:static\\s+|async\\s+|get\\s+)*${key.replace(/[^\w$]/g, '')}\\s*[(<]`);
|
|
51
|
+
const owners = key.match(/^[\w$]+$/) ? entries.filter((e) => method.test(e.body)) : [];
|
|
52
|
+
if (owners.length && owners.length <= 3) return owners.map((e) => e.body).join('\n\n');
|
|
53
|
+
if (owners.length) return `"${name}" is a method of ${owners.map((e) => e.name).join(', ')}: help('one of them').`;
|
|
54
|
+
const close = entries.filter((e) => e.name.toLowerCase().includes(k)).map((e) => e.name);
|
|
55
|
+
return `${PACKAGE} exports nothing named "${name}".`
|
|
56
|
+
+ (close.length ? ` Close: ${close.join(', ')}.` : ' help() lists every export.');
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* This package's documentation, for where the README is out of reach, such
|
|
61
|
+
* as a notebook, and for coding assistants.
|
|
62
|
+
*
|
|
63
|
+
* @param {string} [name] - an export, such as `'minimize'`
|
|
64
|
+
* @returns {Promise<string>} its declaration, options and examples; without
|
|
65
|
+
* `name`, the overview and a line per export
|
|
66
|
+
* @example
|
|
67
|
+
* await help(); // overview and index
|
|
68
|
+
* await help('minimize'); // one export in full
|
|
69
|
+
*/
|
|
70
|
+
export async function help(name) {
|
|
71
|
+
loading ??= read().catch((e) => {
|
|
72
|
+
loading = undefined;
|
|
73
|
+
throw e;
|
|
74
|
+
});
|
|
75
|
+
return lookup(await loading, name);
|
|
76
|
+
}
|
package/src/index.js
CHANGED
|
@@ -27,6 +27,9 @@ export {
|
|
|
27
27
|
RMSProp,
|
|
28
28
|
} from './compat.js';
|
|
29
29
|
|
|
30
|
+
export { help } from './help.js';
|
|
31
|
+
export { version } from './version.js';
|
|
32
|
+
|
|
30
33
|
import { methods, minimize } from './minimize.js';
|
|
31
34
|
import { nelderMead } from './neldermead.js';
|
|
32
35
|
import { lbfgs } from './lbfgs.js';
|
|
@@ -44,7 +47,12 @@ import {
|
|
|
44
47
|
RMSProp,
|
|
45
48
|
} from './compat.js';
|
|
46
49
|
|
|
50
|
+
import { help } from './help.js';
|
|
51
|
+
import { version } from './version.js';
|
|
52
|
+
|
|
47
53
|
export default {
|
|
54
|
+
help,
|
|
55
|
+
version,
|
|
48
56
|
minimize,
|
|
49
57
|
methods,
|
|
50
58
|
nelderMead,
|
package/src/lbfgs.js
CHANGED
|
@@ -23,26 +23,32 @@ function norm2(a) {
|
|
|
23
23
|
/**
|
|
24
24
|
* Minimize a function with L-BFGS.
|
|
25
25
|
*
|
|
26
|
-
* @param {
|
|
27
|
-
*
|
|
26
|
+
* @param {(x: number[]) => number | {loss: number, gradient: number[]|Float64Array} | {value: number, gradient: number[]|Float64Array}} f
|
|
27
|
+
* - Objective: a number, or with its gradient as `{loss, gradient}` or
|
|
28
|
+
* `{value, gradient}`
|
|
29
|
+
* @param {number[]} x0 - Initial parameters
|
|
28
30
|
* @param {Object} [options]
|
|
29
|
-
* @param {
|
|
31
|
+
* @param {(x: number[]) => number[]} [options.grad] - Gradient when `f` returns
|
|
32
|
+
* a number; central differences otherwise
|
|
30
33
|
* @param {number} [options.memory=10] - Number of curvature pairs kept
|
|
31
34
|
* @param {number} [options.maxIter=1000] - Maximum iterations
|
|
32
35
|
* @param {number} [options.tol=1e-6] - Convergence tolerance on the gradient norm
|
|
33
36
|
* @param {number} [options.fTol=1e-12] - Relative function-decrease tolerance
|
|
34
37
|
* @param {number} [options.c1=1e-4] - Line search sufficient-decrease constant
|
|
35
38
|
* @param {number} [options.c2=0.9] - Line search curvature constant
|
|
36
|
-
* @param {
|
|
37
|
-
* @
|
|
39
|
+
* @param {number} [options.h=1e-6] - Finite-difference step, without a gradient
|
|
40
|
+
* @param {boolean} [options.verbose=false] - Log progress every 10 iterations
|
|
41
|
+
* @returns {{x: number[], fx: number, iterations: number, nfev: number, fevals: number, converged: boolean, success: boolean, history: {loss: number[], gradNorm: number[]}}}
|
|
42
|
+
* `converged` is false if the line search fails; `fevals` is a deprecated
|
|
43
|
+
* alias of `nfev`; `success` equals `converged`
|
|
38
44
|
*/
|
|
39
45
|
export function lbfgs(f, x0, options = {}) {
|
|
40
46
|
const n = x0.length;
|
|
41
|
-
const m = options.memory
|
|
42
|
-
const maxIter = options.maxIter
|
|
43
|
-
const tol = options.tol
|
|
47
|
+
const m = options.memory ?? 10;
|
|
48
|
+
const maxIter = options.maxIter ?? 1000;
|
|
49
|
+
const tol = options.tol ?? 1e-6;
|
|
44
50
|
const fTol = options.fTol !== undefined ? options.fTol : 1e-12;
|
|
45
|
-
const verbose = options.verbose
|
|
51
|
+
const verbose = options.verbose ?? false;
|
|
46
52
|
|
|
47
53
|
const evaluate = makeEvaluator(f, options.grad, options);
|
|
48
54
|
let fevals = 0;
|
package/src/leastsq.js
CHANGED
|
@@ -139,13 +139,13 @@ function normalEquations(J, r, w = null) {
|
|
|
139
139
|
}
|
|
140
140
|
|
|
141
141
|
/**
|
|
142
|
-
* Minimize 0.5 * sum(r(p)^2) with Levenberg-Marquardt.
|
|
142
|
+
* Minimize a sum of squared residuals, 0.5 * sum(r(p)^2), with Levenberg-Marquardt.
|
|
143
143
|
*
|
|
144
144
|
* @param {Object} spec
|
|
145
|
-
* @param {
|
|
146
|
-
* @param {
|
|
147
|
-
* @param {
|
|
148
|
-
* central finite differences
|
|
145
|
+
* @param {(p: number[]) => number[]} spec.residuals - Residual vector, length m
|
|
146
|
+
* @param {number[]} spec.x0 - Initial parameters of length n
|
|
147
|
+
* @param {(p: number[]) => number[][]} [spec.jacobian] - m-by-n Jacobian of
|
|
148
|
+
* the residuals; central finite differences otherwise
|
|
149
149
|
* @param {number} [spec.maxIter=200] - Maximum accepted iterations
|
|
150
150
|
* @param {number} [spec.fTol=1e-10] - Relative cost reduction on an accepted step
|
|
151
151
|
* @param {number} [spec.xTol=1e-10] - Max relative step component on an accepted step
|
|
@@ -153,14 +153,23 @@ function normalEquations(J, r, w = null) {
|
|
|
153
153
|
* @param {number} [spec.lambda0=1e-3] - Initial damping
|
|
154
154
|
* @param {number} [spec.lambdaUp=10] - Damping increase factor on rejection
|
|
155
155
|
* @param {number} [spec.lambdaDown=10] - Damping decrease factor on acceptance
|
|
156
|
-
* @param {
|
|
157
|
-
*
|
|
156
|
+
* @param {'linear'|'huber'|'soft_l1'|'cauchy'} [spec.loss='linear'] - Robust
|
|
157
|
+
* losses down-weight outliers (IRLS, scipy least_squares semantics)
|
|
158
158
|
* @param {number} [spec.fScale=1] - Residual scale at which the robust losses
|
|
159
159
|
* start to flatten (scipy's f_scale)
|
|
160
|
-
* @param {Array<
|
|
161
|
-
* bounds (MINUIT transform; null/±Infinity for unbounded sides)
|
|
160
|
+
* @param {Array<[number|null, number|null]|null>} [spec.bounds] - Per-parameter
|
|
161
|
+
* [lo, hi] box bounds (MINUIT transform; null/±Infinity for unbounded sides)
|
|
162
162
|
* @param {boolean} [spec.history=false] - Record {cost, lambda} per accepted iteration
|
|
163
|
-
* @returns {
|
|
163
|
+
* @returns {{x: number[], fx: number, residuals: number[], iterations: number, fevals: number, converged: boolean, bounded?: boolean, history?: Array<{cost: number, lambda: number}>}}
|
|
164
|
+
* `fx` is the cost, 0.5 * sum(r^2) (with a robust loss, 0.5 * fScale^2 *
|
|
165
|
+
* sum(rho)); `residuals` are at `x`; `bounded` is set with `bounds`
|
|
166
|
+
* @example
|
|
167
|
+
* const r = leastSquares({
|
|
168
|
+
* residuals: ([a, b]) => [10 * (b - a * a), 1 - a],
|
|
169
|
+
* x0: [-1.2, 1],
|
|
170
|
+
* });
|
|
171
|
+
* r.x; // ≈ [1, 1]
|
|
172
|
+
* r.fx; // ≈ 0
|
|
164
173
|
*/
|
|
165
174
|
export function leastSquares(spec = {}) {
|
|
166
175
|
const {
|
|
@@ -327,16 +336,44 @@ export function leastSquares(spec = {}) {
|
|
|
327
336
|
}
|
|
328
337
|
|
|
329
338
|
/**
|
|
330
|
-
* Fit a
|
|
339
|
+
* Fit a model to (x, y) data by least squares, scipy.optimize.curve_fit style.
|
|
340
|
+
*
|
|
341
|
+
* The residuals are `y[i] - model(x[i], params)`; the keys after `p0` go to
|
|
342
|
+
* `leastSquares`. `cov` is `inv(J^T J) * s^2` with `s^2 = 2 * fx / (m - n)`;
|
|
343
|
+
* it and `stdErr` are NaN with a robust loss, with no more data than
|
|
344
|
+
* parameters, or when `J^T J` is singular.
|
|
331
345
|
*
|
|
332
346
|
* @param {Object} spec
|
|
333
|
-
* @param {
|
|
334
|
-
*
|
|
335
|
-
* @param {
|
|
336
|
-
*
|
|
337
|
-
* @param {
|
|
338
|
-
*
|
|
339
|
-
* @
|
|
347
|
+
* @param {(x: any, params: number[]) => number} spec.model - Prediction for
|
|
348
|
+
* one datum `x[i]`
|
|
349
|
+
* @param {any[]} spec.x - Independent data, one entry per observation (numbers,
|
|
350
|
+
* or arrays for several variables)
|
|
351
|
+
* @param {number[]} spec.y - Dependent data, same length as x
|
|
352
|
+
* @param {number[]} spec.p0 - Initial parameters
|
|
353
|
+
* @param {Array<[number|null, number|null]|null>} [spec.bounds] - Per-parameter
|
|
354
|
+
* [lo, hi] box bounds, null/±Infinity for an open side
|
|
355
|
+
* @param {(p: number[]) => number[][]} [spec.jacobian] - m-by-n Jacobian of
|
|
356
|
+
* the residuals, which is minus the model's; finite differences otherwise
|
|
357
|
+
* @param {'linear'|'huber'|'soft_l1'|'cauchy'} [spec.loss='linear'] - Robust loss
|
|
358
|
+
* @param {number} [spec.fScale=1] - Residual scale for the robust losses
|
|
359
|
+
* @param {number} [spec.maxIter=200] - Maximum accepted iterations
|
|
360
|
+
* @param {number} [spec.fTol=1e-10] - Relative cost reduction on an accepted step
|
|
361
|
+
* @param {number} [spec.xTol=1e-10] - Max relative step component on an accepted step
|
|
362
|
+
* @param {number} [spec.gTol=1e-10] - Inf-norm of the gradient J^T r
|
|
363
|
+
* @param {number} [spec.lambda0=1e-3] - Initial damping
|
|
364
|
+
* @param {number} [spec.lambdaUp=10] - Damping increase factor on rejection
|
|
365
|
+
* @param {number} [spec.lambdaDown=10] - Damping decrease factor on acceptance
|
|
366
|
+
* @returns {{params: number[], cov: number[][], stdErr: number[], fx: number, iterations: number, converged: boolean}}
|
|
367
|
+
* `fx` is the cost, 0.5 * sum of squared residuals (with a robust loss,
|
|
368
|
+
* the robust cost)
|
|
369
|
+
* @example
|
|
370
|
+
* const { params, stdErr } = curveFit({
|
|
371
|
+
* model: (t, [a, b, c]) => a * Math.exp(-b * t) + c,
|
|
372
|
+
* x: [0, 0.5, 1, 1.5, 2, 2.5, 3, 3.5, 4],
|
|
373
|
+
* y: [3.02, 1.80, 1.17, 0.85, 0.66, 0.59, 0.55, 0.52, 0.51],
|
|
374
|
+
* p0: [1, 1, 0],
|
|
375
|
+
* });
|
|
376
|
+
* // params ≈ [2.524, 1.322, 0.496], stdErr ≈ [0.0078, 0.0100, 0.0043]
|
|
340
377
|
*/
|
|
341
378
|
export function curveFit(spec = {}) {
|
|
342
379
|
const { model, x, y, p0, ...options } = spec;
|
package/src/linesearch.js
CHANGED
|
@@ -38,20 +38,22 @@ function interpolate(a, fa, da, b, fb, db) {
|
|
|
38
38
|
}
|
|
39
39
|
|
|
40
40
|
/**
|
|
41
|
-
*
|
|
41
|
+
* Find a step along direction p from x that satisfies the strong Wolfe conditions.
|
|
42
42
|
*
|
|
43
|
-
* @param {
|
|
44
|
-
* @param {
|
|
45
|
-
* @param {
|
|
43
|
+
* @param {(x: number[]) => {loss: number, gradient: ArrayLike<number>}} evaluate - Objective and gradient
|
|
44
|
+
* @param {number[]} x - Starting point
|
|
45
|
+
* @param {number[]|Float64Array} p - Descent direction (g0'p must be < 0)
|
|
46
46
|
* @param {number} f0 - f(x)
|
|
47
|
-
* @param {
|
|
47
|
+
* @param {ArrayLike<number>} g0 - gradient at x
|
|
48
48
|
* @param {Object} [options]
|
|
49
49
|
* @param {number} [options.t0=1] - Initial step
|
|
50
50
|
* @param {number} [options.c1=1e-4] - Sufficient-decrease constant
|
|
51
51
|
* @param {number} [options.c2=0.9] - Curvature constant
|
|
52
52
|
* @param {number} [options.maxIter=25] - Bracketing iterations
|
|
53
53
|
* @param {number} [options.tMax=1e10] - Maximum step
|
|
54
|
-
* @returns {
|
|
54
|
+
* @returns {{success: boolean, t: number, fx: number, gradient: ArrayLike<number>, xNew: number[], fevals: number}}
|
|
55
|
+
* The step `t`, and f and its gradient at `xNew = x + t * p`; on failure,
|
|
56
|
+
* `t = 0` and the starting values
|
|
55
57
|
*/
|
|
56
58
|
export function strongWolfeLineSearch(evaluate, x, p, f0, g0, options = {}) {
|
|
57
59
|
const c1 = options.c1 !== undefined ? options.c1 : 1e-4;
|
package/src/linsolve.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
|
|
1
|
+
/*
|
|
2
2
|
* Dense linear-system solver.
|
|
3
3
|
*
|
|
4
4
|
* Gaussian elimination with scaled partial pivoting for the small n-by-n
|
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
*/
|
|
8
8
|
|
|
9
9
|
/**
|
|
10
|
-
* Solve the linear system A x = b.
|
|
10
|
+
* Solve the linear system A x = b by Gaussian elimination with scaled partial pivoting.
|
|
11
11
|
*
|
|
12
12
|
* @param {Array<Array<number>>} A - n-by-n coefficient matrix (not mutated)
|
|
13
13
|
* @param {Array<number>} b - Right-hand side of length n (not mutated)
|
package/src/minimize.js
CHANGED
|
@@ -41,8 +41,8 @@ const METHODS = {
|
|
|
41
41
|
};
|
|
42
42
|
|
|
43
43
|
/**
|
|
44
|
-
* List the
|
|
45
|
-
* @returns {Array<string>}
|
|
44
|
+
* List the method names `minimize` accepts, aliases included.
|
|
45
|
+
* @returns {Array<string>} `['neldermead', 'nelder-mead', 'lbfgs', 'l-bfgs', 'gd', 'sgd', 'gradient_descent', 'adam']`
|
|
46
46
|
*/
|
|
47
47
|
export function methods() {
|
|
48
48
|
return Object.keys(METHODS);
|
|
@@ -51,14 +51,56 @@ export function methods() {
|
|
|
51
51
|
/**
|
|
52
52
|
* Minimize a scalar function of one or more variables.
|
|
53
53
|
*
|
|
54
|
+
* The other keys of `spec` go to the method; each method's defaults are on
|
|
55
|
+
* `nelderMead`, `lbfgs`, `gradientDescent` and `adam`.
|
|
56
|
+
*
|
|
54
57
|
* @param {Object} spec
|
|
55
|
-
* @param {
|
|
56
|
-
*
|
|
57
|
-
*
|
|
58
|
-
* @param {
|
|
59
|
-
* @param {
|
|
60
|
-
*
|
|
61
|
-
* @
|
|
58
|
+
* @param {(x: number[]) => number | {loss: number, gradient: number[]|Float64Array} | {value: number, gradient: number[]|Float64Array}} spec.f
|
|
59
|
+
* - Objective: a number, `{loss, gradient}` or `{value, gradient}` (what
|
|
60
|
+
* `@tangent.to/grad`'s `valueAndGrad` and `compile` return)
|
|
61
|
+
* @param {number[]} spec.x0 - Initial parameters
|
|
62
|
+
* @param {'neldermead'|'nelder-mead'|'lbfgs'|'l-bfgs'|'gd'|'sgd'|'gradient_descent'|'adam'} [spec.method='neldermead']
|
|
63
|
+
* - Case-insensitive; `'lbfgs'` for smooth objectives
|
|
64
|
+
* @param {(x: number[]) => number[]} [spec.grad] - Gradient, for the
|
|
65
|
+
* gradient methods when `f` returns a number; central differences otherwise
|
|
66
|
+
* @param {Array<[number|null, number|null]|null>} [spec.bounds] - `[lo, hi]`
|
|
67
|
+
* per parameter, `null` or ±Infinity for an open side; works with every method
|
|
68
|
+
* @param {number} [spec.maxIter] - Iteration cap
|
|
69
|
+
* @param {number} [spec.tol] - Gradient-norm tolerance; for Nelder-Mead, the
|
|
70
|
+
* default of `fTol`
|
|
71
|
+
* @param {number} [spec.fTol] - Function tolerance (Nelder-Mead, L-BFGS)
|
|
72
|
+
* @param {number} [spec.xTol] - Simplex-size tolerance (Nelder-Mead)
|
|
73
|
+
* @param {number} [spec.learningRate] - Step size (gd, adam)
|
|
74
|
+
* @param {boolean} [spec.lineSearch] - Backtracking line search (gd)
|
|
75
|
+
* @param {number} [spec.memory] - Curvature pairs kept (L-BFGS)
|
|
76
|
+
* @param {number} [spec.c1] - Line-search constant (L-BFGS)
|
|
77
|
+
* @param {number} [spec.c2] - Line-search constant (L-BFGS)
|
|
78
|
+
* @param {number} [spec.beta1] - Adam constant
|
|
79
|
+
* @param {number} [spec.beta2] - Adam constant
|
|
80
|
+
* @param {number} [spec.epsilon] - Adam constant
|
|
81
|
+
* @param {number} [spec.rho] - Nelder-Mead reflection coefficient
|
|
82
|
+
* @param {number} [spec.chi] - Nelder-Mead expansion coefficient
|
|
83
|
+
* @param {number} [spec.psi] - Nelder-Mead contraction coefficient
|
|
84
|
+
* @param {number} [spec.sigma] - Nelder-Mead shrink coefficient
|
|
85
|
+
* @param {number} [spec.nonZeroDelta] - Nelder-Mead initial simplex scale
|
|
86
|
+
* @param {number} [spec.zeroDelta] - Nelder-Mead initial simplex offset
|
|
87
|
+
* @param {number} [spec.h] - Finite-difference step for the gradient
|
|
88
|
+
* @param {boolean} [spec.history] - Nelder-Mead: record the simplex per
|
|
89
|
+
* iteration (the other methods always return a history)
|
|
90
|
+
* @param {boolean} [spec.verbose] - Log progress (gradient methods)
|
|
91
|
+
* @returns {{x: number[], fx: number, iterations: number, nfev: number, converged: boolean, success: boolean, method: string, bounded?: boolean, fevals?: number, history?: any}}
|
|
92
|
+
* `method` is the name as given, lowercased; `bounded` is set with
|
|
93
|
+
* `bounds`; `history` is the method's (with bounds, its points and
|
|
94
|
+
* gradient norms are in internal coordinates); `fevals` (Nelder-Mead,
|
|
95
|
+
* L-BFGS) is a deprecated alias of `nfev`
|
|
96
|
+
* @example
|
|
97
|
+
* const r = minimize({
|
|
98
|
+
* f: ([a, b]) => (1 - a) ** 2 + 100 * (b - a * a) ** 2,
|
|
99
|
+
* x0: [-1.2, 1],
|
|
100
|
+
* method: 'lbfgs',
|
|
101
|
+
* });
|
|
102
|
+
* r.x; // ≈ [1, 1]
|
|
103
|
+
* r.converged; // true
|
|
62
104
|
*/
|
|
63
105
|
export function minimize(spec = {}) {
|
|
64
106
|
const { f, x0, method = 'neldermead', bounds, ...options } = spec;
|
package/src/neldermead.js
CHANGED
|
@@ -17,11 +17,16 @@ import { makeScalarEvaluator } from './evaluate.js';
|
|
|
17
17
|
/**
|
|
18
18
|
* Minimize a function using the Nelder-Mead downhill simplex method.
|
|
19
19
|
*
|
|
20
|
-
*
|
|
21
|
-
*
|
|
20
|
+
* Stops when the simplex's f spread is below `fTol` and its best two
|
|
21
|
+
* vertices are within `xTol` in every coordinate.
|
|
22
|
+
*
|
|
23
|
+
* @param {(x: number[]) => number | {loss: number} | {value: number}} f - Objective;
|
|
24
|
+
* a returned gradient is ignored
|
|
25
|
+
* @param {number[]} x0 - Initial parameters
|
|
22
26
|
* @param {Object} [options]
|
|
23
|
-
* @param {number} [options.maxIter=200*n] - Maximum iterations
|
|
27
|
+
* @param {number} [options.maxIter=200*n] - Maximum iterations, n = x0.length
|
|
24
28
|
* @param {number} [options.fTol=1e-6] - Convergence tolerance on f spread across the simplex
|
|
29
|
+
* @param {number} [options.tol] - Alias of `fTol`, read when `fTol` is not given
|
|
25
30
|
* @param {number} [options.xTol=1e-5] - Convergence tolerance on x spread across the simplex
|
|
26
31
|
* @param {number} [options.rho=1] - Reflection coefficient
|
|
27
32
|
* @param {number} [options.chi=2] - Expansion coefficient
|
|
@@ -30,20 +35,21 @@ import { makeScalarEvaluator } from './evaluate.js';
|
|
|
30
35
|
* @param {number} [options.nonZeroDelta=1.05] - Relative perturbation for nonzero x0 entries
|
|
31
36
|
* @param {number} [options.zeroDelta=1e-3] - Absolute perturbation for zero x0 entries
|
|
32
37
|
* @param {boolean} [options.history=false] - Record {x, fx, simplex} per iteration
|
|
33
|
-
* @returns {
|
|
38
|
+
* @returns {{x: number[], fx: number, iterations: number, nfev: number, fevals: number, converged: boolean, success: boolean, history?: Array<{x: number[], fx: number, simplex: number[][]}>}}
|
|
39
|
+
* `fevals` is a deprecated alias of `nfev`; `success` equals `converged`
|
|
34
40
|
*/
|
|
35
41
|
export function nelderMead(f, x0, options = {}) {
|
|
36
42
|
const n = x0.length;
|
|
37
|
-
const maxIter = options.maxIter
|
|
38
|
-
const fTol = options.fTol
|
|
39
|
-
const xTol = options.xTol
|
|
40
|
-
const nonZeroDelta = options.nonZeroDelta
|
|
41
|
-
const zeroDelta = options.zeroDelta
|
|
43
|
+
const maxIter = options.maxIter ?? n * 200;
|
|
44
|
+
const fTol = options.fTol ?? options.tol ?? 1e-6;
|
|
45
|
+
const xTol = options.xTol ?? 1e-5;
|
|
46
|
+
const nonZeroDelta = options.nonZeroDelta ?? 1.05;
|
|
47
|
+
const zeroDelta = options.zeroDelta ?? 1e-3;
|
|
42
48
|
const rho = options.rho !== undefined ? options.rho : 1;
|
|
43
49
|
const chi = options.chi !== undefined ? options.chi : 2;
|
|
44
50
|
const psi = options.psi !== undefined ? options.psi : -0.5;
|
|
45
51
|
const sigma = options.sigma !== undefined ? options.sigma : 0.5;
|
|
46
|
-
const trackHistory = options.history
|
|
52
|
+
const trackHistory = options.history ?? false;
|
|
47
53
|
|
|
48
54
|
const evaluateScalar = makeScalarEvaluator(f);
|
|
49
55
|
let fevals = 0;
|
package/src/numdiff.js
CHANGED
|
@@ -1,15 +1,17 @@
|
|
|
1
|
-
|
|
1
|
+
/*
|
|
2
2
|
* Numerical differentiation utilities
|
|
3
3
|
*/
|
|
4
4
|
|
|
5
5
|
/**
|
|
6
6
|
* Approximate the gradient of a scalar function by central finite differences.
|
|
7
7
|
*
|
|
8
|
-
* @param {
|
|
9
|
-
* @param {
|
|
8
|
+
* @param {(x: number[]) => number} f - Scalar function
|
|
9
|
+
* @param {number[]} x - Point at which to evaluate the gradient
|
|
10
10
|
* @param {Object} [options]
|
|
11
|
-
* @param {number} [options.h=1e-6] -
|
|
12
|
-
* @returns {
|
|
11
|
+
* @param {number} [options.h=1e-6] - Absolute step size
|
|
12
|
+
* @returns {number[]} Gradient approximation
|
|
13
|
+
* @example
|
|
14
|
+
* numericalGradient(([a, b]) => a * a + 3 * b, [1, 2]); // ≈ [2, 3]
|
|
13
15
|
*/
|
|
14
16
|
export function numericalGradient(f, x, options = {}) {
|
|
15
17
|
const h = options.h || 1e-6;
|
|
@@ -30,14 +32,15 @@ export function numericalGradient(f, x, options = {}) {
|
|
|
30
32
|
}
|
|
31
33
|
|
|
32
34
|
/**
|
|
33
|
-
*
|
|
35
|
+
* Approximate the Jacobian of a vector-valued function by central finite differences.
|
|
36
|
+
*
|
|
34
37
|
* Per-component step h_j = step * max(1, |x_j|).
|
|
35
38
|
*
|
|
36
|
-
* @param {
|
|
37
|
-
* @param {
|
|
39
|
+
* @param {(x: number[]) => ArrayLike<number>} f - Function returning m values
|
|
40
|
+
* @param {number[]} x - Point of length n
|
|
38
41
|
* @param {Object} [options]
|
|
39
42
|
* @param {number} [options.step=1e-6] - Relative step size
|
|
40
|
-
* @returns {
|
|
43
|
+
* @returns {number[][]} m-by-n Jacobian, `J[i][j] = d f_i / d x_j`
|
|
41
44
|
*/
|
|
42
45
|
export function numericalJacobian(f, x, options = {}) {
|
|
43
46
|
const step = options.step || 1e-6;
|
|
@@ -67,13 +70,15 @@ export function numericalJacobian(f, x, options = {}) {
|
|
|
67
70
|
}
|
|
68
71
|
|
|
69
72
|
/**
|
|
70
|
-
*
|
|
73
|
+
* Approximate the Hessian of a scalar function by central finite differences.
|
|
74
|
+
*
|
|
75
|
+
* Per-component step h_j = step * max(1, |x_j|).
|
|
71
76
|
*
|
|
72
|
-
* @param {
|
|
73
|
-
* @param {
|
|
77
|
+
* @param {(x: number[]) => number} f - Scalar function
|
|
78
|
+
* @param {number[]} x - Point of length n
|
|
74
79
|
* @param {Object} [options]
|
|
75
80
|
* @param {number} [options.step=1e-4] - Relative step size
|
|
76
|
-
* @returns {
|
|
81
|
+
* @returns {number[][]} n-by-n symmetric Hessian
|
|
77
82
|
*/
|
|
78
83
|
export function numericalHessian(f, x, options = {}) {
|
|
79
84
|
const h = options.step || 1e-4;
|
package/src/scalar.js
CHANGED
|
@@ -324,14 +324,19 @@ function goldenMinimize(fn, xa, xb, xc, fxb, xTol, maxIter) {
|
|
|
324
324
|
/**
|
|
325
325
|
* Minimize a univariate function.
|
|
326
326
|
*
|
|
327
|
-
* @param {
|
|
327
|
+
* @param {(x: number) => number} f - Objective
|
|
328
328
|
* @param {Object} [options]
|
|
329
|
-
* @param {
|
|
330
|
-
*
|
|
331
|
-
*
|
|
329
|
+
* @param {'brent'|'golden'} [options.method='brent'] - Brent's method or
|
|
330
|
+
* golden-section search; case-insensitive
|
|
331
|
+
* @param {number[]} [options.bracket=[0, 1]] - [a, b] to auto-bracket
|
|
332
|
+
* from (downhill), or a full bracketing triple [a, b, c] with f(b) <= f(a), f(b) <= f(c)
|
|
332
333
|
* @param {number} [options.xTol=1e-8] - Relative tolerance on x
|
|
333
334
|
* @param {number} [options.maxIter=500] - Maximum iterations
|
|
334
|
-
* @returns {
|
|
335
|
+
* @returns {{x: number, fx: number, iterations: number, nfev: number, fevals: number, converged: boolean, success: boolean}}
|
|
336
|
+
* `fevals` is a deprecated alias of `nfev`; `success` equals `converged`
|
|
337
|
+
* @throws {Error} if no minimum can be bracketed (f monotonic or unbounded below)
|
|
338
|
+
* @example
|
|
339
|
+
* minimizeScalar(Math.cos, { bracket: [2, 4] }).x; // 3.14159265441603
|
|
335
340
|
*/
|
|
336
341
|
export function minimizeScalar(f, options = {}) {
|
|
337
342
|
if (typeof f !== 'function') {
|
|
@@ -552,15 +557,20 @@ function bisectRoot(fn, a0, b0, fa0, xTol, rTol, maxIter) {
|
|
|
552
557
|
/**
|
|
553
558
|
* Find a root of a univariate function inside a sign-changing bracket.
|
|
554
559
|
*
|
|
555
|
-
* @param {
|
|
556
|
-
* @param {Object}
|
|
557
|
-
* @param {
|
|
558
|
-
*
|
|
559
|
-
*
|
|
560
|
+
* @param {(x: number) => number} f - Function
|
|
561
|
+
* @param {Object} options
|
|
562
|
+
* @param {number[]} options.bracket - [a, b] with f(a) and f(b) of opposite
|
|
563
|
+
* signs (required)
|
|
564
|
+
* @param {'brent'|'bisect'} [options.method='brent'] - Brent-Dekker or
|
|
565
|
+
* bisection; case-insensitive
|
|
560
566
|
* @param {number} [options.xTol=1e-12] - Absolute tolerance on x
|
|
561
567
|
* @param {number} [options.rTol=4 * Number.EPSILON] - Relative tolerance on x
|
|
562
568
|
* @param {number} [options.maxIter=100] - Maximum iterations
|
|
563
|
-
* @returns {
|
|
569
|
+
* @returns {{x: number, fx: number, iterations: number, nfev: number, fevals: number, converged: boolean, success: boolean}}
|
|
570
|
+
* `fevals` is a deprecated alias of `nfev`; `success` equals `converged`
|
|
571
|
+
* @throws {Error} if f(a) and f(b) have the same sign, or f is not finite
|
|
572
|
+
* @example
|
|
573
|
+
* rootScalar(Math.cos, { bracket: [1, 2] }).x; // 1.5707963267948966
|
|
564
574
|
*/
|
|
565
575
|
export function rootScalar(f, options = {}) {
|
|
566
576
|
if (typeof f !== 'function') {
|
package/src/steps.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
|
|
1
|
+
/*
|
|
2
2
|
* Update rules, one step at a time.
|
|
3
3
|
*
|
|
4
4
|
* The drivers in gradient.js run a whole minimization: they own the loop,
|
|
@@ -19,16 +19,17 @@
|
|
|
19
19
|
* state per tensor.
|
|
20
20
|
*/
|
|
21
21
|
|
|
22
|
-
/** @typedef {{ learningRate?: number }} StepOptions */
|
|
23
|
-
|
|
24
22
|
/**
|
|
25
|
-
*
|
|
26
|
-
*
|
|
23
|
+
* Take one plain gradient-descent step in place: `x -= lr · g`.
|
|
24
|
+
*
|
|
25
|
+
* Stateless; returns `null` so it has the signature of the other steps,
|
|
26
|
+
* `state = step(x, gradient, state, options)`.
|
|
27
27
|
*
|
|
28
28
|
* @param {number[]|Float64Array} x - moved in place
|
|
29
|
-
* @param {number
|
|
30
|
-
* @param {null} [_state]
|
|
31
|
-
* @param {
|
|
29
|
+
* @param {ArrayLike<number>} gradient - same length as x
|
|
30
|
+
* @param {null} [_state] - unused
|
|
31
|
+
* @param {Object} [options] - read on every call
|
|
32
|
+
* @param {number} [options.learningRate=0.01] - Step size
|
|
32
33
|
* @returns {null}
|
|
33
34
|
*/
|
|
34
35
|
export function gradientStep(x, gradient, _state = null, options = {}) {
|
|
@@ -38,13 +39,16 @@ export function gradientStep(x, gradient, _state = null, options = {}) {
|
|
|
38
39
|
}
|
|
39
40
|
|
|
40
41
|
/**
|
|
41
|
-
*
|
|
42
|
+
* Take one gradient-descent-with-momentum step in place: `v = μ v + lr · g; x -= v`.
|
|
42
43
|
*
|
|
43
44
|
* @param {number[]|Float64Array} x - moved in place
|
|
44
|
-
* @param {number
|
|
45
|
-
* @param {{ velocity: Float64Array }|null} [state]
|
|
46
|
-
*
|
|
47
|
-
* @
|
|
45
|
+
* @param {ArrayLike<number>} gradient - same length as x
|
|
46
|
+
* @param {{ velocity: Float64Array }|null} [state] - from the previous call;
|
|
47
|
+
* null to start
|
|
48
|
+
* @param {Object} [options] - read on every call
|
|
49
|
+
* @param {number} [options.learningRate=0.01] - Step size
|
|
50
|
+
* @param {number} [options.momentum=0.9] - μ
|
|
51
|
+
* @returns {{ velocity: Float64Array }} the state, to pass to the next call
|
|
48
52
|
*/
|
|
49
53
|
export function momentumStep(x, gradient, state = null, options = {}) {
|
|
50
54
|
const lr = options.learningRate ?? 0.01;
|
|
@@ -59,13 +63,17 @@ export function momentumStep(x, gradient, state = null, options = {}) {
|
|
|
59
63
|
}
|
|
60
64
|
|
|
61
65
|
/**
|
|
62
|
-
* RMSProp: a running mean of squared gradients scales each coordinate's step.
|
|
66
|
+
* Take one RMSProp step in place: a running mean of squared gradients scales each coordinate's step.
|
|
63
67
|
*
|
|
64
68
|
* @param {number[]|Float64Array} x - moved in place
|
|
65
|
-
* @param {number
|
|
66
|
-
* @param {{ cache: Float64Array }|null} [state]
|
|
67
|
-
*
|
|
68
|
-
* @
|
|
69
|
+
* @param {ArrayLike<number>} gradient - same length as x
|
|
70
|
+
* @param {{ cache: Float64Array }|null} [state] - from the previous call;
|
|
71
|
+
* null to start
|
|
72
|
+
* @param {Object} [options] - read on every call
|
|
73
|
+
* @param {number} [options.learningRate=0.01] - Step size
|
|
74
|
+
* @param {number} [options.decay=0.9] - Decay of the running mean
|
|
75
|
+
* @param {number} [options.epsilon=1e-8] - Added to the denominator
|
|
76
|
+
* @returns {{ cache: Float64Array }} the state, to pass to the next call
|
|
69
77
|
*/
|
|
70
78
|
export function rmspropStep(x, gradient, state = null, options = {}) {
|
|
71
79
|
const lr = options.learningRate ?? 0.01;
|
|
@@ -82,15 +90,29 @@ export function rmspropStep(x, gradient, state = null, options = {}) {
|
|
|
82
90
|
}
|
|
83
91
|
|
|
84
92
|
/**
|
|
85
|
-
* Adam (Kingma and Ba, 2015): bias-corrected first and second moments.
|
|
86
|
-
*
|
|
87
|
-
*
|
|
93
|
+
* Take one Adam step in place (Kingma and Ba, 2015): bias-corrected first and second moments.
|
|
94
|
+
*
|
|
95
|
+
* Keep one state per parameter tensor. The step count lives in the state, so
|
|
96
|
+
* bias correction is right however many tensors share one options object.
|
|
88
97
|
*
|
|
89
98
|
* @param {number[]|Float64Array} x - moved in place
|
|
90
|
-
* @param {number
|
|
91
|
-
* @param {{ m: Float64Array, v: Float64Array, t: number }|null} [state]
|
|
92
|
-
*
|
|
93
|
-
* @
|
|
99
|
+
* @param {ArrayLike<number>} gradient - same length as x
|
|
100
|
+
* @param {{ m: Float64Array, v: Float64Array, t: number }|null} [state] - from
|
|
101
|
+
* the previous call; null to start
|
|
102
|
+
* @param {Object} [options] - read on every call
|
|
103
|
+
* @param {number} [options.learningRate=0.01] - Step size
|
|
104
|
+
* @param {number} [options.beta1=0.9] - First-moment decay
|
|
105
|
+
* @param {number} [options.beta2=0.999] - Second-moment decay
|
|
106
|
+
* @param {number} [options.epsilon=1e-8] - Added to the denominator
|
|
107
|
+
* @returns {{ m: Float64Array, v: Float64Array, t: number }} the state, to
|
|
108
|
+
* pass to the next call
|
|
109
|
+
* @example
|
|
110
|
+
* const x = [3, -2];
|
|
111
|
+
* let state = null;
|
|
112
|
+
* for (let i = 0; i < 500; i++) {
|
|
113
|
+
* state = adamStep(x, [2 * x[0], 2 * x[1]], state, { learningRate: 0.1 });
|
|
114
|
+
* }
|
|
115
|
+
* // x ≈ [0, 0]
|
|
94
116
|
*/
|
|
95
117
|
export function adamStep(x, gradient, state = null, options = {}) {
|
|
96
118
|
const lr = options.learningRate ?? 0.01;
|