@tangent.to/opt 0.2.0 → 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 +18 -8
- 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 +53 -12
- 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/gradient.js
CHANGED
|
@@ -21,11 +21,15 @@ function gradNorm(gradient) {
|
|
|
21
21
|
}
|
|
22
22
|
|
|
23
23
|
/**
|
|
24
|
-
*
|
|
24
|
+
* Find a step size along the negative gradient by backtracking until the Armijo condition holds.
|
|
25
25
|
*
|
|
26
|
-
*
|
|
27
|
-
*
|
|
28
|
-
*
|
|
26
|
+
* Starts at step 1 and multiplies it by 0.8 until
|
|
27
|
+
* `f(x - t * g) <= f(x) - 0.3 * t * |g|^2`, trying 20 steps; returns 0.8^20
|
|
28
|
+
* if none passes.
|
|
29
|
+
*
|
|
30
|
+
* @param {(x: number[]) => {loss: number}} evaluate - Objective, as `{loss}`
|
|
31
|
+
* @param {number[]} x - Current point
|
|
32
|
+
* @param {ArrayLike<number>} gradient - Gradient at x
|
|
29
33
|
* @param {number} currentLoss - Loss at x
|
|
30
34
|
* @returns {number} Step size
|
|
31
35
|
*/
|
|
@@ -64,11 +68,11 @@ export function backtrackingLineSearch(evaluate, x, gradient, currentLoss) {
|
|
|
64
68
|
* @returns {Object} {x, fx, iterations, converged, history}
|
|
65
69
|
*/
|
|
66
70
|
function descend(spec, f, x0, options = {}) {
|
|
67
|
-
const learningRate = options.learningRate
|
|
68
|
-
const maxIter = options.maxIter
|
|
69
|
-
const tol = options.tol
|
|
70
|
-
const verbose = options.verbose
|
|
71
|
-
const lineSearch = options.lineSearch
|
|
71
|
+
const learningRate = options.learningRate ?? 0.01;
|
|
72
|
+
const maxIter = options.maxIter ?? 1000;
|
|
73
|
+
const tol = options.tol ?? 1e-6;
|
|
74
|
+
const verbose = options.verbose ?? false;
|
|
75
|
+
const lineSearch = options.lineSearch ?? false;
|
|
72
76
|
|
|
73
77
|
const evaluateRaw = makeEvaluator(f, options.grad, options);
|
|
74
78
|
let nfev = 0;
|
|
@@ -126,12 +130,24 @@ function descend(spec, f, x0, options = {}) {
|
|
|
126
130
|
}
|
|
127
131
|
|
|
128
132
|
/**
|
|
129
|
-
*
|
|
133
|
+
* Minimize a function by plain gradient descent, with optional backtracking line search.
|
|
130
134
|
*
|
|
131
|
-
* @param {
|
|
132
|
-
*
|
|
133
|
-
*
|
|
134
|
-
* @
|
|
135
|
+
* @param {(x: number[]) => number | {loss: number, gradient: number[]|Float64Array} | {value: number, gradient: number[]|Float64Array}} f
|
|
136
|
+
* - Objective: a number, or with its gradient as `{loss, gradient}` or
|
|
137
|
+
* `{value, gradient}`
|
|
138
|
+
* @param {number[]} x0 - Initial parameters
|
|
139
|
+
* @param {Object} [options]
|
|
140
|
+
* @param {(x: number[]) => number[]} [options.grad] - Gradient when `f` returns
|
|
141
|
+
* a number; central differences otherwise
|
|
142
|
+
* @param {number} [options.learningRate=0.01] - Step size
|
|
143
|
+
* @param {number} [options.maxIter=1000] - Maximum iterations
|
|
144
|
+
* @param {number} [options.tol=1e-6] - Convergence tolerance on the gradient norm
|
|
145
|
+
* @param {boolean} [options.lineSearch=false] - Backtracking (Armijo) line search
|
|
146
|
+
* in place of the fixed learning rate
|
|
147
|
+
* @param {number} [options.h=1e-6] - Finite-difference step, without a gradient
|
|
148
|
+
* @param {boolean} [options.verbose=false] - Log progress every 100 iterations
|
|
149
|
+
* @returns {{x: number[], fx: number, iterations: number, nfev: number, converged: boolean, success: boolean, history: {loss: number[], gradNorm: number[], learningRate: number[]}}}
|
|
150
|
+
* `history.learningRate` holds the step size used at each iteration
|
|
135
151
|
*/
|
|
136
152
|
export function gradientDescent(f, x0, options = {}) {
|
|
137
153
|
return descend(
|
|
@@ -146,15 +162,25 @@ export function gradientDescent(f, x0, options = {}) {
|
|
|
146
162
|
}
|
|
147
163
|
|
|
148
164
|
/**
|
|
149
|
-
*
|
|
165
|
+
* Minimize a function by gradient descent with momentum.
|
|
150
166
|
*
|
|
151
|
-
* @param {
|
|
152
|
-
*
|
|
153
|
-
*
|
|
154
|
-
* @
|
|
167
|
+
* @param {(x: number[]) => number | {loss: number, gradient: number[]|Float64Array} | {value: number, gradient: number[]|Float64Array}} f
|
|
168
|
+
* - Objective: a number, or with its gradient as `{loss, gradient}` or
|
|
169
|
+
* `{value, gradient}`
|
|
170
|
+
* @param {number[]} x0 - Initial parameters
|
|
171
|
+
* @param {Object} [options]
|
|
172
|
+
* @param {(x: number[]) => number[]} [options.grad] - Gradient when `f` returns
|
|
173
|
+
* a number; central differences otherwise
|
|
174
|
+
* @param {number} [options.learningRate=0.01] - Step size
|
|
175
|
+
* @param {number} [options.maxIter=1000] - Maximum iterations
|
|
176
|
+
* @param {number} [options.tol=1e-6] - Convergence tolerance on the gradient norm
|
|
177
|
+
* @param {number} [options.momentum=0.9] - Momentum coefficient
|
|
178
|
+
* @param {number} [options.h=1e-6] - Finite-difference step, without a gradient
|
|
179
|
+
* @param {boolean} [options.verbose=false] - Log progress every 100 iterations
|
|
180
|
+
* @returns {{x: number[], fx: number, iterations: number, nfev: number, converged: boolean, success: boolean, history: {loss: number[], gradNorm: number[]}}}
|
|
155
181
|
*/
|
|
156
182
|
export function momentumDescent(f, x0, options = {}) {
|
|
157
|
-
const momentum = options.momentum
|
|
183
|
+
const momentum = options.momentum ?? 0.9;
|
|
158
184
|
return descend(
|
|
159
185
|
{
|
|
160
186
|
step: (x, gradient, state, lr) =>
|
|
@@ -167,16 +193,27 @@ export function momentumDescent(f, x0, options = {}) {
|
|
|
167
193
|
}
|
|
168
194
|
|
|
169
195
|
/**
|
|
170
|
-
* RMSProp.
|
|
196
|
+
* Minimize a function with RMSProp.
|
|
171
197
|
*
|
|
172
|
-
* @param {
|
|
173
|
-
*
|
|
174
|
-
*
|
|
175
|
-
* @
|
|
198
|
+
* @param {(x: number[]) => number | {loss: number, gradient: number[]|Float64Array} | {value: number, gradient: number[]|Float64Array}} f
|
|
199
|
+
* - Objective: a number, or with its gradient as `{loss, gradient}` or
|
|
200
|
+
* `{value, gradient}`
|
|
201
|
+
* @param {number[]} x0 - Initial parameters
|
|
202
|
+
* @param {Object} [options]
|
|
203
|
+
* @param {(x: number[]) => number[]} [options.grad] - Gradient when `f` returns
|
|
204
|
+
* a number; central differences otherwise
|
|
205
|
+
* @param {number} [options.learningRate=0.01] - Step size
|
|
206
|
+
* @param {number} [options.maxIter=1000] - Maximum iterations
|
|
207
|
+
* @param {number} [options.tol=1e-6] - Convergence tolerance on the gradient norm
|
|
208
|
+
* @param {number} [options.decay=0.9] - Decay of the running mean of squared gradients
|
|
209
|
+
* @param {number} [options.epsilon=1e-8] - Added to the denominator
|
|
210
|
+
* @param {number} [options.h=1e-6] - Finite-difference step, without a gradient
|
|
211
|
+
* @param {boolean} [options.verbose=false] - Log progress every 100 iterations
|
|
212
|
+
* @returns {{x: number[], fx: number, iterations: number, nfev: number, converged: boolean, success: boolean, history: {loss: number[], gradNorm: number[]}}}
|
|
176
213
|
*/
|
|
177
214
|
export function rmsprop(f, x0, options = {}) {
|
|
178
|
-
const decay = options.decay
|
|
179
|
-
const epsilon = options.epsilon
|
|
215
|
+
const decay = options.decay ?? 0.9;
|
|
216
|
+
const epsilon = options.epsilon ?? 1e-8;
|
|
180
217
|
return descend(
|
|
181
218
|
{
|
|
182
219
|
step: (x, gradient, state, lr) =>
|
|
@@ -189,17 +226,29 @@ export function rmsprop(f, x0, options = {}) {
|
|
|
189
226
|
}
|
|
190
227
|
|
|
191
228
|
/**
|
|
192
|
-
* Adam (adaptive moment estimation).
|
|
229
|
+
* Minimize a function with Adam (adaptive moment estimation).
|
|
193
230
|
*
|
|
194
|
-
* @param {
|
|
195
|
-
*
|
|
196
|
-
*
|
|
197
|
-
* @
|
|
231
|
+
* @param {(x: number[]) => number | {loss: number, gradient: number[]|Float64Array} | {value: number, gradient: number[]|Float64Array}} f
|
|
232
|
+
* - Objective: a number, or with its gradient as `{loss, gradient}` or
|
|
233
|
+
* `{value, gradient}`
|
|
234
|
+
* @param {number[]} x0 - Initial parameters
|
|
235
|
+
* @param {Object} [options]
|
|
236
|
+
* @param {(x: number[]) => number[]} [options.grad] - Gradient when `f` returns
|
|
237
|
+
* a number; central differences otherwise
|
|
238
|
+
* @param {number} [options.learningRate=0.01] - Step size
|
|
239
|
+
* @param {number} [options.maxIter=1000] - Maximum iterations
|
|
240
|
+
* @param {number} [options.tol=1e-6] - Convergence tolerance on the gradient norm
|
|
241
|
+
* @param {number} [options.beta1=0.9] - First-moment decay
|
|
242
|
+
* @param {number} [options.beta2=0.999] - Second-moment decay
|
|
243
|
+
* @param {number} [options.epsilon=1e-8] - Added to the denominator
|
|
244
|
+
* @param {number} [options.h=1e-6] - Finite-difference step, without a gradient
|
|
245
|
+
* @param {boolean} [options.verbose=false] - Log progress every 100 iterations
|
|
246
|
+
* @returns {{x: number[], fx: number, iterations: number, nfev: number, converged: boolean, success: boolean, history: {loss: number[], gradNorm: number[]}}}
|
|
198
247
|
*/
|
|
199
248
|
export function adam(f, x0, options = {}) {
|
|
200
|
-
const beta1 = options.beta1
|
|
201
|
-
const beta2 = options.beta2
|
|
202
|
-
const epsilon = options.epsilon
|
|
249
|
+
const beta1 = options.beta1 ?? 0.9;
|
|
250
|
+
const beta2 = options.beta2 ?? 0.999;
|
|
251
|
+
const epsilon = options.epsilon ?? 1e-8;
|
|
203
252
|
return descend(
|
|
204
253
|
{
|
|
205
254
|
step: (x, gradient, state, lr) =>
|
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
|
@@ -11,9 +11,8 @@
|
|
|
11
11
|
* });
|
|
12
12
|
* // result: {x, fx, iterations, converged, method, ...}
|
|
13
13
|
*
|
|
14
|
-
* Gradient-based methods use
|
|
15
|
-
*
|
|
16
|
-
* differences otherwise.
|
|
14
|
+
* Gradient-based methods use a gradient returned by the objective or a
|
|
15
|
+
* separate `grad` callback, with central finite differences as the fallback.
|
|
17
16
|
*/
|
|
18
17
|
|
|
19
18
|
import { nelderMead } from './neldermead.js';
|
|
@@ -42,8 +41,8 @@ const METHODS = {
|
|
|
42
41
|
};
|
|
43
42
|
|
|
44
43
|
/**
|
|
45
|
-
* List the
|
|
46
|
-
* @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']`
|
|
47
46
|
*/
|
|
48
47
|
export function methods() {
|
|
49
48
|
return Object.keys(METHODS);
|
|
@@ -52,14 +51,56 @@ export function methods() {
|
|
|
52
51
|
/**
|
|
53
52
|
* Minimize a scalar function of one or more variables.
|
|
54
53
|
*
|
|
54
|
+
* The other keys of `spec` go to the method; each method's defaults are on
|
|
55
|
+
* `nelderMead`, `lbfgs`, `gradientDescent` and `adam`.
|
|
56
|
+
*
|
|
55
57
|
* @param {Object} spec
|
|
56
|
-
* @param {
|
|
57
|
-
*
|
|
58
|
-
*
|
|
59
|
-
* @param {
|
|
60
|
-
* @param {
|
|
61
|
-
*
|
|
62
|
-
* @
|
|
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
|
|
63
104
|
*/
|
|
64
105
|
export function minimize(spec = {}) {
|
|
65
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;
|