@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/llms.txt ADDED
@@ -0,0 +1,183 @@
1
+ # @tangent.to/opt 0.2.2
2
+
3
+ > Numerical optimization for JavaScript (ESM): L-BFGS, Nelder-Mead, gradient descent and Adam with box bounds; scalar minimization and root-finding; least squares and curve fitting
4
+
5
+ Numerical optimization for JavaScript (ESM): minimization in one or many
6
+ variables, scalar root-finding and nonlinear least squares. Zero
7
+ dependencies; runs in browsers, Node.js and Deno.
8
+
9
+ - **Multivariate**: L-BFGS with strong Wolfe line search (the default for
10
+ smooth problems), Nelder-Mead (derivative-free), gradient descent (optional
11
+ backtracking line search) and Adam
12
+ - **Scalar**: Brent and golden-section minimization with auto-bracketing;
13
+ Brent and bisection root-finding
14
+ - **Least squares**: Levenberg-Marquardt, and `curveFit` with covariance and
15
+ standard errors; robust losses `huber`, `soft_l1`, `cauchy`
16
+ - **Box bounds** for `minimize`, `leastSquares` and `curveFit`
17
+ (`bounds: [[0, 10], [null, 5]]`), by MINUIT-style parameter transforms
18
+
19
+ ## Install
20
+
21
+ ```bash
22
+ npm install @tangent.to/opt # npm
23
+ deno add jsr:@tangent/opt # Deno / JSR
24
+ ```
25
+
26
+ Types ship with the package. In a notebook, `await help('minimize')` returns
27
+ an export's documentation; `llms-full.txt` in the package holds all of it.
28
+
29
+ ## Usage
30
+
31
+ ```javascript
32
+ import { minimize } from '@tangent.to/opt';
33
+
34
+ // Derivative-free (default method: Nelder-Mead)
35
+ const result = minimize({
36
+ f: ([a, b]) => (1 - a) ** 2 + 100 * (b - a * a) ** 2,
37
+ x0: [-1.2, 1],
38
+ });
39
+ // { x: ≈ [1, 1], fx: 5.4e-11, iterations: 89, fevals: 168, converged: true, method: 'neldermead', ... }
40
+
41
+ // L-BFGS: use this for smooth objectives
42
+ const fit = minimize({
43
+ f: (x) => x[0] ** 2 + x[1] ** 2,
44
+ grad: (x) => [2 * x[0], 2 * x[1]], // optional; finite differences otherwise
45
+ x0: [3, -2],
46
+ method: 'lbfgs',
47
+ });
48
+ // fit.x: [0, 0]
49
+ ```
50
+
51
+ Methods for `minimize`: `'neldermead'`, `'lbfgs'`, `'gd'`, `'adam'` (aliases
52
+ in `methods()`). Other keys of the spec (`maxIter`, `tol`, `learningRate`,
53
+ `history`, ...) are passed to the method.
54
+
55
+ Scalar optimization, root-finding and curve fitting:
56
+
57
+ ```javascript
58
+ import { curveFit, minimizeScalar, rootScalar } from '@tangent.to/opt';
59
+
60
+ minimizeScalar(Math.cos, { bracket: [2, 4] }).x; // 3.14159265441603
61
+ rootScalar(Math.cos, { bracket: [1, 2] }).x; // 1.5707963267948966
62
+
63
+ const { params, stdErr } = curveFit({
64
+ model: (t, [a, b, c]) => a * Math.exp(-b * t) + c,
65
+ x: [0, 0.5, 1, 1.5, 2, 2.5, 3, 3.5, 4],
66
+ y: [3.02, 1.80, 1.17, 0.85, 0.66, 0.59, 0.55, 0.52, 0.51],
67
+ p0: [1, 1, 0],
68
+ bounds: [[0, null], [0, null], [null, null]], // optional
69
+ });
70
+ // params ≈ [2.524, 1.322, 0.496], stdErr ≈ [0.0078, 0.0100, 0.0043]
71
+ ```
72
+
73
+ `curveFit` and `leastSquares` take `loss: 'huber' | 'soft_l1' | 'cauchy'`
74
+ with a residual scale `fScale`. With a robust loss, `cov` and `stdErr` are
75
+ `NaN`: the Gaussian covariance formula does not apply.
76
+
77
+ ### Objectives
78
+
79
+ An objective returns a number, `{ loss, gradient }` or `{ value, gradient }`.
80
+ The last is what `@tangent.to/grad`'s `valueAndGrad` and `compile` return,
81
+ so either can be passed to `lbfgs` or `adam` as it is. Without a returned
82
+ gradient or a `grad` option, gradient methods use central finite
83
+ differences.
84
+
85
+ ### One step at a time
86
+
87
+ For a training loop that samples its own mini-batches, each update rule is
88
+ also a step function. It moves `x` in place (an array or `Float64Array`),
89
+ keeps its moments in a state created on the first call, and reads its options
90
+ on every call, so a learning-rate schedule is a number changed between steps.
91
+
92
+ ```javascript
93
+ import { adamStep } from '@tangent.to/opt';
94
+
95
+ const params = [3, -2];
96
+ const opts = { learningRate: 0.1 };
97
+ let state = null;
98
+ for (let i = 0; i < 500; i++) {
99
+ const gradient = [2 * params[0], 2 * params[1]]; // from a mini-batch, in practice
100
+ state = adamStep(params, gradient, state, opts);
101
+ }
102
+ // params ≈ [0, 0]
103
+ ```
104
+
105
+ `gradientStep`, `momentumStep`, `rmspropStep` and `adamStep` share this
106
+ signature. Keep one state per parameter tensor.
107
+
108
+ ### Result shape
109
+
110
+ Minimizers return `{ x, fx, iterations, converged, ... }`. `fevals` is
111
+ reported by Nelder-Mead, L-BFGS, the scalar methods and `leastSquares`;
112
+ `history` by L-BFGS and the gradient methods always, by Nelder-Mead and
113
+ `leastSquares` with `history: true`. `curveFit` returns
114
+ `{ params, cov, stdErr, fx, iterations, converged }`.
115
+
116
+ ## API
117
+
118
+ | export | purpose |
119
+ | --- | --- |
120
+ | `minimize(spec)`, `methods()` | multivariate minimization by method name |
121
+ | `nelderMead`, `lbfgs`, `gradientDescent`, `adam`, `momentumDescent`, `rmsprop` | the methods, as `(f, x0, options)` |
122
+ | `gradientStep`, `momentumStep`, `rmspropStep`, `adamStep` | single update steps |
123
+ | `minimizeScalar(f, options)`, `rootScalar(f, options)` | scalar minimization and root-finding |
124
+ | `leastSquares(spec)`, `curveFit(spec)` | nonlinear least squares |
125
+ | `numericalGradient`, `numericalJacobian`, `numericalHessian` | central finite differences |
126
+ | `strongWolfeLineSearch`, `backtrackingLineSearch`, `makeBoundsTransform`, `solve` | building blocks |
127
+ | `GradientDescent`, `MomentumOptimizer`, `RMSProp`, `AdamOptimizer`, `createOptimizer` | class interface used by `tangent/ds`: `minimize(lossFn, x0)` returns `{ x, history }` |
128
+
129
+ ## Validation
130
+
131
+ `npm run test:scipy` (needs [uv](https://docs.astral.sh/uv/) and Node)
132
+ checks each method against `scipy.optimize`: Nelder-Mead, L-BFGS against
133
+ `L-BFGS-B` (also with bounds), `minimizeScalar` against `minimize_scalar`,
134
+ `rootScalar` against `brentq`, `curveFit` parameters and standard errors
135
+ against `curve_fit`, robust losses against `least_squares`, gradient methods
136
+ against a BFGS optimum, and `numericalGradient` against `approx_fprime`.
137
+
138
+ ## Scope
139
+
140
+ General constrained optimization, LP/QP and global optimization are out of
141
+ scope.
142
+
143
+ ## License
144
+
145
+ MIT. The Nelder-Mead implementation is ported from
146
+ [fmin](https://github.com/benfred/fmin) (BSD-3-Clause); see
147
+ [THIRD_PARTY_NOTICES.md](./THIRD_PARTY_NOTICES.md).
148
+
149
+ ## Exports
150
+
151
+ - `nelderMead`: Minimize a function using the Nelder-Mead downhill simplex method.
152
+ - `lbfgs`: Minimize a function with L-BFGS.
153
+ - `strongWolfeLineSearch`: Find a step along direction p from x that satisfies the strong Wolfe conditions.
154
+ - `solve`: Solve the linear system A x = b by Gaussian elimination with scaled partial pivoting.
155
+ - `makeBoundsTransform`: Build the transform between bounded parameters and unbounded internal ones, or null when every parameter is free.
156
+ - `help`: This package's documentation, for where the README is out of reach, such as a notebook, and for coding assistants.
157
+ - `version`: This package's version.
158
+ - `methods`: List the method names `minimize` accepts, aliases included.
159
+ - `minimize`: Minimize a scalar function of one or more variables.
160
+ - `adam`: Minimize a function with Adam (adaptive moment estimation).
161
+ - `backtrackingLineSearch`: Find a step size along the negative gradient by backtracking until the Armijo condition holds.
162
+ - `gradientDescent`: Minimize a function by plain gradient descent, with optional backtracking line search.
163
+ - `momentumDescent`: Minimize a function by gradient descent with momentum.
164
+ - `rmsprop`: Minimize a function with RMSProp.
165
+ - `adamStep`: Take one Adam step in place (Kingma and Ba, 2015): bias-corrected first and second moments.
166
+ - `gradientStep`: Take one plain gradient-descent step in place: `x -= lr · g`.
167
+ - `momentumStep`: Take one gradient-descent-with-momentum step in place: `v = μ v + lr · g; x -= v`.
168
+ - `rmspropStep`: Take one RMSProp step in place: a running mean of squared gradients scales each coordinate's step.
169
+ - `minimizeScalar`: Minimize a univariate function.
170
+ - `rootScalar`: Find a root of a univariate function inside a sign-changing bracket.
171
+ - `curveFit`: Fit a model to (x, y) data by least squares, scipy.optimize.curve_fit style.
172
+ - `leastSquares`: Minimize a sum of squared residuals, 0.5 * sum(r(p)^2), with Levenberg-Marquardt.
173
+ - `numericalGradient`: Approximate the gradient of a scalar function by central finite differences.
174
+ - `numericalHessian`: Approximate the Hessian of a scalar function by central finite differences.
175
+ - `numericalJacobian`: Approximate the Jacobian of a vector-valued function by central finite differences.
176
+ - `AdamOptimizer`: Adam as a `tangent/ds`-style optimizer object: `minimize(lossFn, x0)` returns `{x, history}`.
177
+ - `createOptimizer`: Create a `tangent/ds`-style optimizer by name.
178
+ - `GradientDescent`: Batch gradient descent, with optional backtracking line search, as a `tangent/ds`-style optimizer object: `minimize(lossFn, x0)` returns `{x, history}`.
179
+ - `MomentumOptimizer`: Gradient descent with momentum as a `tangent/ds`-style optimizer object: `minimize(lossFn, x0)` returns `{x, history}`.
180
+ - `RMSProp`: RMSProp as a `tangent/ds`-style optimizer object: `minimize(lossFn, x0)` returns `{x, history}`.
181
+
182
+ Each export in full, with its types and options: https://cdn.jsdelivr.net/npm/@tangent.to/opt@0.2.2/llms-full.txt, or `await help('name')`
183
+ from the package itself.
package/package.json CHANGED
@@ -1,13 +1,15 @@
1
1
  {
2
2
  "name": "@tangent.to/opt",
3
- "version": "0.2.1",
4
- "description": "Declarative numerical optimization for JavaScript (ESM): Nelder-Mead, gradient descent, momentum, RMSProp, Adam",
3
+ "version": "0.2.2",
4
+ "description": "Numerical optimization for JavaScript (ESM): L-BFGS, Nelder-Mead, gradient descent and Adam with box bounds; scalar minimization and root-finding; least squares and curve fitting",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
7
7
  "module": "./dist/index.js",
8
8
  "browser": "./dist/index.js",
9
+ "types": "./types/index.d.ts",
9
10
  "exports": {
10
11
  ".": {
12
+ "types": "./types/index.d.ts",
11
13
  "import": "./dist/index.js",
12
14
  "default": "./dist/index.js"
13
15
  }
@@ -17,10 +19,13 @@
17
19
  "dist",
18
20
  "README.md",
19
21
  "LICENSE",
20
- "THIRD_PARTY_NOTICES.md"
22
+ "THIRD_PARTY_NOTICES.md",
23
+ "types",
24
+ "llms.txt",
25
+ "llms-full.txt"
21
26
  ],
22
27
  "scripts": {
23
- "prepare": "npm run build:browser",
28
+ "prepare": "npm run build:browser && npm run build:docs",
24
29
  "test": "vitest",
25
30
  "test:run": "vitest run",
26
31
  "test:coverage": "vitest --coverage",
@@ -32,7 +37,8 @@
32
37
  "deno:lint": "deno lint src/",
33
38
  "deno:fmt": "deno fmt src/",
34
39
  "deno:check": "deno check src/index.js",
35
- "version": "node scripts/sync-version.mjs && git add deno.json"
40
+ "version": "node scripts/sync-version.mjs && git add deno.json src/version.js",
41
+ "build:docs": "node scripts/docs.mjs"
36
42
  },
37
43
  "keywords": [
38
44
  "optimization",
@@ -56,6 +62,7 @@
56
62
  },
57
63
  "devDependencies": {
58
64
  "esbuild": "^0.25.11",
65
+ "typescript": "^6.0.3",
59
66
  "vitest": "^1.6.0"
60
67
  }
61
68
  }
package/src/bounds.js CHANGED
@@ -23,12 +23,20 @@ const UPPER = 2;
23
23
  const BOTH = 3;
24
24
 
25
25
  /**
26
- * Build a bounds transform, or return null when every parameter is free.
26
+ * Build the transform between bounded parameters and unbounded internal ones, or null when every parameter is free.
27
27
  *
28
- * @param {Array<Array<number|null>>} bounds - Per-parameter [lo, hi];
29
- * null/undefined/±Infinity mean unbounded on that side
28
+ * Both bounds: `ext = lo + (hi - lo) * (sin(int) + 1) / 2`; lower only:
29
+ * `ext = lo - 1 + sqrt(int^2 + 1)`; upper only: `ext = hi + 1 - sqrt(int^2 + 1)`.
30
+ * This is MINUIT's transform; `minimize`, `leastSquares` and `curveFit` use
31
+ * it for their `bounds`.
32
+ *
33
+ * @param {Array<[number|null|undefined, number|null|undefined]|null|undefined>} bounds - Per-parameter
34
+ * [lo, hi]; null/undefined/±Infinity mean unbounded on that side
30
35
  * @param {number} n - Number of parameters
31
- * @returns {Object|null} {toInternal, toExternal, dExtDInt, clamp}
36
+ * @returns {{toInternal: (xExt: number[]) => number[], toExternal: (xInt: number[]) => number[], dExtDInt: (xInt: number[]) => number[], clamp: (xExt: number[]) => number[]}|null}
37
+ * `toInternal` first clamps a point on or past a bound to just inside it;
38
+ * `dExtDInt` is d ext_i / d int_i at an internal point
39
+ * @throws {Error} if `bounds.length !== n` or a lower bound is not below its upper
32
40
  */
33
41
  export function makeBoundsTransform(bounds, n) {
34
42
  if (!Array.isArray(bounds) || bounds.length !== n) {
package/src/compat.js CHANGED
@@ -13,11 +13,18 @@
13
13
  import { adam, gradientDescent, momentumDescent, rmsprop } from './gradient.js';
14
14
 
15
15
  class Optimizer {
16
+ /**
17
+ * @param {Object} [options]
18
+ * @param {number} [options.learningRate=0.01] - Step size
19
+ * @param {number} [options.maxIter=1000] - Maximum iterations
20
+ * @param {number} [options.tol=1e-6] - Convergence tolerance on the gradient norm
21
+ * @param {boolean} [options.verbose=false] - Log progress every 100 iterations
22
+ */
16
23
  constructor(options = {}) {
17
- this.learningRate = options.learningRate || 0.01;
18
- this.maxIter = options.maxIter || 1000;
19
- this.tol = options.tol || 1e-6;
20
- this.verbose = options.verbose || false;
24
+ this.learningRate = options.learningRate ?? 0.01;
25
+ this.maxIter = options.maxIter ?? 1000;
26
+ this.tol = options.tol ?? 1e-6;
27
+ this.verbose = options.verbose ?? false;
21
28
  }
22
29
 
23
30
  /**
@@ -34,24 +41,46 @@ class Optimizer {
34
41
  _options(options) {
35
42
  return {
36
43
  learningRate: this.learningRate,
37
- maxIter: options.maxIter || this.maxIter,
38
- tol: options.tol || this.tol,
44
+ maxIter: options.maxIter ?? this.maxIter,
45
+ tol: options.tol ?? this.tol,
39
46
  verbose: this.verbose,
40
47
  };
41
48
  }
42
49
  }
43
50
 
44
51
  /**
45
- * Gradient Descent (batch; optional backtracking line search)
52
+ * Batch gradient descent, with optional backtracking line search, as a `tangent/ds`-style optimizer object: `minimize(lossFn, x0)` returns `{x, history}`.
53
+ *
54
+ * New code can call `gradientDescent` or `minimize` directly.
46
55
  */
47
56
  export class GradientDescent extends Optimizer {
57
+ /**
58
+ * @param {Object} [options]
59
+ * @param {number} [options.learningRate=0.01] - Step size
60
+ * @param {number} [options.maxIter=1000] - Maximum iterations
61
+ * @param {number} [options.tol=1e-6] - Convergence tolerance on the gradient norm
62
+ * @param {boolean} [options.verbose=false] - Log progress every 100 iterations
63
+ * @param {boolean} [options.lineSearch=false] - Backtracking line search in place of the fixed step
64
+ * @param {boolean} [options.stochastic=false] - Stored, unused
65
+ * @param {number} [options.batchSize=32] - Stored, unused
66
+ */
48
67
  constructor(options = {}) {
49
68
  super(options);
50
- this.stochastic = options.stochastic || false;
51
- this.batchSize = options.batchSize || 32;
52
- this.lineSearch = options.lineSearch || false;
69
+ this.stochastic = options.stochastic ?? false;
70
+ this.batchSize = options.batchSize ?? 32;
71
+ this.lineSearch = options.lineSearch ?? false;
53
72
  }
54
73
 
74
+ /**
75
+ * Minimize `lossFn` from `x0`.
76
+ * @param {(x: number[]) => number | {loss: number, gradient: number[]|Float64Array} | {value: number, gradient: number[]|Float64Array}} lossFn
77
+ * - Objective; usually `{loss, gradient}`, finite differences for a number
78
+ * @param {number[]} x0 - Initial parameters
79
+ * @param {Object} [options] - Overrides for this call
80
+ * @param {number} [options.maxIter] - Maximum iterations
81
+ * @param {number} [options.tol] - Gradient-norm tolerance
82
+ * @returns {{x: number[], history: {loss: number[], gradNorm: number[], learningRate: number[]}}}
83
+ */
55
84
  minimize(lossFn, x0, options = {}) {
56
85
  const { x, history } = gradientDescent(lossFn, x0, {
57
86
  ...this._options(options),
@@ -62,14 +91,34 @@ export class GradientDescent extends Optimizer {
62
91
  }
63
92
 
64
93
  /**
65
- * Momentum Optimizer
94
+ * Gradient descent with momentum as a `tangent/ds`-style optimizer object: `minimize(lossFn, x0)` returns `{x, history}`.
95
+ *
96
+ * New code can call `momentumDescent` or `minimize` directly.
66
97
  */
67
98
  export class MomentumOptimizer extends Optimizer {
99
+ /**
100
+ * @param {Object} [options]
101
+ * @param {number} [options.learningRate=0.01] - Step size
102
+ * @param {number} [options.maxIter=1000] - Maximum iterations
103
+ * @param {number} [options.tol=1e-6] - Convergence tolerance on the gradient norm
104
+ * @param {boolean} [options.verbose=false] - Log progress every 100 iterations
105
+ * @param {number} [options.momentum=0.9] - Momentum coefficient
106
+ */
68
107
  constructor(options = {}) {
69
108
  super(options);
70
- this.momentum = options.momentum || 0.9;
109
+ this.momentum = options.momentum ?? 0.9;
71
110
  }
72
111
 
112
+ /**
113
+ * Minimize `lossFn` from `x0`.
114
+ * @param {(x: number[]) => number | {loss: number, gradient: number[]|Float64Array} | {value: number, gradient: number[]|Float64Array}} lossFn
115
+ * - Objective; usually `{loss, gradient}`, finite differences for a number
116
+ * @param {number[]} x0 - Initial parameters
117
+ * @param {Object} [options] - Overrides for this call
118
+ * @param {number} [options.maxIter] - Maximum iterations
119
+ * @param {number} [options.tol] - Gradient-norm tolerance
120
+ * @returns {{x: number[], history: {loss: number[], gradNorm: number[]}}}
121
+ */
73
122
  minimize(lossFn, x0, options = {}) {
74
123
  const { x, history } = momentumDescent(lossFn, x0, {
75
124
  ...this._options(options),
@@ -80,15 +129,36 @@ export class MomentumOptimizer extends Optimizer {
80
129
  }
81
130
 
82
131
  /**
83
- * RMSProp Optimizer
132
+ * RMSProp as a `tangent/ds`-style optimizer object: `minimize(lossFn, x0)` returns `{x, history}`.
133
+ *
134
+ * New code can call `rmsprop` or `minimize` directly.
84
135
  */
85
136
  export class RMSProp extends Optimizer {
137
+ /**
138
+ * @param {Object} [options]
139
+ * @param {number} [options.learningRate=0.01] - Step size
140
+ * @param {number} [options.maxIter=1000] - Maximum iterations
141
+ * @param {number} [options.tol=1e-6] - Convergence tolerance on the gradient norm
142
+ * @param {boolean} [options.verbose=false] - Log progress every 100 iterations
143
+ * @param {number} [options.decay=0.9] - Decay of the running mean of squared gradients
144
+ * @param {number} [options.epsilon=1e-8] - Added to the denominator
145
+ */
86
146
  constructor(options = {}) {
87
147
  super(options);
88
- this.decay = options.decay || 0.9;
89
- this.epsilon = options.epsilon || 1e-8;
148
+ this.decay = options.decay ?? 0.9;
149
+ this.epsilon = options.epsilon ?? 1e-8;
90
150
  }
91
151
 
152
+ /**
153
+ * Minimize `lossFn` from `x0`.
154
+ * @param {(x: number[]) => number | {loss: number, gradient: number[]|Float64Array} | {value: number, gradient: number[]|Float64Array}} lossFn
155
+ * - Objective; usually `{loss, gradient}`, finite differences for a number
156
+ * @param {number[]} x0 - Initial parameters
157
+ * @param {Object} [options] - Overrides for this call
158
+ * @param {number} [options.maxIter] - Maximum iterations
159
+ * @param {number} [options.tol] - Gradient-norm tolerance
160
+ * @returns {{x: number[], history: {loss: number[], gradNorm: number[]}}}
161
+ */
92
162
  minimize(lossFn, x0, options = {}) {
93
163
  const { x, history } = rmsprop(lossFn, x0, {
94
164
  ...this._options(options),
@@ -100,16 +170,38 @@ export class RMSProp extends Optimizer {
100
170
  }
101
171
 
102
172
  /**
103
- * Adam Optimizer (Adaptive Moment Estimation)
173
+ * Adam as a `tangent/ds`-style optimizer object: `minimize(lossFn, x0)` returns `{x, history}`.
174
+ *
175
+ * New code can call `adam` or `minimize` directly.
104
176
  */
105
177
  export class AdamOptimizer extends Optimizer {
178
+ /**
179
+ * @param {Object} [options]
180
+ * @param {number} [options.learningRate=0.01] - Step size
181
+ * @param {number} [options.maxIter=1000] - Maximum iterations
182
+ * @param {number} [options.tol=1e-6] - Convergence tolerance on the gradient norm
183
+ * @param {boolean} [options.verbose=false] - Log progress every 100 iterations
184
+ * @param {number} [options.beta1=0.9] - First-moment decay
185
+ * @param {number} [options.beta2=0.999] - Second-moment decay
186
+ * @param {number} [options.epsilon=1e-8] - Added to the denominator
187
+ */
106
188
  constructor(options = {}) {
107
189
  super(options);
108
- this.beta1 = options.beta1 || 0.9;
109
- this.beta2 = options.beta2 || 0.999;
110
- this.epsilon = options.epsilon || 1e-8;
190
+ this.beta1 = options.beta1 ?? 0.9;
191
+ this.beta2 = options.beta2 ?? 0.999;
192
+ this.epsilon = options.epsilon ?? 1e-8;
111
193
  }
112
194
 
195
+ /**
196
+ * Minimize `lossFn` from `x0`.
197
+ * @param {(x: number[]) => number | {loss: number, gradient: number[]|Float64Array} | {value: number, gradient: number[]|Float64Array}} lossFn
198
+ * - Objective; usually `{loss, gradient}`, finite differences for a number
199
+ * @param {number[]} x0 - Initial parameters
200
+ * @param {Object} [options] - Overrides for this call
201
+ * @param {number} [options.maxIter] - Maximum iterations
202
+ * @param {number} [options.tol] - Gradient-norm tolerance
203
+ * @returns {{x: number[], history: {loss: number[], gradNorm: number[]}}}
204
+ */
113
205
  minimize(lossFn, x0, options = {}) {
114
206
  const { x, history } = adam(lossFn, x0, {
115
207
  ...this._options(options),
@@ -122,10 +214,16 @@ export class AdamOptimizer extends Optimizer {
122
214
  }
123
215
 
124
216
  /**
125
- * Convenience function to create optimizer by name
126
- * @param {string} name - Optimizer name
127
- * @param {Object} options - Optimizer options
128
- * @returns {Optimizer} Optimizer instance
217
+ * Create a `tangent/ds`-style optimizer by name.
218
+ *
219
+ * @param {'gd'|'gradient_descent'|'sgd'|'momentum'|'rmsprop'|'adam'} name - Case-insensitive;
220
+ * `'gd'`, `'gradient_descent'` and `'sgd'` all give a `GradientDescent`
221
+ * @param {Object} [options] - The class's constructor options
222
+ * @returns {GradientDescent|MomentumOptimizer|RMSProp|AdamOptimizer}
223
+ * @throws {Error} for an unknown name
224
+ * @example
225
+ * const opt = createOptimizer('adam', { learningRate: 0.1 });
226
+ * opt.minimize((x) => ({ loss: x[0] ** 2, gradient: [2 * x[0]] }), [3]).x; // ≈ [0]
129
227
  */
130
228
  export function createOptimizer(name, options = {}) {
131
229
  const optimizers = {
package/src/gradient.js CHANGED
@@ -21,11 +21,15 @@ function gradNorm(gradient) {
21
21
  }
22
22
 
23
23
  /**
24
- * Backtracking line search satisfying the Armijo condition.
24
+ * Find a step size along the negative gradient by backtracking until the Armijo condition holds.
25
25
  *
26
- * @param {Function} evaluate - (x) => {loss, gradient}
27
- * @param {Array<number>} x - Current point
28
- * @param {Array<number>} gradient - Gradient at x
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 || 0.01;
68
- const maxIter = options.maxIter || 1000;
69
- const tol = options.tol || 1e-6;
70
- const verbose = options.verbose || false;
71
- const lineSearch = options.lineSearch || false;
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
- * Plain gradient descent, with optional backtracking line search.
133
+ * Minimize a function by plain gradient descent, with optional backtracking line search.
130
134
  *
131
- * @param {Function} f - Objective: (x) => number or (x) => {loss, gradient}
132
- * @param {Array<number>} x0 - Initial parameters
133
- * @param {Object} [options] - {grad, learningRate, maxIter, tol, lineSearch, verbose}
134
- * @returns {Object} {x, fx, iterations, converged, history}
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
- * Gradient descent with momentum.
165
+ * Minimize a function by gradient descent with momentum.
150
166
  *
151
- * @param {Function} f - Objective
152
- * @param {Array<number>} x0 - Initial parameters
153
- * @param {Object} [options] - {grad, learningRate, maxIter, tol, momentum, verbose}
154
- * @returns {Object} {x, fx, iterations, converged, history}
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 || 0.9;
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 {Function} f - Objective
173
- * @param {Array<number>} x0 - Initial parameters
174
- * @param {Object} [options] - {grad, learningRate, maxIter, tol, decay, epsilon, verbose}
175
- * @returns {Object} {x, fx, iterations, converged, history}
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 || 0.9;
179
- const epsilon = options.epsilon || 1e-8;
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 {Function} f - Objective
195
- * @param {Array<number>} x0 - Initial parameters
196
- * @param {Object} [options] - {grad, learningRate, maxIter, tol, beta1, beta2, epsilon, verbose}
197
- * @returns {Object} {x, fx, iterations, converged, history}
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 || 0.9;
201
- const beta2 = options.beta2 || 0.999;
202
- const epsilon = options.epsilon || 1e-8;
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) =>