@nirs4all/methods 1.3.17 → 1.3.19
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 +68 -2
- package/dist/estimatorRolesGenerated.js +1 -1
- package/dist/explain.d.ts +124 -0
- package/dist/explain.js +554 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -0
- package/dist/n4m.js +1 -1
- package/dist/n4m.wasm +0 -0
- package/dist/preflightDiagnostics.js +2 -2
- package/package.json +2 -2
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.
|
|
61
|
-
console.log(n4m.abiVersion()); // [2,
|
|
60
|
+
console.log(n4m.version()); // "1.3.19+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).
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// SPDX-License-Identifier: CECILL-2.1 OR AGPL-3.0-or-later
|
|
2
2
|
// Generated by scripts/generate_js_roles.py from `n4m_cli --manifest-json`. Do not edit.
|
|
3
|
-
// Native ABI 2.
|
|
3
|
+
// Native ABI 2.23.0.
|
|
4
4
|
import { NativeEstimator, NativeMethod, NativeProcedure, } from "./estimatorRoles.js";
|
|
5
5
|
/** Native `aom_pop.aom_chain_fixed_fit` (regressor). */
|
|
6
6
|
export class AOMFixedCandidate extends NativeEstimator {
|
|
@@ -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
|
+
};
|