@nirs4all/methods 1.3.16 → 1.3.18

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 CHANGED
@@ -57,8 +57,8 @@ restores the original typed label table; omitting it exposes native class IDs.
57
57
  import * as n4m from "@nirs4all/methods";
58
58
 
59
59
  await n4m.loadModule();
60
- console.log(n4m.version()); // "1.3.14+abi.2.22.0"
61
- console.log(n4m.abiVersion()); // [2, 22, 0]
60
+ console.log(n4m.version()); // "1.3.18+abi.2.23.0"
61
+ console.log(n4m.abiVersion()); // [2, 23, 0]
62
62
 
63
63
  const rows = 40, cols = 6;
64
64
  const X = new Float64Array(rows * cols); // row-major
@@ -375,3 +375,69 @@ quantities are `null`, including ranks across disconnected comparison graphs.
375
375
  Bayesian uncertainty is an approximate algorithm posterior standard deviation,
376
376
  not a frequentist standard error. The Friedman statistic is descriptive and
377
377
  uses complete blocks; the caller must assess independence.
378
+
379
+ ## Explainability
380
+
381
+ `explainModel`, `linearShap`, `treeShap`, `groupsFixedWidth`,
382
+ `groupsFromRanges` and `summarizeAttributions` wrap `n4m/explain.h`. Every
383
+ attribution is computed by libn4m; the binding only marshals buffers and
384
+ drives the native ask/tell session.
385
+
386
+ The model-agnostic explainers (`exact_shap`, `permutation_shap`,
387
+ `kernel_shap`, `lime`, `occlusion`) never call a model themselves: the native
388
+ session emits batches of perturbed rows, the host predicts them with any
389
+ backend (a WASM pipeline, ONNX Runtime Web, a worker round trip) and the
390
+ binding submits the predictions back. `predictBatch` may be synchronous or
391
+ return a promise; the rows it receives are a fresh copy that stays valid
392
+ across `await`.
393
+
394
+ ```js
395
+ import { loadModule, explainModel, groupsFixedWidth, summarizeAttributions } from "@nirs4all/methods";
396
+ await loadModule();
397
+
398
+ // X and background are row-major { data: Float64Array, rows, cols } in the
399
+ // feature space the predictor consumes (for example raw spectra of a fitted pipeline).
400
+ const result = await explainModel({
401
+ X, background,
402
+ grouping: groupsFixedWidth(X.cols, 16), // optional; default one group per feature
403
+ predictBatch: async (rows, nRows, nFeatures) => pipeline.predict(rows, nRows, nFeatures),
404
+ options: { method: "permutation_shap", nPermutations: 10, seed: 0 },
405
+ onProgress: (done, total) => console.log(`${done}/${total} model rows`),
406
+ signal: abortController.signal, // rejects with an "AbortError" DOMException
407
+ });
408
+ // result.attributions is [row][group][output]; expected/predictions are [row][output].
409
+ console.log(result.exactness, result.additivityMaxAbsError);
410
+ const { meanAbs, meanSigned } = summarizeAttributions(result, 0);
411
+ ```
412
+
413
+ | Kind | Exactness | Additive | `groupAggregation` |
414
+ | --- | --- | --- | --- |
415
+ | `exact_shap` (groups ≤ 16) | `exact` | yes | `group_game` |
416
+ | `permutation_shap` (antithetic) | `sampled` (`stdError` is the Monte-Carlo standard error) | yes | `group_game` |
417
+ | `kernel_shap` | `sampled`, or `exact` when the coalition budget covers all 2^G − 2 coalitions | yes | `group_game` |
418
+ | `lime` | `surrogate` | no | `group_game` |
419
+ | `occlusion` | `perturbation` | no | `group_game` |
420
+ | `linear_shap` | `exact` (interventional) | yes | `none`, or `group_game` with grouping (linear group sums are group Shapley values) |
421
+ | `tree_shap` (path-dependent) | `exact` | yes | `none`, or `sum_of_feature_values` with grouping |
422
+
423
+ Baselines: `background` (interventional average over every background row),
424
+ `mean` (column mean of the background) and `interpolate` (each absent run is
425
+ bridged by a straight line between its present neighbours; contiguous groups
426
+ only, background optional). `nOutputs` is inferred by predicting `X` row 0
427
+ once when omitted; that probe row is counted in `evaluations`. The output space
428
+ (target units, class probability, decision score) is whatever `predictBatch`
429
+ returns; the binding never relabels it. `settings` uses the snake_case keys of
430
+ the `nirs4all.explanation.v1` envelope, which hosts build from the result plus
431
+ their own axis, output and sample-index metadata.
432
+
433
+ `linearShap({ X, coefficients, intercept, reference, grouping })` explains an
434
+ affine model `X · coefficients + intercept` (`coefficients` is
435
+ `nFeatures × nOutputs`, `reference` the background column means).
436
+ `treeShap({ X, trees, grouping })` takes a generic flat ensemble
437
+ (`treeOffsets` of length `nTrees + 1`, per-node `feature`, `threshold`, local
438
+ `left`/`right` children, `cover`, `value`, optional `defaultLeft`,
439
+ `decisionType` 0 for `x <= threshold` or 1 for `x < threshold`, `baseOffset`
440
+ and `treeScale`); converting a specific library's trees to this layout is the
441
+ host's job. `groupsFromRanges(nFeatures, [[start, end), ...])` turns half-open
442
+ feature-index ranges (for example chemical bands already mapped to indices)
443
+ into a partition and reports `rangeOfGroup` (`-1` for uncovered runs).
@@ -102,6 +102,12 @@ export declare abstract class NativeEstimator extends NativeMethod {
102
102
  fit(X: Matrix, y?: Matrix | Float64Array | ArrayLike<number>, inputs?: FitInputs): this;
103
103
  /** True when the fitted state embeds training rows (kernel PLS, GPR-PLS, LW-PLS, ...). */
104
104
  containsTrainingRows(): boolean;
105
+ /**
106
+ * Named diagnostics of the last fit (n4m_estimator_fit_result), for
107
+ * example the training loss history of a neural regressor; null when the
108
+ * method keeps none, including after fromN4me (diagnostics are not state).
109
+ */
110
+ fitResult(): Record<string, ProcedureOutput> | null;
105
111
  /**
106
112
  * Portable fitted state (N4ME bytes), readable by every n4m binding. A
107
113
  * state that embeds training rows (containsTrainingRows()) is refused
@@ -340,6 +340,36 @@ export class NativeEstimator extends NativeMethod {
340
340
  m._free(out);
341
341
  }
342
342
  }
343
+ /**
344
+ * Named diagnostics of the last fit (n4m_estimator_fit_result), for
345
+ * example the training loss history of a neural regressor; null when the
346
+ * method keeps none, including after fromN4me (diagnostics are not state).
347
+ */
348
+ fitResult() {
349
+ const m = getModule();
350
+ const handle = this.handle();
351
+ const out = m._malloc(8);
352
+ try {
353
+ m.setValue(out, 0, "i32");
354
+ const status = m.ccall("n4m_estimator_fit_result", "number", ["number", "number"], [handle, out]);
355
+ if (status === 10)
356
+ return null; // N4M_ERR_UNSUPPORTED: no fit diagnostics
357
+ checkStatus(status);
358
+ const result = m.getValue(out, "i32");
359
+ checkStatus(m.ccall("n4m_method_result_entry_count", "number", ["number", "number"], [result, out]));
360
+ const count = m.getValue(out, "i32");
361
+ const entries = {};
362
+ for (let i = 0; i < count; ++i) {
363
+ checkStatus(m.ccall("n4m_method_result_entry", "number", ["number", "number", "number", "number"], [result, i, out, out + 4]));
364
+ const name = m.UTF8ToString(m.getValue(out, "i32"));
365
+ entries[name] = readEntry(result, name, m.getValue(out + 4, "i32"));
366
+ }
367
+ return entries;
368
+ }
369
+ finally {
370
+ m._free(out);
371
+ }
372
+ }
343
373
  /**
344
374
  * Portable fitted state (N4ME bytes), readable by every n4m binding. A
345
375
  * state that embeds training rows (containsTrainingRows()) is refused
@@ -2257,6 +2257,54 @@ export declare class SOPLS extends NativeEstimator implements Regressor {
2257
2257
  constructor(params?: SOPLSParams);
2258
2258
  predict(X: Matrix): Matrix;
2259
2259
  }
2260
+ /** Parameters of MultibranchRegressor; unset values take the native defaults. */
2261
+ export interface MultibranchRegressorParams {
2262
+ /** Default []. */
2263
+ branch_kinds?: number[];
2264
+ /** Default []. */
2265
+ branch_shapes?: number[];
2266
+ /** Default 4. */
2267
+ filters?: number;
2268
+ /** Default 5. */
2269
+ kernel_size?: number;
2270
+ /** Default 2. */
2271
+ pool_size?: number;
2272
+ /** Default 8. */
2273
+ embedding_dim?: number;
2274
+ /** Default 8. */
2275
+ head_hidden?: number;
2276
+ /** Default 100. */
2277
+ epochs?: number;
2278
+ /** Default 16. */
2279
+ batch_size?: number;
2280
+ /** Default 0.01. */
2281
+ learning_rate?: number;
2282
+ /** Default 0.0001. */
2283
+ weight_decay?: number;
2284
+ /** Optional: unset by default. */
2285
+ seed?: number;
2286
+ }
2287
+ /** Native `models.neural.multibranch_regressor` (transformer, regressor). */
2288
+ export declare class MultibranchRegressor extends NativeEstimator implements Regressor, Transformer {
2289
+ readonly methodId = "models.neural.multibranch_regressor";
2290
+ readonly paramTypes: {
2291
+ readonly branch_kinds: "int_array";
2292
+ readonly branch_shapes: "int_array";
2293
+ readonly filters: "int";
2294
+ readonly kernel_size: "int";
2295
+ readonly pool_size: "int";
2296
+ readonly embedding_dim: "int";
2297
+ readonly head_hidden: "int";
2298
+ readonly epochs: "int";
2299
+ readonly batch_size: "int";
2300
+ readonly learning_rate: "double";
2301
+ readonly weight_decay: "double";
2302
+ readonly seed: "int";
2303
+ };
2304
+ constructor(params?: MultibranchRegressorParams);
2305
+ predict(X: Matrix): Matrix;
2306
+ transform(X: Matrix): Matrix;
2307
+ }
2260
2308
  /** Parameters of CPPLS; unset values take the native defaults. */
2261
2309
  export interface CPPLSParams {
2262
2310
  /** Default 2. */
@@ -3308,6 +3356,16 @@ export declare class BaselineCenter extends NativeEstimator implements Transform
3308
3356
  constructor(params?: BaselineCenterParams);
3309
3357
  transform(X: Matrix): Matrix;
3310
3358
  }
3359
+ /** Parameters of BlockRms; unset values take the native defaults. */
3360
+ export interface BlockRmsParams {
3361
+ }
3362
+ /** Native `preprocessing.scaling.block_rms` (transformer). */
3363
+ export declare class BlockRms extends NativeEstimator implements Transformer {
3364
+ readonly methodId = "preprocessing.scaling.block_rms";
3365
+ readonly paramTypes: {};
3366
+ constructor(params?: BlockRmsParams);
3367
+ transform(X: Matrix): Matrix;
3368
+ }
3311
3369
  /** Parameters of LogTransform; unset values take the native defaults. */
3312
3370
  export interface LogTransformParams {
3313
3371
  /** Default 0. */
@@ -1689,6 +1689,35 @@ export class SOPLS extends NativeEstimator {
1689
1689
  }
1690
1690
  }
1691
1691
  NativeMethod.register("models.multiblock.so_pls", SOPLS);
1692
+ /** Native `models.neural.multibranch_regressor` (transformer, regressor). */
1693
+ export class MultibranchRegressor extends NativeEstimator {
1694
+ methodId = "models.neural.multibranch_regressor";
1695
+ paramTypes = {
1696
+ branch_kinds: "int_array",
1697
+ branch_shapes: "int_array",
1698
+ filters: "int",
1699
+ kernel_size: "int",
1700
+ pool_size: "int",
1701
+ embedding_dim: "int",
1702
+ head_hidden: "int",
1703
+ epochs: "int",
1704
+ batch_size: "int",
1705
+ learning_rate: "double",
1706
+ weight_decay: "double",
1707
+ seed: "int",
1708
+ };
1709
+ constructor(params = {}) {
1710
+ super();
1711
+ this.params = { ...params };
1712
+ }
1713
+ predict(X) {
1714
+ return this.predictMatrix(X);
1715
+ }
1716
+ transform(X) {
1717
+ return this.transformMatrix(X);
1718
+ }
1719
+ }
1720
+ NativeMethod.register("models.neural.multibranch_regressor", MultibranchRegressor);
1692
1721
  /** Native `models.pls.cppls` (regressor). */
1693
1722
  export class CPPLS extends NativeEstimator {
1694
1723
  methodId = "models.pls.cppls";
@@ -2605,6 +2634,19 @@ export class BaselineCenter extends NativeEstimator {
2605
2634
  }
2606
2635
  }
2607
2636
  NativeMethod.register("preprocessing.scaling.baseline", BaselineCenter);
2637
+ /** Native `preprocessing.scaling.block_rms` (transformer). */
2638
+ export class BlockRms extends NativeEstimator {
2639
+ methodId = "preprocessing.scaling.block_rms";
2640
+ paramTypes = {};
2641
+ constructor(params = {}) {
2642
+ super();
2643
+ this.params = { ...params };
2644
+ }
2645
+ transform(X) {
2646
+ return this.transformMatrix(X);
2647
+ }
2648
+ }
2649
+ NativeMethod.register("preprocessing.scaling.block_rms", BlockRms);
2608
2650
  /** Native `preprocessing.scaling.log_transform` (transformer). */
2609
2651
  export class LogTransform extends NativeEstimator {
2610
2652
  methodId = "preprocessing.scaling.log_transform";
@@ -0,0 +1,124 @@
1
+ import { type Matrix } from "./types.js";
2
+ export type ExplainMethod = "exact_shap" | "permutation_shap" | "kernel_shap" | "lime" | "occlusion";
3
+ export type ExplainBaseline = "background" | "mean" | "interpolate";
4
+ export type AttributionKind = ExplainMethod | "linear_shap" | "tree_shap";
5
+ export interface ExplainOptions {
6
+ /** Default "permutation_shap". */
7
+ method?: ExplainMethod;
8
+ /** Default "background". */
9
+ baseline?: ExplainBaseline;
10
+ /** Antithetic permutation pairs per row (default 10). */
11
+ nPermutations?: number;
12
+ /** Sampled coalitions per row for kernel_shap/lime; 0 = native auto. */
13
+ nCoalitions?: number;
14
+ /** LIME kernel width; <= 0 = native auto. */
15
+ limeKernelWidth?: number;
16
+ /** LIME ridge penalty (default 1). */
17
+ limeRidge?: number;
18
+ /** Upper bound of rows per requested batch (default 4096). */
19
+ maxBatchRows?: number;
20
+ /** Sampling seed: a nonnegative integer < 2^53 (default 0). */
21
+ seed?: number;
22
+ }
23
+ /** rows: row-major nRows x nFeatures in the explained feature space.
24
+ * Returns nRows x nOutputs row-major predictions. */
25
+ export type PredictBatch = (rows: Float64Array, nRows: number, nFeatures: number) => Float64Array | number[] | Promise<Float64Array | number[]>;
26
+ /** Feature partition: featureGroup[j] in [0, nGroups) for every feature j. */
27
+ export interface FeatureGrouping {
28
+ featureGroup: Int32Array;
29
+ nGroups: number;
30
+ /** groupsFromRanges only: source range index per group, -1 for uncovered runs. */
31
+ rangeOfGroup?: Int32Array;
32
+ }
33
+ export interface ExplainModelInput {
34
+ /** Rows to explain. */
35
+ X: Matrix;
36
+ /** Required for the "background" and "mean" baselines. */
37
+ background?: Matrix;
38
+ /** Omitted = one group per feature. */
39
+ grouping?: FeatureGrouping;
40
+ /** Omitted = inferred by predicting X row 0 once. */
41
+ nOutputs?: number;
42
+ predictBatch: PredictBatch;
43
+ options?: ExplainOptions;
44
+ onProgress?: (doneEvaluations: number, totalEvaluations: number) => void;
45
+ /** Checked between batches; aborts with DOMException "AbortError". */
46
+ signal?: AbortSignal;
47
+ }
48
+ export interface AttributionResult {
49
+ kind: AttributionKind;
50
+ /** null for linear/tree. */
51
+ baseline: ExplainBaseline | null;
52
+ exactness: "exact" | "sampled" | "surrogate" | "perturbation";
53
+ additive: boolean;
54
+ groupAggregation: "group_game" | "sum_of_feature_values" | "none";
55
+ nRows: number;
56
+ nGroups: number;
57
+ nOutputs: number;
58
+ nFeatures: number;
59
+ /** [row][group][output] */
60
+ attributions: Float64Array;
61
+ /** [row][output] */
62
+ expected: Float64Array;
63
+ /** [row][output] */
64
+ predictions: Float64Array;
65
+ /** [row][group][output] (permutation only; NaN when a single pair was drawn). */
66
+ stdError: Float64Array | null;
67
+ /** max |prediction - expected - sum(attributions)|; null when not additive. */
68
+ additivityMaxAbsError: number | null;
69
+ /** Model rows evaluated by the host (0 for linear/tree). */
70
+ evaluations: number;
71
+ settings: Record<string, number | string | boolean | null>;
72
+ engine: {
73
+ name: "nirs4all-methods";
74
+ version: string;
75
+ abi: string;
76
+ };
77
+ }
78
+ export interface FlatTreeEnsemble {
79
+ /** nTrees + 1 offsets; tree t owns nodes [treeOffsets[t], treeOffsets[t+1]). */
80
+ treeOffsets: number[] | Int32Array;
81
+ feature: Int32Array | number[];
82
+ threshold: Float64Array;
83
+ /** Child indices LOCAL to the tree, -1 for a leaf. */
84
+ left: Int32Array | number[];
85
+ right: Int32Array | number[];
86
+ defaultLeft?: Uint8Array;
87
+ cover: Float64Array;
88
+ /** nNodes * nOutputs leaf values. */
89
+ value: Float64Array;
90
+ nOutputs: number;
91
+ /** 0: x <= threshold goes left (sklearn, LightGBM); 1: x < threshold (XGBoost). */
92
+ decisionType?: 0 | 1;
93
+ baseOffset?: Float64Array;
94
+ /** 1/nTrees for averaging forests, 1 for boosting (default 1). */
95
+ treeScale?: number;
96
+ }
97
+ /** Explain any model through a native ask/tell session. The host predicts
98
+ * the requested perturbed rows with predictBatch (sync or async). */
99
+ export declare function explainModel(input: ExplainModelInput): Promise<AttributionResult>;
100
+ /** Exact interventional SHAP of an affine model X . coefficients + intercept. */
101
+ export declare function linearShap(input: {
102
+ X: Matrix;
103
+ coefficients: Matrix;
104
+ intercept?: Float64Array;
105
+ reference: Float64Array;
106
+ grouping?: FeatureGrouping;
107
+ }): AttributionResult;
108
+ /** Exact path-dependent TreeSHAP over a generic flat tree ensemble. Grouped
109
+ * values are sums of per-feature Shapley values, not group-game values. */
110
+ export declare function treeShap(input: {
111
+ X: Matrix;
112
+ trees: FlatTreeEnsemble;
113
+ grouping?: FeatureGrouping;
114
+ }): AttributionResult;
115
+ /** Contiguous fixed-width partition: feature j -> group floor(j / width). */
116
+ export declare function groupsFixedWidth(nFeatures: number, width: number): FeatureGrouping;
117
+ /** Partition from half-open [start, end) feature-index ranges. Range r becomes
118
+ * group r; every maximal uncovered run becomes one further group. */
119
+ export declare function groupsFromRanges(nFeatures: number, ranges: ReadonlyArray<readonly [number, number]>): FeatureGrouping;
120
+ /** Per-group mean |attribution| and mean signed attribution over rows. */
121
+ export declare function summarizeAttributions(result: AttributionResult, outputIndex?: number): {
122
+ meanAbs: Float64Array;
123
+ meanSigned: Float64Array;
124
+ };