@nirs4all/methods 1.3.18 → 1.4.0
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 +32 -2
- package/dist/estimatorRoles.d.ts +46 -0
- package/dist/estimatorRoles.js +106 -1
- package/dist/estimatorRolesGenerated.js +1 -1
- package/dist/explain.d.ts +46 -2
- package/dist/explain.js +173 -8
- package/dist/index.d.ts +2 -2
- package/dist/index.js +1 -1
- package/dist/n4m.js +1 -1
- package/dist/n4m.wasm +0 -0
- package/dist/preflightDiagnostics.js +2 -2
- package/dist/rolePipeline.d.ts +17 -2
- package/dist/rolePipeline.js +46 -3
- 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.
|
|
61
|
-
console.log(n4m.abiVersion()); // [2,
|
|
60
|
+
console.log(n4m.version()); // "1.4.0+abi.2.24.0"
|
|
61
|
+
console.log(n4m.abiVersion()); // [2, 24, 0]
|
|
62
62
|
|
|
63
63
|
const rows = 40, cols = 6;
|
|
64
64
|
const X = new Float64Array(rows * cols); // row-major
|
|
@@ -419,6 +419,7 @@ const { meanAbs, meanSigned } = summarizeAttributions(result, 0);
|
|
|
419
419
|
| `occlusion` | `perturbation` | no | `group_game` |
|
|
420
420
|
| `linear_shap` | `exact` (interventional) | yes | `none`, or `group_game` with grouping (linear group sums are group Shapley values) |
|
|
421
421
|
| `tree_shap` (path-dependent) | `exact` | yes | `none`, or `sum_of_feature_values` with grouping |
|
|
422
|
+
| `gradient` (ABI 2.24; central differences) | `perturbation` | no (exact for affine models; `additivityMaxAbsError` reported) | `sum_of_feature_values` |
|
|
422
423
|
|
|
423
424
|
Baselines: `background` (interventional average over every background row),
|
|
424
425
|
`mean` (column mean of the background) and `interpolate` (each absent run is
|
|
@@ -441,3 +442,32 @@ and `treeScale`); converting a specific library's trees to this layout is the
|
|
|
441
442
|
host's job. `groupsFromRanges(nFeatures, [[start, end), ...])` turns half-open
|
|
442
443
|
feature-index ranges (for example chemical bands already mapped to indices)
|
|
443
444
|
into a partition and reports `rangeOfGroup` (`-1` for uncovered runs).
|
|
445
|
+
|
|
446
|
+
`method: "gradient"` (ABI 2.24) returns, besides the first-order attributions
|
|
447
|
+
`g_j (x_j - r_j)` against the background mean `r`, `gradients`
|
|
448
|
+
(`[row][feature][output]`), `meanGradient` (`[feature][output]`) and
|
|
449
|
+
`gradientSteps`; `options.gradientStep` sets the relative step (default
|
|
450
|
+
`1e-3`, scaled by the background column spread). `perturbRows({ X, background,
|
|
451
|
+
grouping, absentGroups, baseline })` returns exactly the rows a session sends
|
|
452
|
+
to the model for one coalition (baseline preview; `background` yields
|
|
453
|
+
`X.rows * background.rows` rows). `summarizeAttributions` also returns
|
|
454
|
+
`meanSignedStdError` (`sqrt(sum_r se_rg^2) / nRows`, `null` without
|
|
455
|
+
`stdError`).
|
|
456
|
+
|
|
457
|
+
### Model-intrinsic importances (ABI 2.24)
|
|
458
|
+
|
|
459
|
+
```js
|
|
460
|
+
const est = NativeEstimator.fromN4me(state); // e.g. a fitted PLSRegression or Ridge
|
|
461
|
+
const { coefficients, intercept } = est.affineCoefficients(); // predict(X) = X·B + b
|
|
462
|
+
const latent = est.latentStructure(); // W, R, P, Q, xMean, xScale (PLS family)
|
|
463
|
+
const vip = modelImportance(est, Xtrain, { kind: "vip" }); // or "selectivity_ratio" / "standardized_coefficients"
|
|
464
|
+
const raw = pipeline.inputAffineCoefficients(); // exact raw-input map of an affine RolePipeline
|
|
465
|
+
pipeline.stepsInfo().map((s) => [s.affine, s.columnAligned]);
|
|
466
|
+
aggregateProfile(vip, groupsFixedWidth(vip.length, 8), "mean");
|
|
467
|
+
const { spearman, topKJaccard } = compareProfiles(profilesMatrix, { topK: 10 });
|
|
468
|
+
```
|
|
469
|
+
|
|
470
|
+
Refusals are native `N4mError`s (`UNSUPPORTED` for a non-affine estimator or a
|
|
471
|
+
model without latent structure; the pipeline refusal names the first
|
|
472
|
+
non-affine step). See `docs/EXPLAIN.md` and
|
|
473
|
+
`docs/explain/importance_profile_v1.schema.json`.
|
package/dist/estimatorRoles.d.ts
CHANGED
|
@@ -118,6 +118,22 @@ export declare abstract class NativeEstimator extends NativeMethod {
|
|
|
118
118
|
}): Uint8Array;
|
|
119
119
|
/** Rebuilds a fitted estimator of the class registered for its method. */
|
|
120
120
|
static fromN4me(payload: Uint8Array): NativeEstimator;
|
|
121
|
+
/**
|
|
122
|
+
* Affine map predict(X) = X B + b of a fitted estimator declaring the
|
|
123
|
+
* native N4M_CAP_AFFINE capability (PLS family, Ridge, ...), also after
|
|
124
|
+
* fromN4me(). Throws the native UNSUPPORTED refusal otherwise.
|
|
125
|
+
*/
|
|
126
|
+
affineCoefficients(): AffineCoefficients;
|
|
127
|
+
/** W, R, P, Q, x mean / scale of a fitted latent-variable model; native refusal otherwise. */
|
|
128
|
+
latentStructure(): LatentStructure;
|
|
129
|
+
/**
|
|
130
|
+
* Importance profile (nFeaturesIn values) on rows X given in this
|
|
131
|
+
* estimator's input space (normally the preprocessed training rows):
|
|
132
|
+
* VIP, target-projection selectivity ratio or standardized coefficients
|
|
133
|
+
* (ddof = 1), computed natively.
|
|
134
|
+
*/
|
|
135
|
+
modelImportance(X: Matrix, options: ModelImportanceOptions): Float64Array;
|
|
136
|
+
private dim;
|
|
121
137
|
/** Releases the native estimator. */
|
|
122
138
|
dispose(): void;
|
|
123
139
|
protected predictMatrix(X: Matrix): Matrix;
|
|
@@ -134,6 +150,36 @@ export declare abstract class NativeEstimator extends NativeMethod {
|
|
|
134
150
|
private handle;
|
|
135
151
|
private static methodIdOf;
|
|
136
152
|
}
|
|
153
|
+
/** predict(X) = X . coefficients + intercept (ABI 2.24). */
|
|
154
|
+
export interface AffineCoefficients {
|
|
155
|
+
/** nFeaturesIn x nOutputs, row-major. */
|
|
156
|
+
coefficients: Matrix;
|
|
157
|
+
/** nOutputs. */
|
|
158
|
+
intercept: Float64Array;
|
|
159
|
+
}
|
|
160
|
+
/** Latent structure of a fitted PLS-family model (ABI 2.24), row-major. */
|
|
161
|
+
export interface LatentStructure {
|
|
162
|
+
nComponents: number;
|
|
163
|
+
/** p x A (W). */
|
|
164
|
+
xWeights: Matrix;
|
|
165
|
+
/** p x A (R = W (P'W)^-1; scores T = ((X - xMean) / xScale) R). */
|
|
166
|
+
xRotations: Matrix;
|
|
167
|
+
/** p x A (P). */
|
|
168
|
+
xLoadings: Matrix;
|
|
169
|
+
/** q x A (Q, in the fitted Y units). */
|
|
170
|
+
yLoadings: Matrix;
|
|
171
|
+
/** p, centring used at fit (0 when uncentred). */
|
|
172
|
+
xMean: Float64Array;
|
|
173
|
+
/** p, scaling used at fit (1 when unscaled). */
|
|
174
|
+
xScale: Float64Array;
|
|
175
|
+
}
|
|
176
|
+
/** Native n4m_importance_kind_t codes. */
|
|
177
|
+
export type ModelImportanceKind = "vip" | "selectivity_ratio" | "standardized_coefficients";
|
|
178
|
+
export interface ModelImportanceOptions {
|
|
179
|
+
kind: ModelImportanceKind;
|
|
180
|
+
/** Output column (selectivity ratio, standardized coefficients); default 0. VIP uses every output. */
|
|
181
|
+
outputIndex?: number;
|
|
182
|
+
}
|
|
137
183
|
/** Splitter role: Data[n, p] (+ Target, groups) -> folds of 0-based row indices. */
|
|
138
184
|
export interface Splitter {
|
|
139
185
|
split(X: Matrix, y?: Float64Array | ArrayLike<number>, groups?: number[]): Fold[];
|
package/dist/estimatorRoles.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// SPDX-License-Identifier: CECILL-2.1 OR AGPL-3.0-or-later
|
|
2
|
-
// Generic native estimator roles (ABI 2.13).
|
|
2
|
+
// Generic native estimator roles (ABI 2.13; model-intrinsic structure ABI 2.24).
|
|
3
3
|
//
|
|
4
4
|
// The helpers exported below (contexts, allocations, typed parameters, fit
|
|
5
5
|
// inputs) are shared with rolePipeline.ts; the package index does not
|
|
@@ -424,6 +424,108 @@ export class NativeEstimator extends NativeMethod {
|
|
|
424
424
|
m._free(out);
|
|
425
425
|
}
|
|
426
426
|
}
|
|
427
|
+
/**
|
|
428
|
+
* Affine map predict(X) = X B + b of a fitted estimator declaring the
|
|
429
|
+
* native N4M_CAP_AFFINE capability (PLS family, Ridge, ...), also after
|
|
430
|
+
* fromN4me(). Throws the native UNSUPPORTED refusal otherwise.
|
|
431
|
+
*/
|
|
432
|
+
affineCoefficients() {
|
|
433
|
+
const m = getModule();
|
|
434
|
+
const handle = this.handle();
|
|
435
|
+
const p = this.dim("n4m_estimator_n_features_in", handle);
|
|
436
|
+
const q = this.dim("n4m_estimator_n_outputs", handle);
|
|
437
|
+
const coef = m._malloc(Math.max(1, p * q) * 8);
|
|
438
|
+
const icpt = m._malloc(Math.max(1, q) * 8);
|
|
439
|
+
try {
|
|
440
|
+
withContext((ctx) => checkStatus(m.ccall("n4m_estimator_affine_coefficients_v1", "number", ["number", "number", "number", "i64", "number", "i64"], [ctx, handle, coef, BigInt(p * q), icpt, BigInt(q)]), ctx));
|
|
441
|
+
return {
|
|
442
|
+
coefficients: { data: m.HEAPF64.slice(coef / 8, coef / 8 + p * q), rows: p, cols: q },
|
|
443
|
+
intercept: m.HEAPF64.slice(icpt / 8, icpt / 8 + q),
|
|
444
|
+
};
|
|
445
|
+
}
|
|
446
|
+
finally {
|
|
447
|
+
m._free(coef);
|
|
448
|
+
m._free(icpt);
|
|
449
|
+
}
|
|
450
|
+
}
|
|
451
|
+
/** W, R, P, Q, x mean / scale of a fitted latent-variable model; native refusal otherwise. */
|
|
452
|
+
latentStructure() {
|
|
453
|
+
const m = getModule();
|
|
454
|
+
const handle = this.handle();
|
|
455
|
+
const p = this.dim("n4m_estimator_n_features_in", handle);
|
|
456
|
+
const q = this.dim("n4m_estimator_n_outputs", handle);
|
|
457
|
+
const aPtr = m._malloc(8);
|
|
458
|
+
const allocs = [aPtr];
|
|
459
|
+
try {
|
|
460
|
+
return withContext((ctx) => {
|
|
461
|
+
const call = (bufs, pa, qa) => checkStatus(m.ccall("n4m_estimator_latent_structure_v1", "number", ["number", "number", "number", "number", "number", "number", "i64", "number", "i64",
|
|
462
|
+
"number", "number", "i64"], [ctx, handle, aPtr, bufs[0], bufs[1], bufs[2], BigInt(pa), bufs[3], BigInt(qa),
|
|
463
|
+
bufs[4], bufs[5], BigInt(p)]), ctx);
|
|
464
|
+
call([0, 0, 0, 0, 0, 0], 0, 0);
|
|
465
|
+
const a = readI64(aPtr);
|
|
466
|
+
const sizes = [p * a, p * a, p * a, q * a, p, p];
|
|
467
|
+
const bufs = sizes.map((n) => {
|
|
468
|
+
const ptr = m._malloc(Math.max(1, n) * 8);
|
|
469
|
+
allocs.push(ptr);
|
|
470
|
+
return ptr;
|
|
471
|
+
});
|
|
472
|
+
call(bufs, p * a, q * a);
|
|
473
|
+
const read = (i) => m.HEAPF64.slice(bufs[i] / 8, bufs[i] / 8 + sizes[i]);
|
|
474
|
+
return {
|
|
475
|
+
nComponents: a,
|
|
476
|
+
xWeights: { data: read(0), rows: p, cols: a },
|
|
477
|
+
xRotations: { data: read(1), rows: p, cols: a },
|
|
478
|
+
xLoadings: { data: read(2), rows: p, cols: a },
|
|
479
|
+
yLoadings: { data: read(3), rows: q, cols: a },
|
|
480
|
+
xMean: read(4),
|
|
481
|
+
xScale: read(5),
|
|
482
|
+
};
|
|
483
|
+
});
|
|
484
|
+
}
|
|
485
|
+
finally {
|
|
486
|
+
allocs.forEach((ptr) => m._free(ptr));
|
|
487
|
+
}
|
|
488
|
+
}
|
|
489
|
+
/**
|
|
490
|
+
* Importance profile (nFeaturesIn values) on rows X given in this
|
|
491
|
+
* estimator's input space (normally the preprocessed training rows):
|
|
492
|
+
* VIP, target-projection selectivity ratio or standardized coefficients
|
|
493
|
+
* (ddof = 1), computed natively.
|
|
494
|
+
*/
|
|
495
|
+
modelImportance(X, options) {
|
|
496
|
+
const kind = IMPORTANCE_KINDS[options?.kind];
|
|
497
|
+
if (kind === undefined)
|
|
498
|
+
throw new Error(`unknown importance kind ${String(options?.kind)}`);
|
|
499
|
+
const outputIndex = options.outputIndex ?? 0;
|
|
500
|
+
if (!Number.isSafeInteger(outputIndex) || outputIndex < 0) {
|
|
501
|
+
throw new Error("outputIndex must be a nonnegative integer");
|
|
502
|
+
}
|
|
503
|
+
checkMatrix("X", X);
|
|
504
|
+
const m = getModule();
|
|
505
|
+
const handle = this.handle();
|
|
506
|
+
const p = this.dim("n4m_estimator_n_features_in", handle);
|
|
507
|
+
const xv = makeMatrixView(X.data, X.rows, X.cols);
|
|
508
|
+
const out = m._malloc(Math.max(1, p) * 8);
|
|
509
|
+
try {
|
|
510
|
+
withContext((ctx) => checkStatus(m.ccall("n4m_estimator_importance_v1", "number", ["number", "number", "number", "number", "i64", "number", "i64"], [ctx, handle, xv.viewPtr, kind, BigInt(outputIndex), out, BigInt(p)]), ctx));
|
|
511
|
+
return m.HEAPF64.slice(out / 8, out / 8 + p);
|
|
512
|
+
}
|
|
513
|
+
finally {
|
|
514
|
+
xv.free();
|
|
515
|
+
m._free(out);
|
|
516
|
+
}
|
|
517
|
+
}
|
|
518
|
+
dim(symbol, handle) {
|
|
519
|
+
const m = getModule();
|
|
520
|
+
const ptr = m._malloc(8);
|
|
521
|
+
try {
|
|
522
|
+
checkStatus(m.ccall(symbol, "number", ["number", "number"], [handle, ptr]));
|
|
523
|
+
return readI64(ptr);
|
|
524
|
+
}
|
|
525
|
+
finally {
|
|
526
|
+
m._free(ptr);
|
|
527
|
+
}
|
|
528
|
+
}
|
|
427
529
|
/** Releases the native estimator. */
|
|
428
530
|
dispose() {
|
|
429
531
|
if (this.ptr !== 0) {
|
|
@@ -550,6 +652,9 @@ export class NativeEstimator extends NativeMethod {
|
|
|
550
652
|
}
|
|
551
653
|
}
|
|
552
654
|
}
|
|
655
|
+
const IMPORTANCE_KINDS = {
|
|
656
|
+
vip: 0, selectivity_ratio: 1, standardized_coefficients: 2,
|
|
657
|
+
};
|
|
553
658
|
/** Base of the generated procedures: one native run, no fitted state. */
|
|
554
659
|
export class NativeProcedure extends NativeMethod {
|
|
555
660
|
runRaw(X, y, inputs, read) {
|
|
@@ -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.24.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 {
|
package/dist/explain.d.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { type Matrix } from "./types.js";
|
|
2
|
-
|
|
2
|
+
import type { ModelImportanceOptions, NativeEstimator } from "./estimatorRoles.js";
|
|
3
|
+
export type ExplainMethod = "exact_shap" | "permutation_shap" | "kernel_shap" | "lime" | "occlusion" | "gradient";
|
|
3
4
|
export type ExplainBaseline = "background" | "mean" | "interpolate";
|
|
4
5
|
export type AttributionKind = ExplainMethod | "linear_shap" | "tree_shap";
|
|
5
6
|
export interface ExplainOptions {
|
|
@@ -19,6 +20,8 @@ export interface ExplainOptions {
|
|
|
19
20
|
maxBatchRows?: number;
|
|
20
21
|
/** Sampling seed: a nonnegative integer < 2^53 (default 0). */
|
|
21
22
|
seed?: number;
|
|
23
|
+
/** "gradient" only: relative central-difference step, h_j = gradientStep * s_j (default 1e-3). */
|
|
24
|
+
gradientStep?: number;
|
|
22
25
|
}
|
|
23
26
|
/** rows: row-major nRows x nFeatures in the explained feature space.
|
|
24
27
|
* Returns nRows x nOutputs row-major predictions. */
|
|
@@ -74,6 +77,12 @@ export interface AttributionResult {
|
|
|
74
77
|
version: string;
|
|
75
78
|
abi: string;
|
|
76
79
|
};
|
|
80
|
+
/** "gradient" only: per-row gradients [row][feature][output]. */
|
|
81
|
+
gradients?: Float64Array;
|
|
82
|
+
/** "gradient" only: mean over the explained rows of the gradients, [feature][output]. */
|
|
83
|
+
meanGradient?: Float64Array;
|
|
84
|
+
/** "gradient" only: absolute finite-difference step of each feature. */
|
|
85
|
+
gradientSteps?: Float64Array;
|
|
77
86
|
}
|
|
78
87
|
export interface FlatTreeEnsemble {
|
|
79
88
|
/** nTrees + 1 offsets; tree t owns nodes [treeOffsets[t], treeOffsets[t+1]). */
|
|
@@ -117,8 +126,43 @@ export declare function groupsFixedWidth(nFeatures: number, width: number): Feat
|
|
|
117
126
|
/** Partition from half-open [start, end) feature-index ranges. Range r becomes
|
|
118
127
|
* group r; every maximal uncovered run becomes one further group. */
|
|
119
128
|
export declare function groupsFromRanges(nFeatures: number, ranges: ReadonlyArray<readonly [number, number]>): FeatureGrouping;
|
|
120
|
-
/** Per-group mean |attribution| and mean signed attribution over rows
|
|
129
|
+
/** Per-group mean |attribution| and mean signed attribution over rows; with
|
|
130
|
+
* a stdError (permutation SHAP), the Monte-Carlo standard error of the mean
|
|
131
|
+
* signed attribution sqrt(sum_r se_rg^2) / nRows, else null. */
|
|
121
132
|
export declare function summarizeAttributions(result: AttributionResult, outputIndex?: number): {
|
|
122
133
|
meanAbs: Float64Array;
|
|
123
134
|
meanSigned: Float64Array;
|
|
135
|
+
meanSignedStdError: Float64Array | null;
|
|
136
|
+
};
|
|
137
|
+
/**
|
|
138
|
+
* The rows an explanation session sends to the model for one coalition:
|
|
139
|
+
* every row of X with the features of `absentGroups` filled by the baseline
|
|
140
|
+
* (the session's own native filling code). "background" returns
|
|
141
|
+
* X.rows * background.rows rows (row i, background row b at i * nBackground + b);
|
|
142
|
+
* "mean" and "interpolate" one row per row of X.
|
|
143
|
+
*/
|
|
144
|
+
export declare function perturbRows(input: {
|
|
145
|
+
X: Matrix;
|
|
146
|
+
background?: Matrix;
|
|
147
|
+
grouping: FeatureGrouping;
|
|
148
|
+
absentGroups: number[];
|
|
149
|
+
baseline: ExplainBaseline;
|
|
150
|
+
}): Matrix;
|
|
151
|
+
export type ProfileAggregation = "sum" | "mean" | "sum_abs" | "mean_abs" | "max_abs";
|
|
152
|
+
/** Native importance profile of a fitted estimator on rows of its input space
|
|
153
|
+
* (VIP, target-projection selectivity ratio, standardized coefficients). */
|
|
154
|
+
export declare function modelImportance(est: NativeEstimator, X: Matrix, options: ModelImportanceOptions): Float64Array;
|
|
155
|
+
/** Aggregates a per-feature profile (no NaN; +-inf kept) over a feature grouping. */
|
|
156
|
+
export declare function aggregateProfile(values: Float64Array, grouping: FeatureGrouping, rule: ProfileAggregation): Float64Array;
|
|
157
|
+
/**
|
|
158
|
+
* Pairwise agreement of m profiles (rows of an m x G matrix, G >= 2, no NaN):
|
|
159
|
+
* Spearman correlation of average ranks (equals scipy.stats.spearmanr; NaN for
|
|
160
|
+
* a constant profile) and the Jaccard overlap of the top-K entries by |value|
|
|
161
|
+
* (lowest index on ties; default K = 10).
|
|
162
|
+
*/
|
|
163
|
+
export declare function compareProfiles(profiles: Matrix, options?: {
|
|
164
|
+
topK?: number;
|
|
165
|
+
}): {
|
|
166
|
+
spearman: Matrix;
|
|
167
|
+
topKJaccard: Matrix;
|
|
124
168
|
};
|
package/dist/explain.js
CHANGED
|
@@ -10,13 +10,13 @@ import { checkStatus, getModule, makeMatrixView } from "./ffi.js";
|
|
|
10
10
|
import { N4mError, Status } from "./types.js";
|
|
11
11
|
// ---- enum codes (explain.h) ------------------------------------------------
|
|
12
12
|
const METHOD_CODES = {
|
|
13
|
-
exact_shap: 0, permutation_shap: 1, kernel_shap: 2, lime: 3, occlusion: 4,
|
|
13
|
+
exact_shap: 0, permutation_shap: 1, kernel_shap: 2, lime: 3, occlusion: 4, gradient: 5,
|
|
14
14
|
};
|
|
15
15
|
const BASELINE_CODES = {
|
|
16
16
|
background: 0, mean: 1, interpolate: 2,
|
|
17
17
|
};
|
|
18
18
|
const OPTION_KEYS = new Set(["method", "baseline", "nPermutations", "nCoalitions",
|
|
19
|
-
"limeKernelWidth", "limeRidge", "maxBatchRows", "seed"]);
|
|
19
|
+
"limeKernelWidth", "limeRidge", "maxBatchRows", "seed", "gradientStep"]);
|
|
20
20
|
// ---- n4m_explain_options_v1_t layout (identical on wasm32 and LP64) ---------
|
|
21
21
|
// uint64 struct_size @0, int32 method @8, int32 baseline @12,
|
|
22
22
|
// int64 n_outputs @16, n_permutations @24, n_coalitions @32,
|
|
@@ -145,6 +145,7 @@ function sessionExactness(method, nCoalitions, nGroups) {
|
|
|
145
145
|
case "permutation_shap": return "sampled";
|
|
146
146
|
case "lime": return "surrogate";
|
|
147
147
|
case "occlusion": return "perturbation";
|
|
148
|
+
case "gradient": return "perturbation"; // central finite differences
|
|
148
149
|
}
|
|
149
150
|
}
|
|
150
151
|
// ---- ask/tell session --------------------------------------------------------
|
|
@@ -181,6 +182,10 @@ export async function explainModel(input) {
|
|
|
181
182
|
if (!Number.isSafeInteger(seed) || seed < 0) {
|
|
182
183
|
throw new Error("seed must be a nonnegative integer below 2^53");
|
|
183
184
|
}
|
|
185
|
+
if (options.gradientStep !== undefined &&
|
|
186
|
+
(!Number.isFinite(options.gradientStep) || options.gradientStep <= 0)) {
|
|
187
|
+
throw new Error("gradientStep must be finite and > 0");
|
|
188
|
+
}
|
|
184
189
|
for (const key of ["limeKernelWidth", "limeRidge"]) {
|
|
185
190
|
if (options[key] !== undefined && !Number.isFinite(options[key])) {
|
|
186
191
|
throw new Error(`${key} must be finite`);
|
|
@@ -198,6 +203,9 @@ export async function explainModel(input) {
|
|
|
198
203
|
else if (baseline !== "interpolate") {
|
|
199
204
|
throw new Error(`the ${baseline} baseline requires a background matrix`);
|
|
200
205
|
}
|
|
206
|
+
if (method === "gradient" && baseline === "interpolate") {
|
|
207
|
+
throw new Error("the gradient method uses the background mean reference (background or mean baseline)");
|
|
208
|
+
}
|
|
201
209
|
const nGroupsIn = checkGrouping(grouping, nFeatures);
|
|
202
210
|
if (signal?.aborted)
|
|
203
211
|
throw abortError();
|
|
@@ -251,6 +259,9 @@ export async function explainModel(input) {
|
|
|
251
259
|
checkStatus(m.ccall("n4m_explain_session_create_v1", "number", ["number", "number", "number", "number", "i64", "number", "number"], [ctx.handle, xView.viewPtr, bgView.viewPtr, groupPtr,
|
|
252
260
|
BigInt(nGroupsIn), opt, outSession]), ctx.handle);
|
|
253
261
|
session = m.getValue(outSession, "i32");
|
|
262
|
+
if (method === "gradient" && options.gradientStep !== undefined) {
|
|
263
|
+
checkStatus(m.ccall("n4m_explain_session_set_gradient_step_v1", "number", ["number", "number", "number"], [ctx.handle, session, options.gradientStep]), ctx.handle);
|
|
264
|
+
}
|
|
254
265
|
const info = arena.alloc(5 * 8);
|
|
255
266
|
checkStatus(m.ccall("n4m_explain_session_info_v1", "number", Array(6).fill("number"), [session, info, info + 8, info + 16, info + 24, info + 32]));
|
|
256
267
|
const nRows = readI64(info), nGroups = readI64(info + 16);
|
|
@@ -292,17 +303,33 @@ export async function explainModel(input) {
|
|
|
292
303
|
const attributions = readF64(attrPtr, attrSize);
|
|
293
304
|
const expected = readF64(expPtr, outSize);
|
|
294
305
|
const predictions = readF64(predOutPtr, outSize);
|
|
295
|
-
const
|
|
306
|
+
const gradient = method === "gradient";
|
|
307
|
+
let gradientOut = {};
|
|
308
|
+
if (gradient) {
|
|
309
|
+
const gradSize = nRows * nFeatures * nOutputs, meanSize = nFeatures * nOutputs;
|
|
310
|
+
const gradPtr = arena.alloc(gradSize * 8), meanPtr = arena.alloc(meanSize * 8);
|
|
311
|
+
const stepPtr = arena.alloc(nFeatures * 8);
|
|
312
|
+
checkStatus(m.ccall("n4m_explain_session_gradients_v1", "number", ["number", "number", "number", "i64", "number", "i64", "number", "i64"], [ctx.handle, session, gradPtr, BigInt(gradSize), meanPtr, BigInt(meanSize), stepPtr,
|
|
313
|
+
BigInt(nFeatures)]), ctx.handle);
|
|
314
|
+
gradientOut = {
|
|
315
|
+
gradients: readF64(gradPtr, gradSize),
|
|
316
|
+
meanGradient: readF64(meanPtr, meanSize),
|
|
317
|
+
gradientSteps: readF64(stepPtr, nFeatures),
|
|
318
|
+
};
|
|
319
|
+
}
|
|
320
|
+
const additive = method !== "lime" && method !== "occlusion" && !gradient;
|
|
296
321
|
return {
|
|
297
322
|
kind: method,
|
|
298
323
|
baseline,
|
|
299
324
|
exactness: sessionExactness(method, nCoalitions, nGroups),
|
|
300
325
|
additive,
|
|
301
|
-
|
|
326
|
+
// Gradient groups are sums of per-feature first-order terms.
|
|
327
|
+
groupAggregation: gradient ? "sum_of_feature_values" : "group_game",
|
|
302
328
|
nRows, nGroups, nOutputs, nFeatures,
|
|
303
329
|
attributions, expected, predictions,
|
|
304
330
|
stdError: hasStdError ? readF64(stdPtr, attrSize) : null,
|
|
305
|
-
|
|
331
|
+
// Reported diagnostic; the gradient method is not additive in general.
|
|
332
|
+
additivityMaxAbsError: additive || gradient
|
|
306
333
|
? additivityError(attributions, expected, predictions, nRows, nGroups, nOutputs)
|
|
307
334
|
: null,
|
|
308
335
|
evaluations,
|
|
@@ -318,8 +345,11 @@ export async function explainModel(input) {
|
|
|
318
345
|
seed,
|
|
319
346
|
n_outputs_inferred: input.nOutputs === undefined,
|
|
320
347
|
total_evaluations: total,
|
|
348
|
+
gradient_step: gradient ? (options.gradientStep ?? 1e-3) : null,
|
|
349
|
+
reference: gradient ? "background_mean" : null,
|
|
321
350
|
},
|
|
322
351
|
engine: engineInfo(),
|
|
352
|
+
...gradientOut,
|
|
323
353
|
};
|
|
324
354
|
}
|
|
325
355
|
finally {
|
|
@@ -530,9 +560,14 @@ export function groupsFromRanges(nFeatures, ranges) {
|
|
|
530
560
|
arena.free();
|
|
531
561
|
}
|
|
532
562
|
}
|
|
533
|
-
/** Per-group mean |attribution| and mean signed attribution over rows
|
|
563
|
+
/** Per-group mean |attribution| and mean signed attribution over rows; with
|
|
564
|
+
* a stdError (permutation SHAP), the Monte-Carlo standard error of the mean
|
|
565
|
+
* signed attribution sqrt(sum_r se_rg^2) / nRows, else null. */
|
|
534
566
|
export function summarizeAttributions(result, outputIndex = 0) {
|
|
535
|
-
const { nRows, nGroups, nOutputs, attributions } = result;
|
|
567
|
+
const { nRows, nGroups, nOutputs, attributions, stdError } = result;
|
|
568
|
+
if (stdError != null && (!(stdError instanceof Float64Array) || stdError.length !== attributions.length)) {
|
|
569
|
+
throw new Error("result.stdError must match result.attributions");
|
|
570
|
+
}
|
|
536
571
|
if (!(attributions instanceof Float64Array) || attributions.length !== nRows * nGroups * nOutputs) {
|
|
537
572
|
throw new Error("result.attributions must hold nRows * nGroups * nOutputs values");
|
|
538
573
|
}
|
|
@@ -546,9 +581,139 @@ export function summarizeAttributions(result, outputIndex = 0) {
|
|
|
546
581
|
const absPtr = arena.alloc(nGroups * 8), signedPtr = arena.alloc(nGroups * 8);
|
|
547
582
|
checkStatus(m.ccall("n4m_explain_summarize_v1", "number", ["number", "i64", "i64", "i64", "i64", "number", "number", "i64"], [attrPtr, BigInt(nRows), BigInt(nGroups), BigInt(nOutputs), BigInt(outputIndex),
|
|
548
583
|
absPtr, signedPtr, BigInt(nGroups)]));
|
|
549
|
-
|
|
584
|
+
let meanSignedStdError = null;
|
|
585
|
+
if (stdError != null) {
|
|
586
|
+
const sePtr = arena.f64(stdError), outPtr = arena.alloc(nGroups * 8);
|
|
587
|
+
checkStatus(m.ccall("n4m_explain_summarize_std_error_v1", "number", ["number", "i64", "i64", "i64", "i64", "number", "i64"], [sePtr, BigInt(nRows), BigInt(nGroups), BigInt(nOutputs), BigInt(outputIndex),
|
|
588
|
+
outPtr, BigInt(nGroups)]));
|
|
589
|
+
meanSignedStdError = readF64(outPtr, nGroups);
|
|
590
|
+
}
|
|
591
|
+
return { meanAbs: readF64(absPtr, nGroups), meanSigned: readF64(signedPtr, nGroups),
|
|
592
|
+
meanSignedStdError };
|
|
593
|
+
}
|
|
594
|
+
finally {
|
|
595
|
+
arena.free();
|
|
596
|
+
}
|
|
597
|
+
}
|
|
598
|
+
// ---- coalition rows (baseline preview) ---------------------------------------
|
|
599
|
+
/**
|
|
600
|
+
* The rows an explanation session sends to the model for one coalition:
|
|
601
|
+
* every row of X with the features of `absentGroups` filled by the baseline
|
|
602
|
+
* (the session's own native filling code). "background" returns
|
|
603
|
+
* X.rows * background.rows rows (row i, background row b at i * nBackground + b);
|
|
604
|
+
* "mean" and "interpolate" one row per row of X.
|
|
605
|
+
*/
|
|
606
|
+
export function perturbRows(input) {
|
|
607
|
+
const { X, background, grouping, absentGroups, baseline } = input;
|
|
608
|
+
checkMatrix("X", X);
|
|
609
|
+
if (!Object.prototype.hasOwnProperty.call(BASELINE_CODES, baseline)) {
|
|
610
|
+
throw new Error(`unknown explain baseline ${baseline}`);
|
|
611
|
+
}
|
|
612
|
+
if (background !== undefined) {
|
|
613
|
+
checkMatrix("background", background, true);
|
|
614
|
+
if (background.cols !== X.cols)
|
|
615
|
+
throw new Error("background must have X.cols columns");
|
|
616
|
+
}
|
|
617
|
+
else if (baseline !== "interpolate") {
|
|
618
|
+
throw new Error(`the ${baseline} baseline requires a background matrix`);
|
|
619
|
+
}
|
|
620
|
+
const nGroups = checkGrouping(grouping, X.cols);
|
|
621
|
+
if (!Array.isArray(absentGroups))
|
|
622
|
+
throw new Error("absentGroups must be an array of group indices");
|
|
623
|
+
checkIntegers("absentGroups", absentGroups, absentGroups.length);
|
|
624
|
+
const m = getModule();
|
|
625
|
+
const arena = new Arena();
|
|
626
|
+
let ctx = null;
|
|
627
|
+
let xView = null;
|
|
628
|
+
let bgView = null;
|
|
629
|
+
try {
|
|
630
|
+
ctx = Context.create();
|
|
631
|
+
xView = makeMatrixView(X.data, X.rows, X.cols);
|
|
632
|
+
bgView = background !== undefined
|
|
633
|
+
? makeMatrixView(background.data, background.rows, background.cols) : null;
|
|
634
|
+
const groupPtr = arena.int64(grouping.featureGroup);
|
|
635
|
+
const absentPtr = arena.int64(absentGroups);
|
|
636
|
+
const countPtr = arena.alloc(8);
|
|
637
|
+
const call = (outPtr, capacity) => checkStatus(m.ccall("n4m_explain_perturb_rows_v1", "number", ["number", "number", "number", "number", "i64", "number", "number", "i64", "number", "i64",
|
|
638
|
+
"number"], [ctx.handle, xView.viewPtr, bgView ? bgView.viewPtr : 0, groupPtr, BigInt(nGroups),
|
|
639
|
+
BASELINE_CODES[baseline], absentPtr, BigInt(absentGroups.length), outPtr, BigInt(capacity),
|
|
640
|
+
countPtr]), ctx.handle);
|
|
641
|
+
call(0, 0);
|
|
642
|
+
const rows = readI64(countPtr);
|
|
643
|
+
const outPtr = arena.alloc(rows * X.cols * 8);
|
|
644
|
+
call(outPtr, rows);
|
|
645
|
+
return { data: readF64(outPtr, rows * X.cols), rows, cols: X.cols };
|
|
646
|
+
}
|
|
647
|
+
finally {
|
|
648
|
+
bgView?.free();
|
|
649
|
+
xView?.free();
|
|
650
|
+
arena.free();
|
|
651
|
+
ctx?.destroy();
|
|
652
|
+
}
|
|
653
|
+
}
|
|
654
|
+
const AGGREGATION_CODES = {
|
|
655
|
+
sum: 0, mean: 1, sum_abs: 2, mean_abs: 3, max_abs: 4,
|
|
656
|
+
};
|
|
657
|
+
/** Native importance profile of a fitted estimator on rows of its input space
|
|
658
|
+
* (VIP, target-projection selectivity ratio, standardized coefficients). */
|
|
659
|
+
export function modelImportance(est, X, options) {
|
|
660
|
+
return est.modelImportance(X, options);
|
|
661
|
+
}
|
|
662
|
+
/** Aggregates a per-feature profile (no NaN; +-inf kept) over a feature grouping. */
|
|
663
|
+
export function aggregateProfile(values, grouping, rule) {
|
|
664
|
+
if (!(values instanceof Float64Array) || values.length < 1) {
|
|
665
|
+
throw new Error("values must be a non-empty Float64Array");
|
|
666
|
+
}
|
|
667
|
+
const code = AGGREGATION_CODES[rule];
|
|
668
|
+
if (code === undefined)
|
|
669
|
+
throw new Error(`unknown profile aggregation ${String(rule)}`);
|
|
670
|
+
const nGroups = checkGrouping(grouping, values.length);
|
|
671
|
+
const m = getModule();
|
|
672
|
+
const arena = new Arena();
|
|
673
|
+
let ctx = null;
|
|
674
|
+
try {
|
|
675
|
+
ctx = Context.create();
|
|
676
|
+
const valuesPtr = arena.f64(values);
|
|
677
|
+
const groupPtr = arena.int64(grouping.featureGroup);
|
|
678
|
+
const outPtr = arena.alloc(nGroups * 8);
|
|
679
|
+
checkStatus(m.ccall("n4m_explain_aggregate_profile_v1", "number", ["number", "number", "i64", "number", "i64", "number", "number", "i64"], [ctx.handle, valuesPtr, BigInt(values.length), groupPtr, BigInt(nGroups), code, outPtr,
|
|
680
|
+
BigInt(nGroups)]), ctx.handle);
|
|
681
|
+
return readF64(outPtr, nGroups);
|
|
550
682
|
}
|
|
551
683
|
finally {
|
|
552
684
|
arena.free();
|
|
685
|
+
ctx?.destroy();
|
|
686
|
+
}
|
|
687
|
+
}
|
|
688
|
+
/**
|
|
689
|
+
* Pairwise agreement of m profiles (rows of an m x G matrix, G >= 2, no NaN):
|
|
690
|
+
* Spearman correlation of average ranks (equals scipy.stats.spearmanr; NaN for
|
|
691
|
+
* a constant profile) and the Jaccard overlap of the top-K entries by |value|
|
|
692
|
+
* (lowest index on ties; default K = 10).
|
|
693
|
+
*/
|
|
694
|
+
export function compareProfiles(profiles, options = {}) {
|
|
695
|
+
checkMatrix("profiles", profiles);
|
|
696
|
+
const topK = options.topK ?? 10;
|
|
697
|
+
if (!Number.isSafeInteger(topK) || topK < 1)
|
|
698
|
+
throw new Error("topK must be a positive integer");
|
|
699
|
+
const n = profiles.rows;
|
|
700
|
+
const m = getModule();
|
|
701
|
+
const arena = new Arena();
|
|
702
|
+
let ctx = null;
|
|
703
|
+
let view = null;
|
|
704
|
+
try {
|
|
705
|
+
ctx = Context.create();
|
|
706
|
+
view = makeMatrixView(profiles.data, profiles.rows, profiles.cols);
|
|
707
|
+
const rhoPtr = arena.alloc(n * n * 8), jacPtr = arena.alloc(n * n * 8);
|
|
708
|
+
checkStatus(m.ccall("n4m_explain_compare_profiles_v1", "number", ["number", "number", "i64", "number", "i64", "number", "i64"], [ctx.handle, view.viewPtr, BigInt(topK), rhoPtr, BigInt(n * n), jacPtr, BigInt(n * n)]), ctx.handle);
|
|
709
|
+
return {
|
|
710
|
+
spearman: { data: readF64(rhoPtr, n * n), rows: n, cols: n },
|
|
711
|
+
topKJaccard: { data: readF64(jacPtr, n * n), rows: n, cols: n },
|
|
712
|
+
};
|
|
713
|
+
}
|
|
714
|
+
finally {
|
|
715
|
+
view?.free();
|
|
716
|
+
arena.free();
|
|
717
|
+
ctx?.destroy();
|
|
553
718
|
}
|
|
554
719
|
}
|
package/dist/index.d.ts
CHANGED
|
@@ -8,7 +8,7 @@ export { Model, fitPls, predictPls, fitModel, predictModel, fitAom, fitAomChain,
|
|
|
8
8
|
export { ppCreate, ppFit, ppTransform, ppGetState, ppSetState, ppDestroy, type PpOperator, } from "./preprocessing.js";
|
|
9
9
|
export { MethodResult } from "./methodResult.js";
|
|
10
10
|
export { NativeModel, type ComponentResolution } from "./nativeModel.js";
|
|
11
|
-
export { NativeEstimator, NativeMethod, NativeProcedure, manifest, methodClass, type Augmenter, type Classifier, type FitInputs, type Fold, type ParamType, type ParamValue, type ProbabilisticClassifier, type Procedure, type ProcedureOutput, type Regressor, type SampleFilter, type Selector, type Splitter, type TargetMixingAugmenter, type Transformer } from "./estimatorRoles.js";
|
|
11
|
+
export { NativeEstimator, NativeMethod, NativeProcedure, manifest, methodClass, type AffineCoefficients, type LatentStructure, type ModelImportanceKind, type ModelImportanceOptions, type Augmenter, type Classifier, type FitInputs, type Fold, type ParamType, type ParamValue, type ProbabilisticClassifier, type Procedure, type ProcedureOutput, type Regressor, type SampleFilter, type Selector, type Splitter, type TargetMixingAugmenter, type Transformer } from "./estimatorRoles.js";
|
|
12
12
|
export * from "./estimatorRolesGenerated.js";
|
|
13
13
|
export { RolePipeline, type ClassLabel, type PipelineRole, type RolePipelineState, type RolePipelineStepInfo, type RoleStep } from "./rolePipeline.js";
|
|
14
14
|
export { MultimodalPipeline, MultimodalClassifierPipeline, type MultimodalClassLabel, type MultimodalRecipe, type MultimodalSourceSchema, type MultimodalSourceSchemas, type MultimodalBlocks, type RawTensor } from "./multimodalPipeline.js";
|
|
@@ -24,4 +24,4 @@ export declare function version(): string;
|
|
|
24
24
|
export declare function abiVersion(): readonly [number, number, number];
|
|
25
25
|
export { rank, type RankingMethod, type RankingOptions, type RankingCandidate, type RankingResult } from "./ranking.js";
|
|
26
26
|
export { mixedEffects, fanova, normalizeLoss, type MixedEffectsOptions, type MixedEffectsResult, type FanovaOptions, type FanovaResult } from "./componentAnalysis.js";
|
|
27
|
-
export { explainModel, linearShap, treeShap, groupsFixedWidth, groupsFromRanges, summarizeAttributions, type ExplainMethod, type ExplainBaseline, type AttributionKind, type ExplainOptions, type PredictBatch, type FeatureGrouping, type ExplainModelInput, type AttributionResult, type FlatTreeEnsemble } from "./explain.js";
|
|
27
|
+
export { explainModel, linearShap, treeShap, groupsFixedWidth, groupsFromRanges, summarizeAttributions, perturbRows, modelImportance, aggregateProfile, compareProfiles, type ProfileAggregation, type ExplainMethod, type ExplainBaseline, type AttributionKind, type ExplainOptions, type PredictBatch, type FeatureGrouping, type ExplainModelInput, type AttributionResult, type FlatTreeEnsemble } from "./explain.js";
|
package/dist/index.js
CHANGED
|
@@ -47,4 +47,4 @@ export function abiVersion() {
|
|
|
47
47
|
}
|
|
48
48
|
export { rank } from "./ranking.js";
|
|
49
49
|
export { mixedEffects, fanova, normalizeLoss } from "./componentAnalysis.js";
|
|
50
|
-
export { explainModel, linearShap, treeShap, groupsFixedWidth, groupsFromRanges, summarizeAttributions } from "./explain.js";
|
|
50
|
+
export { explainModel, linearShap, treeShap, groupsFixedWidth, groupsFromRanges, summarizeAttributions, perturbRows, modelImportance, aggregateProfile, compareProfiles } from "./explain.js";
|