@ac-kit/math-stats 0.5.0 → 0.7.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/CHANGELOG.md +205 -0
- package/README.md +86 -6
- package/dist/_digamma.d.ts +10 -0
- package/dist/_digamma.d.ts.map +1 -0
- package/dist/_digamma.js +38 -0
- package/dist/_digamma.js.map +1 -0
- package/dist/_dilogarithm.d.ts +14 -0
- package/dist/_dilogarithm.d.ts.map +1 -0
- package/dist/_dilogarithm.js +77 -0
- package/dist/_dilogarithm.js.map +1 -0
- package/dist/_histogram-rules.d.ts +15 -0
- package/dist/_histogram-rules.d.ts.map +1 -0
- package/dist/_histogram-rules.js +208 -0
- package/dist/_histogram-rules.js.map +1 -0
- package/dist/_incomplete-gamma-shape-derivative.d.ts +17 -0
- package/dist/_incomplete-gamma-shape-derivative.d.ts.map +1 -0
- package/dist/_incomplete-gamma-shape-derivative.js +90 -0
- package/dist/_incomplete-gamma-shape-derivative.js.map +1 -0
- package/dist/_logistic.d.ts +14 -0
- package/dist/_logistic.d.ts.map +1 -0
- package/dist/_logistic.js +29 -0
- package/dist/_logistic.js.map +1 -0
- package/dist/_normal-tail.d.ts +43 -0
- package/dist/_normal-tail.d.ts.map +1 -0
- package/dist/_normal-tail.js +124 -0
- package/dist/_normal-tail.js.map +1 -0
- package/dist/_rank-test.d.ts +71 -0
- package/dist/_rank-test.d.ts.map +1 -0
- package/dist/_rank-test.js +130 -0
- package/dist/_rank-test.js.map +1 -0
- package/dist/average.js +2 -2
- package/dist/average.js.map +1 -1
- package/dist/bootstrap.d.ts +67 -0
- package/dist/bootstrap.d.ts.map +1 -0
- package/dist/bootstrap.js +154 -0
- package/dist/bootstrap.js.map +1 -0
- package/dist/censored-logistic-distribution.d.ts +23 -0
- package/dist/censored-logistic-distribution.d.ts.map +1 -0
- package/dist/censored-logistic-distribution.js +63 -0
- package/dist/censored-logistic-distribution.js.map +1 -0
- package/dist/censored-shifted-gamma-distribution.d.ts +23 -0
- package/dist/censored-shifted-gamma-distribution.d.ts.map +1 -0
- package/dist/censored-shifted-gamma-distribution.js +73 -0
- package/dist/censored-shifted-gamma-distribution.js.map +1 -0
- package/dist/confidence-interval.d.ts +53 -0
- package/dist/confidence-interval.d.ts.map +1 -1
- package/dist/confidence-interval.js +73 -0
- package/dist/confidence-interval.js.map +1 -1
- package/dist/correlation.d.ts +41 -0
- package/dist/correlation.d.ts.map +1 -1
- package/dist/correlation.js +168 -2
- package/dist/correlation.js.map +1 -1
- package/dist/descriptive.d.ts +129 -0
- package/dist/descriptive.d.ts.map +1 -0
- package/dist/descriptive.js +289 -0
- package/dist/descriptive.js.map +1 -0
- package/dist/forecast/_forecast-checks.d.ts +30 -0
- package/dist/forecast/_forecast-checks.d.ts.map +1 -0
- package/dist/forecast/_forecast-checks.js +119 -0
- package/dist/forecast/_forecast-checks.js.map +1 -0
- package/dist/forecast/_score-kernels.d.ts +63 -0
- package/dist/forecast/_score-kernels.d.ts.map +1 -0
- package/dist/forecast/_score-kernels.js +264 -0
- package/dist/forecast/_score-kernels.js.map +1 -0
- package/dist/forecast/brier-score.d.ts +102 -0
- package/dist/forecast/brier-score.d.ts.map +1 -0
- package/dist/forecast/brier-score.js +163 -0
- package/dist/forecast/brier-score.js.map +1 -0
- package/dist/forecast/crps-closed-form.d.ts +64 -0
- package/dist/forecast/crps-closed-form.d.ts.map +1 -0
- package/dist/forecast/crps-closed-form.js +106 -0
- package/dist/forecast/crps-closed-form.js.map +1 -0
- package/dist/forecast/crps-ensemble.d.ts +53 -0
- package/dist/forecast/crps-ensemble.d.ts.map +1 -0
- package/dist/forecast/crps-ensemble.js +121 -0
- package/dist/forecast/crps-ensemble.js.map +1 -0
- package/dist/forecast/emos.d.ts +158 -0
- package/dist/forecast/emos.d.ts.map +1 -0
- package/dist/forecast/emos.js +397 -0
- package/dist/forecast/emos.js.map +1 -0
- package/dist/forecast/exceedance-probability.d.ts +54 -0
- package/dist/forecast/exceedance-probability.d.ts.map +1 -0
- package/dist/forecast/exceedance-probability.js +125 -0
- package/dist/forecast/exceedance-probability.js.map +1 -0
- package/dist/forecast/log-score.d.ts +18 -0
- package/dist/forecast/log-score.d.ts.map +1 -0
- package/dist/forecast/log-score.js +19 -0
- package/dist/forecast/log-score.js.map +1 -0
- package/dist/forecast/logistic-regression.d.ts +123 -0
- package/dist/forecast/logistic-regression.d.ts.map +1 -0
- package/dist/forecast/logistic-regression.js +282 -0
- package/dist/forecast/logistic-regression.js.map +1 -0
- package/dist/forecast/rank-histogram.d.ts +32 -0
- package/dist/forecast/rank-histogram.d.ts.map +1 -0
- package/dist/forecast/rank-histogram.js +63 -0
- package/dist/forecast/rank-histogram.js.map +1 -0
- package/dist/forecast/reliability-diagram.d.ts +70 -0
- package/dist/forecast/reliability-diagram.d.ts.map +1 -0
- package/dist/forecast/reliability-diagram.js +126 -0
- package/dist/forecast/reliability-diagram.js.map +1 -0
- package/dist/forecast/roc-curve.d.ts +58 -0
- package/dist/forecast/roc-curve.d.ts.map +1 -0
- package/dist/forecast/roc-curve.js +124 -0
- package/dist/forecast/roc-curve.js.map +1 -0
- package/dist/hierarchical-cluster.d.ts.map +1 -1
- package/dist/hierarchical-cluster.js +10 -5
- package/dist/hierarchical-cluster.js.map +1 -1
- package/dist/histogram-edges.d.ts +92 -0
- package/dist/histogram-edges.d.ts.map +1 -0
- package/dist/histogram-edges.js +325 -0
- package/dist/histogram-edges.js.map +1 -0
- package/dist/histogram.d.ts +55 -21
- package/dist/histogram.d.ts.map +1 -1
- package/dist/histogram.js +56 -83
- package/dist/histogram.js.map +1 -1
- package/dist/index.d.ts +23 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +23 -0
- package/dist/index.js.map +1 -1
- package/dist/kmeans.d.ts.map +1 -1
- package/dist/kmeans.js +11 -6
- package/dist/kmeans.js.map +1 -1
- package/dist/kmedoids.js +2 -1
- package/dist/kmedoids.js.map +1 -1
- package/dist/mann-whitney-u.d.ts +27 -0
- package/dist/mann-whitney-u.d.ts.map +1 -0
- package/dist/mann-whitney-u.js +94 -0
- package/dist/mann-whitney-u.js.map +1 -0
- package/dist/multiple-regression.d.ts +123 -0
- package/dist/multiple-regression.d.ts.map +1 -0
- package/dist/multiple-regression.js +208 -0
- package/dist/multiple-regression.js.map +1 -0
- package/dist/principal-components.d.ts +66 -0
- package/dist/principal-components.d.ts.map +1 -0
- package/dist/principal-components.js +105 -0
- package/dist/principal-components.js.map +1 -0
- package/dist/quantile.d.ts +113 -5
- package/dist/quantile.d.ts.map +1 -1
- package/dist/quantile.js +318 -19
- package/dist/quantile.js.map +1 -1
- package/dist/regression.d.ts +46 -0
- package/dist/regression.d.ts.map +1 -1
- package/dist/regression.js +99 -1
- package/dist/regression.js.map +1 -1
- package/dist/running-statistics.d.ts +103 -0
- package/dist/running-statistics.d.ts.map +1 -0
- package/dist/running-statistics.js +283 -0
- package/dist/running-statistics.js.map +1 -0
- package/dist/sample.d.ts +29 -0
- package/dist/sample.d.ts.map +1 -0
- package/dist/sample.js +39 -0
- package/dist/sample.js.map +1 -0
- package/dist/t-digest.d.ts +136 -0
- package/dist/t-digest.d.ts.map +1 -0
- package/dist/t-digest.js +424 -0
- package/dist/t-digest.js.map +1 -0
- package/dist/truncated-normal-distribution.d.ts +28 -0
- package/dist/truncated-normal-distribution.d.ts.map +1 -0
- package/dist/truncated-normal-distribution.js +198 -0
- package/dist/truncated-normal-distribution.js.map +1 -0
- package/dist/wilcoxon-signed-rank.d.ts +42 -0
- package/dist/wilcoxon-signed-rank.d.ts.map +1 -0
- package/dist/wilcoxon-signed-rank.js +117 -0
- package/dist/wilcoxon-signed-rank.js.map +1 -0
- package/package.json +14 -10
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The logarithmic (ignorance) score `−ln f(y)` of a forecast distribution at an
|
|
3
|
+
* observation (Good 1952): its negative log density there, in nats. Lower is
|
|
4
|
+
* better; strictly proper and local, it punishes an observation the forecast
|
|
5
|
+
* held impossible with `+∞`.
|
|
6
|
+
*
|
|
7
|
+
* For the censored laws of this package (`censoredLogisticDistribution`,
|
|
8
|
+
* `censoredShiftedGammaDistribution`), `density` at the censoring point is the
|
|
9
|
+
* point mass, so an observation there scores `−ln P(Y = bound)`: the mixed
|
|
10
|
+
* likelihood of censored regression. A discrete family scores `−ln P(Y = y)`.
|
|
11
|
+
*
|
|
12
|
+
* @param forecast The forecast distribution.
|
|
13
|
+
* @param observation The outcome; `NaN` gives `NaN`.
|
|
14
|
+
* @returns The score.
|
|
15
|
+
*/
|
|
16
|
+
export function logScore(forecast, observation) {
|
|
17
|
+
return -Math.log(forecast.density(observation));
|
|
18
|
+
}
|
|
19
|
+
//# sourceMappingURL=log-score.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"log-score.js","sourceRoot":"","sources":["../../src/forecast/log-score.ts"],"names":[],"mappings":"AAEA;;;;;;;;;;;;;;GAcG;AACH,MAAM,UAAU,QAAQ,CAAC,QAAsB,EAAE,WAAmB;IACnE,OAAO,CAAC,IAAI,CAAC,GAAG,CAAC,QAAQ,CAAC,OAAO,CAAC,WAAW,CAAC,CAAC,CAAC;AACjD,CAAC"}
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
import { type Matrix } from "@ac-kit/math-linear";
|
|
2
|
+
/**
|
|
3
|
+
* The penalty of a {@link logisticRegression}:
|
|
4
|
+
*
|
|
5
|
+
* - `"none"`: maximum likelihood. Under complete or quasi-complete separation (a
|
|
6
|
+
* predictor that splits the outcomes perfectly) it does not exist and the
|
|
7
|
+
* coefficients run off; {@link LogisticRegressionResult.separated} says so.
|
|
8
|
+
* - `"ridge"`: maximises `ℓ(β) − ½λ·Σⱼ βⱼ²` over the penalised columns, which
|
|
9
|
+
* shrinks the coefficients and always has a finite answer.
|
|
10
|
+
* - `"firth"`: maximises `ℓ(β) + ½ ln det I(β)`, Jeffreys' prior (Firth 1993):
|
|
11
|
+
* removes the `O(1/n)` bias of maximum likelihood and stays finite under
|
|
12
|
+
* separation — the method of R's `logistf` for rare events and small
|
|
13
|
+
* samples.
|
|
14
|
+
*/
|
|
15
|
+
export type LogisticRegressionPenalty = "none" | "ridge" | "firth";
|
|
16
|
+
/** Options of {@link logisticRegression}. */
|
|
17
|
+
export type LogisticRegressionOptions = {
|
|
18
|
+
/**
|
|
19
|
+
* One finite non-negative prior weight per case: a frequency weight, or the
|
|
20
|
+
* number of trials when the outcome is a proportion. `null` or absent: `1`.
|
|
21
|
+
*/
|
|
22
|
+
readonly weights?: ArrayLike<number> | null;
|
|
23
|
+
/**
|
|
24
|
+
* One finite offset per case, added to the linear predictor with coefficient
|
|
25
|
+
* `1`.
|
|
26
|
+
*/
|
|
27
|
+
readonly offset?: ArrayLike<number> | null;
|
|
28
|
+
/** The penalty; `"none"` by default. */
|
|
29
|
+
readonly penalty?: LogisticRegressionPenalty;
|
|
30
|
+
/** The ridge strength `λ`, finite and non-negative; `1` by default. */
|
|
31
|
+
readonly ridge?: number;
|
|
32
|
+
/**
|
|
33
|
+
* Columns of the design the ridge leaves free (an intercept, usually); none
|
|
34
|
+
* by default.
|
|
35
|
+
*/
|
|
36
|
+
readonly unpenalized?: readonly number[];
|
|
37
|
+
/**
|
|
38
|
+
* Converged once the (penalised) deviance changes by less than `tolerance ·
|
|
39
|
+
* (|deviance| + 0.1)` in an iteration (R's `glm` rule). Positive; `1e-10` by
|
|
40
|
+
* default. Fisher scoring converges quadratically without a penalty or with
|
|
41
|
+
* the ridge, so the coefficients are then near full precision; Firth's
|
|
42
|
+
* modified score converges linearly, leaving them good to about `√tolerance`
|
|
43
|
+
* — pass a smaller one (down to `1e-16`) for more digits.
|
|
44
|
+
*/
|
|
45
|
+
readonly tolerance?: number;
|
|
46
|
+
/** Iterations at most, a positive integer; `100` by default. */
|
|
47
|
+
readonly maxIterations?: number;
|
|
48
|
+
/** Checked at every iteration; aborting throws its reason. */
|
|
49
|
+
readonly signal?: AbortSignal | null;
|
|
50
|
+
};
|
|
51
|
+
/** What {@link logisticRegression} returns. */
|
|
52
|
+
export type LogisticRegressionResult = {
|
|
53
|
+
/**
|
|
54
|
+
* One coefficient per design column; `0` for a column aliased with others
|
|
55
|
+
* (rank deficiency), whose covariance entries are then `NaN`.
|
|
56
|
+
*/
|
|
57
|
+
readonly coefficients: Float64Array;
|
|
58
|
+
/**
|
|
59
|
+
* The coefficients' covariance: the inverse Fisher information `(XᵀWX)⁻¹` at
|
|
60
|
+
* the estimate (also for Firth's, as `logistf`), `(XᵀWX + λP)⁻¹` under the
|
|
61
|
+
* ridge (the curvature of the penalised likelihood).
|
|
62
|
+
*/
|
|
63
|
+
readonly covariance: Matrix;
|
|
64
|
+
/** Square roots of the covariance's diagonal. */
|
|
65
|
+
readonly standardErrors: Float64Array;
|
|
66
|
+
/** The fitted probabilities, one per case. */
|
|
67
|
+
readonly fitted: Float64Array;
|
|
68
|
+
/**
|
|
69
|
+
* The deviance `2 Σ wᵢ [yᵢ ln(yᵢ/πᵢ) + (1 − yᵢ) ln((1 − yᵢ)/(1 − πᵢ))]`
|
|
70
|
+
* against the saturated model, unpenalised.
|
|
71
|
+
*/
|
|
72
|
+
readonly deviance: number;
|
|
73
|
+
/**
|
|
74
|
+
* `Σ wᵢ [yᵢ ln πᵢ + (1 − yᵢ) ln(1 − πᵢ)]`, unpenalised and without binomial
|
|
75
|
+
* coefficients.
|
|
76
|
+
*/
|
|
77
|
+
readonly logLikelihood: number;
|
|
78
|
+
/** The objective maximised: the log likelihood plus the penalty term. */
|
|
79
|
+
readonly penalizedLogLikelihood: number;
|
|
80
|
+
/** The numerical rank of the design (its weighted, pivoted QR). */
|
|
81
|
+
readonly rank: number;
|
|
82
|
+
/** Iterations run. */
|
|
83
|
+
readonly iterations: number;
|
|
84
|
+
/** Whether the deviance settled within `tolerance` before `maxIterations`. */
|
|
85
|
+
readonly converged: boolean;
|
|
86
|
+
/**
|
|
87
|
+
* Whether some fitted probability of a weighted case is within `10ε` of `0`
|
|
88
|
+
* or `1` — the mark of separation, where unpenalised coefficients are not
|
|
89
|
+
* meaningful (R's "fitted probabilities numerically 0 or 1").
|
|
90
|
+
*/
|
|
91
|
+
readonly separated: boolean;
|
|
92
|
+
};
|
|
93
|
+
/**
|
|
94
|
+
* Logistic regression of binary or proportion outcomes on a design matrix,
|
|
95
|
+
* `logit P(Y = 1) = Xβ + offset`, by iteratively reweighted least squares
|
|
96
|
+
* (Fisher scoring, Nelder and Wedderburn 1972) over a pivoted Householder QR —
|
|
97
|
+
* each step a weighted least-squares solve, never the normal equations, so a
|
|
98
|
+
* nearly collinear design loses digits only as its condition number, and an
|
|
99
|
+
* exactly collinear one gets the basic solution (aliased coefficients `0`,
|
|
100
|
+
* covariance `NaN`, as R's `glm`).
|
|
101
|
+
*
|
|
102
|
+
* Starts from R's `mustart` (`(wy + ½)/(w + 1)`), halves any step that lowers
|
|
103
|
+
* the penalised likelihood, and stops on the deviance change. Firth's penalty
|
|
104
|
+
* adds `hᵢ(½ − πᵢ)` to each working residual, `h` the leverages of the weighted
|
|
105
|
+
* design (the modified score of Firth 1993); the ridge appends `√λ` rows to the
|
|
106
|
+
* design. The covariance, deviance and log likelihood are evaluated at the
|
|
107
|
+
* estimate. Matches statsmodels' `GLM(Binomial)` without a penalty.
|
|
108
|
+
*
|
|
109
|
+
* O(iterations · n · p²) time, O(n · p) memory.
|
|
110
|
+
*
|
|
111
|
+
* @param design The design `X`, one case per row; include a column of ones for
|
|
112
|
+
* an intercept. Finite entries.
|
|
113
|
+
* @param outcomes One outcome per case, in `[0, 1]`: `0`/`1`, or the observed
|
|
114
|
+
* proportion of `weights[i]` trials.
|
|
115
|
+
* @param options Weights, offset, penalty, stopping rules, signal.
|
|
116
|
+
* @returns The fit.
|
|
117
|
+
* @throws {RangeError} When the lengths differ, an outcome lies outside `[0,
|
|
118
|
+
* 1]`, the design, a weight or an offset is not finite (a weight negative),
|
|
119
|
+
* or an option is out of its range.
|
|
120
|
+
* @throws The signal's reason once aborted.
|
|
121
|
+
*/
|
|
122
|
+
export declare function logisticRegression(design: Matrix, outcomes: ArrayLike<number>, options?: LogisticRegressionOptions): LogisticRegressionResult;
|
|
123
|
+
//# sourceMappingURL=logistic-regression.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"logistic-regression.d.ts","sourceRoot":"","sources":["../../src/forecast/logistic-regression.ts"],"names":[],"mappings":"AACA,OAAO,EACN,KAAK,MAAM,EAGX,MAAM,qBAAqB,CAAC;AAK7B;;;;;;;;;;;;GAYG;AACH,MAAM,MAAM,yBAAyB,GAAG,MAAM,GAAG,OAAO,GAAG,OAAO,CAAC;AAEnE,6CAA6C;AAC7C,MAAM,MAAM,yBAAyB,GAAG;IACvC;;;OAGG;IACH,QAAQ,CAAC,OAAO,CAAC,EAAE,SAAS,CAAC,MAAM,CAAC,GAAG,IAAI,CAAC;IAE5C;;;OAGG;IACH,QAAQ,CAAC,MAAM,CAAC,EAAE,SAAS,CAAC,MAAM,CAAC,GAAG,IAAI,CAAC;IAE3C,wCAAwC;IACxC,QAAQ,CAAC,OAAO,CAAC,EAAE,yBAAyB,CAAC;IAE7C,uEAAuE;IACvE,QAAQ,CAAC,KAAK,CAAC,EAAE,MAAM,CAAC;IAExB;;;OAGG;IACH,QAAQ,CAAC,WAAW,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IAEzC;;;;;;;OAOG;IACH,QAAQ,CAAC,SAAS,CAAC,EAAE,MAAM,CAAC;IAE5B,gEAAgE;IAChE,QAAQ,CAAC,aAAa,CAAC,EAAE,MAAM,CAAC;IAEhC,8DAA8D;IAC9D,QAAQ,CAAC,MAAM,CAAC,EAAE,WAAW,GAAG,IAAI,CAAC;CACrC,CAAC;AAEF,+CAA+C;AAC/C,MAAM,MAAM,wBAAwB,GAAG;IACtC;;;OAGG;IACH,QAAQ,CAAC,YAAY,EAAE,YAAY,CAAC;IAEpC;;;;OAIG;IACH,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;IAE5B,iDAAiD;IACjD,QAAQ,CAAC,cAAc,EAAE,YAAY,CAAC;IAEtC,8CAA8C;IAC9C,QAAQ,CAAC,MAAM,EAAE,YAAY,CAAC;IAE9B;;;OAGG;IACH,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAE1B;;;OAGG;IACH,QAAQ,CAAC,aAAa,EAAE,MAAM,CAAC;IAE/B,yEAAyE;IACzE,QAAQ,CAAC,sBAAsB,EAAE,MAAM,CAAC;IAExC,mEAAmE;IACnE,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IAEtB,sBAAsB;IACtB,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;IAE5B,8EAA8E;IAC9E,QAAQ,CAAC,SAAS,EAAE,OAAO,CAAC;IAE5B;;;;OAIG;IACH,QAAQ,CAAC,SAAS,EAAE,OAAO,CAAC;CAC5B,CAAC;AAUF;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AACH,wBAAgB,kBAAkB,CACjC,MAAM,EAAE,MAAM,EACd,QAAQ,EAAE,SAAS,CAAC,MAAM,CAAC,EAC3B,OAAO,CAAC,EAAE,yBAAyB,GACjC,wBAAwB,CA0T1B"}
|
|
@@ -0,0 +1,282 @@
|
|
|
1
|
+
import { assertInteger, describeValue } from "@ac-kit/core";
|
|
2
|
+
import { matrixCreate, QrDecomposition, } from "@ac-kit/math-linear";
|
|
3
|
+
import { logistic_, softplus_ } from "../_logistic.js";
|
|
4
|
+
import { assertSameLength_ } from "./_forecast-checks.js";
|
|
5
|
+
const SEPARATION_ = 10 * Number.EPSILON;
|
|
6
|
+
const MAX_HALVINGS_ = 30;
|
|
7
|
+
/** `y ln(y/π)` with `0 ln 0 = 0`, from `ln π`. */
|
|
8
|
+
function devianceTerm_(y, logP) {
|
|
9
|
+
return y > 0 ? y * (Math.log(y) - logP) : 0;
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* Logistic regression of binary or proportion outcomes on a design matrix,
|
|
13
|
+
* `logit P(Y = 1) = Xβ + offset`, by iteratively reweighted least squares
|
|
14
|
+
* (Fisher scoring, Nelder and Wedderburn 1972) over a pivoted Householder QR —
|
|
15
|
+
* each step a weighted least-squares solve, never the normal equations, so a
|
|
16
|
+
* nearly collinear design loses digits only as its condition number, and an
|
|
17
|
+
* exactly collinear one gets the basic solution (aliased coefficients `0`,
|
|
18
|
+
* covariance `NaN`, as R's `glm`).
|
|
19
|
+
*
|
|
20
|
+
* Starts from R's `mustart` (`(wy + ½)/(w + 1)`), halves any step that lowers
|
|
21
|
+
* the penalised likelihood, and stops on the deviance change. Firth's penalty
|
|
22
|
+
* adds `hᵢ(½ − πᵢ)` to each working residual, `h` the leverages of the weighted
|
|
23
|
+
* design (the modified score of Firth 1993); the ridge appends `√λ` rows to the
|
|
24
|
+
* design. The covariance, deviance and log likelihood are evaluated at the
|
|
25
|
+
* estimate. Matches statsmodels' `GLM(Binomial)` without a penalty.
|
|
26
|
+
*
|
|
27
|
+
* O(iterations · n · p²) time, O(n · p) memory.
|
|
28
|
+
*
|
|
29
|
+
* @param design The design `X`, one case per row; include a column of ones for
|
|
30
|
+
* an intercept. Finite entries.
|
|
31
|
+
* @param outcomes One outcome per case, in `[0, 1]`: `0`/`1`, or the observed
|
|
32
|
+
* proportion of `weights[i]` trials.
|
|
33
|
+
* @param options Weights, offset, penalty, stopping rules, signal.
|
|
34
|
+
* @returns The fit.
|
|
35
|
+
* @throws {RangeError} When the lengths differ, an outcome lies outside `[0,
|
|
36
|
+
* 1]`, the design, a weight or an offset is not finite (a weight negative),
|
|
37
|
+
* or an option is out of its range.
|
|
38
|
+
* @throws The signal's reason once aborted.
|
|
39
|
+
*/
|
|
40
|
+
export function logisticRegression(design, outcomes, options) {
|
|
41
|
+
const routine = "logisticRegression";
|
|
42
|
+
const rows = design.rows;
|
|
43
|
+
const columns = design.columns;
|
|
44
|
+
const data = design.data;
|
|
45
|
+
if (data.length !== rows * columns) {
|
|
46
|
+
throw new RangeError(`${routine}: design.data must hold ${rows} × ${columns} entries, got ${data.length}`);
|
|
47
|
+
}
|
|
48
|
+
assertSameLength_(routine, "design.rows", rows, "outcomes", outcomes.length);
|
|
49
|
+
for (let index = 0; index < data.length; index++) {
|
|
50
|
+
if (!Number.isFinite(data[index])) {
|
|
51
|
+
throw new RangeError(`${routine}: the design must be finite`);
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
for (let index = 0; index < rows; index++) {
|
|
55
|
+
const outcome = outcomes[index];
|
|
56
|
+
if (!(outcome >= 0 && outcome <= 1)) {
|
|
57
|
+
throw new RangeError(`${routine}: outcomes must be in [0, 1], got ${describeValue(outcome)} at ${index}`);
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
const priorWeights = options?.weights ?? null;
|
|
61
|
+
const offsets = options?.offset ?? null;
|
|
62
|
+
if (priorWeights !== null) {
|
|
63
|
+
assertSameLength_(routine, "weights", priorWeights.length, "outcomes", rows);
|
|
64
|
+
for (let index = 0; index < rows; index++) {
|
|
65
|
+
const weight = priorWeights[index];
|
|
66
|
+
if (!(weight >= 0 && weight < Number.POSITIVE_INFINITY)) {
|
|
67
|
+
throw new RangeError(`${routine}: weights must be finite and non-negative, got ${describeValue(weight)} at ${index}`);
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
if (offsets !== null) {
|
|
72
|
+
assertSameLength_(routine, "offset", offsets.length, "outcomes", rows);
|
|
73
|
+
for (let index = 0; index < rows; index++) {
|
|
74
|
+
if (!Number.isFinite(offsets[index])) {
|
|
75
|
+
throw new RangeError(`${routine}: offset must be finite, got ${describeValue(offsets[index])} at ${index}`);
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
const penalty = options?.penalty ?? "none";
|
|
80
|
+
if (penalty !== "none" && penalty !== "ridge" && penalty !== "firth") {
|
|
81
|
+
throw new RangeError(`${routine}: penalty must be "none", "ridge" or "firth", got ${describeValue(penalty)}`);
|
|
82
|
+
}
|
|
83
|
+
const lambda = options?.ridge ?? 1;
|
|
84
|
+
if (!(lambda >= 0 && lambda < Number.POSITIVE_INFINITY)) {
|
|
85
|
+
throw new RangeError(`${routine}: ridge must be finite and non-negative, got ${describeValue(lambda)}`);
|
|
86
|
+
}
|
|
87
|
+
const free = new Uint8Array(columns);
|
|
88
|
+
for (const column of options?.unpenalized ?? []) {
|
|
89
|
+
if (!Number.isInteger(column) || column < 0 || column >= columns) {
|
|
90
|
+
throw new RangeError(`${routine}: unpenalized holds ${describeValue(column)}, not a column of [0, ${columns})`);
|
|
91
|
+
}
|
|
92
|
+
free[column] = 1;
|
|
93
|
+
}
|
|
94
|
+
const tolerance = options?.tolerance ?? 1e-10;
|
|
95
|
+
if (!(tolerance > 0 && tolerance < Number.POSITIVE_INFINITY)) {
|
|
96
|
+
throw new RangeError(`${routine}: tolerance must be positive and finite, got ${describeValue(tolerance)}`);
|
|
97
|
+
}
|
|
98
|
+
const maxIterations = options?.maxIterations ?? 100;
|
|
99
|
+
assertInteger(maxIterations, "maxIterations", 1);
|
|
100
|
+
const signal = options?.signal ?? null;
|
|
101
|
+
// The ridge appends one row √λ·eⱼ per penalised column, of response 0.
|
|
102
|
+
const ridgeRows = [];
|
|
103
|
+
if (penalty === "ridge") {
|
|
104
|
+
for (let column = 0; column < columns; column++) {
|
|
105
|
+
if (free[column] === 0) {
|
|
106
|
+
ridgeRows.push(column);
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
const augmentedRows = rows + ridgeRows.length;
|
|
111
|
+
const augmented = ridgeRows.length === 0 ? design : matrixCreate(augmentedRows, columns);
|
|
112
|
+
if (augmented !== design) {
|
|
113
|
+
const target = augmented.data;
|
|
114
|
+
const root = Math.sqrt(lambda);
|
|
115
|
+
for (let column = 0; column < columns; column++) {
|
|
116
|
+
target.set(data.subarray(rows * column, rows * (column + 1)), augmentedRows * column);
|
|
117
|
+
}
|
|
118
|
+
for (let extra = 0; extra < ridgeRows.length; extra++) {
|
|
119
|
+
target[augmentedRows * ridgeRows[extra] + rows + extra] = root;
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
const qr = new QrDecomposition(augmentedRows, columns);
|
|
123
|
+
const workingWeights = new Float64Array(augmentedRows);
|
|
124
|
+
const response = new Float64Array(augmentedRows);
|
|
125
|
+
const leverages = new Float64Array(augmentedRows);
|
|
126
|
+
const triangle = matrixCreate(Math.min(augmentedRows, columns), columns);
|
|
127
|
+
const eta = new Float64Array(rows);
|
|
128
|
+
const fitted = new Float64Array(rows);
|
|
129
|
+
const beta = new Float64Array(columns);
|
|
130
|
+
const previous = new Float64Array(columns);
|
|
131
|
+
workingWeights.fill(1, rows);
|
|
132
|
+
const priorOf = (index) => priorWeights === null ? 1 : priorWeights[index];
|
|
133
|
+
const offsetOf = (index) => (offsets === null ? 0 : offsets[index]);
|
|
134
|
+
const setLinearPredictor = () => {
|
|
135
|
+
for (let row = 0; row < rows; row++) {
|
|
136
|
+
let sum = offsetOf(row);
|
|
137
|
+
for (let column = 0; column < columns; column++) {
|
|
138
|
+
sum += data[rows * column + row] * beta[column];
|
|
139
|
+
}
|
|
140
|
+
eta[row] = sum;
|
|
141
|
+
}
|
|
142
|
+
};
|
|
143
|
+
// Decomposes √W·X at the current η and returns the log likelihood.
|
|
144
|
+
const decompose = () => {
|
|
145
|
+
let logLikelihood = 0;
|
|
146
|
+
for (let row = 0; row < rows; row++) {
|
|
147
|
+
const linear = eta[row];
|
|
148
|
+
const probability = logistic_(linear);
|
|
149
|
+
const y = outcomes[row];
|
|
150
|
+
const prior = priorOf(row);
|
|
151
|
+
fitted[row] = probability;
|
|
152
|
+
workingWeights[row] = prior * probability * (1 - probability);
|
|
153
|
+
if (prior > 0) {
|
|
154
|
+
logLikelihood -=
|
|
155
|
+
prior * (y * softplus_(-linear) + (1 - y) * softplus_(linear));
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
qr.decompose(augmented, { weights: workingWeights });
|
|
159
|
+
return logLikelihood;
|
|
160
|
+
};
|
|
161
|
+
const penaltyTerm = () => {
|
|
162
|
+
if (penalty === "ridge") {
|
|
163
|
+
let sum = 0;
|
|
164
|
+
for (const column of ridgeRows) {
|
|
165
|
+
sum += beta[column] * beta[column];
|
|
166
|
+
}
|
|
167
|
+
return -0.5 * lambda * sum;
|
|
168
|
+
}
|
|
169
|
+
if (penalty === "firth") {
|
|
170
|
+
qr.r(triangle);
|
|
171
|
+
let logDeterminant = 0;
|
|
172
|
+
const size = triangle.rows;
|
|
173
|
+
for (let index = 0; index < qr.rank; index++) {
|
|
174
|
+
logDeterminant += Math.log(Math.abs(triangle.data[size * index + index]));
|
|
175
|
+
}
|
|
176
|
+
// ½ ln det(XᵀWX) = ln |det R| over the independent columns.
|
|
177
|
+
return logDeterminant;
|
|
178
|
+
}
|
|
179
|
+
return 0;
|
|
180
|
+
};
|
|
181
|
+
// R's mustart: η = logit((wy + ½)/(w + 1)).
|
|
182
|
+
for (let row = 0; row < rows; row++) {
|
|
183
|
+
const prior = priorOf(row);
|
|
184
|
+
const start = (prior * outcomes[row] + 0.5) / (prior + 1);
|
|
185
|
+
eta[row] = Math.log(start) - Math.log1p(-start);
|
|
186
|
+
}
|
|
187
|
+
let objective = Number.NaN;
|
|
188
|
+
let previousObjective = Number.NaN;
|
|
189
|
+
let logLikelihood = Number.NaN;
|
|
190
|
+
let iterations = 0;
|
|
191
|
+
let converged = false;
|
|
192
|
+
let halvings = 0;
|
|
193
|
+
let first = true;
|
|
194
|
+
for (;;) {
|
|
195
|
+
signal?.throwIfAborted();
|
|
196
|
+
logLikelihood = decompose();
|
|
197
|
+
objective = first ? Number.NaN : logLikelihood + penaltyTerm();
|
|
198
|
+
// Compared in deviance units, −2 × the penalised log likelihood.
|
|
199
|
+
if (previousObjective === previousObjective) {
|
|
200
|
+
if (!(objective >=
|
|
201
|
+
previousObjective - 1e-12 * Math.abs(previousObjective)) &&
|
|
202
|
+
halvings < MAX_HALVINGS_) {
|
|
203
|
+
for (let column = 0; column < columns; column++) {
|
|
204
|
+
beta[column] = 0.5 * (beta[column] + previous[column]);
|
|
205
|
+
}
|
|
206
|
+
setLinearPredictor();
|
|
207
|
+
halvings++;
|
|
208
|
+
continue;
|
|
209
|
+
}
|
|
210
|
+
halvings = 0;
|
|
211
|
+
if (2 * Math.abs(objective - previousObjective) <
|
|
212
|
+
tolerance * (2 * Math.abs(objective) + 0.1)) {
|
|
213
|
+
converged = true;
|
|
214
|
+
break;
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
if (iterations >= maxIterations) {
|
|
218
|
+
break;
|
|
219
|
+
}
|
|
220
|
+
iterations++;
|
|
221
|
+
previousObjective = objective;
|
|
222
|
+
previous.set(beta);
|
|
223
|
+
if (penalty === "firth") {
|
|
224
|
+
qr.leverages(leverages);
|
|
225
|
+
}
|
|
226
|
+
for (let row = 0; row < rows; row++) {
|
|
227
|
+
const weight = workingWeights[row];
|
|
228
|
+
if (weight > 0) {
|
|
229
|
+
const probability = fitted[row];
|
|
230
|
+
const adjustment = penalty === "firth" ? leverages[row] * (0.5 - probability) : 0;
|
|
231
|
+
response[row] =
|
|
232
|
+
eta[row] -
|
|
233
|
+
offsetOf(row) +
|
|
234
|
+
(priorOf(row) * (outcomes[row] - probability) + adjustment) / weight;
|
|
235
|
+
}
|
|
236
|
+
else {
|
|
237
|
+
response[row] = 0;
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
qr.solve(beta, response);
|
|
241
|
+
setLinearPredictor();
|
|
242
|
+
first = false;
|
|
243
|
+
}
|
|
244
|
+
const covariance = matrixCreate(columns, columns);
|
|
245
|
+
qr.covariance(covariance);
|
|
246
|
+
const standardErrors = new Float64Array(columns);
|
|
247
|
+
for (let column = 0; column < columns; column++) {
|
|
248
|
+
standardErrors[column] = Math.sqrt(covariance.data[columns * column + column]);
|
|
249
|
+
}
|
|
250
|
+
let deviance = 0;
|
|
251
|
+
let separated = false;
|
|
252
|
+
for (let row = 0; row < rows; row++) {
|
|
253
|
+
const prior = priorOf(row);
|
|
254
|
+
if (prior > 0) {
|
|
255
|
+
const y = outcomes[row];
|
|
256
|
+
const linear = eta[row];
|
|
257
|
+
const probability = fitted[row];
|
|
258
|
+
deviance +=
|
|
259
|
+
2 *
|
|
260
|
+
prior *
|
|
261
|
+
(devianceTerm_(y, -softplus_(-linear)) +
|
|
262
|
+
devianceTerm_(1 - y, -softplus_(linear)));
|
|
263
|
+
if (probability < SEPARATION_ || probability > 1 - SEPARATION_) {
|
|
264
|
+
separated = true;
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
return {
|
|
269
|
+
coefficients: beta,
|
|
270
|
+
covariance,
|
|
271
|
+
standardErrors,
|
|
272
|
+
fitted,
|
|
273
|
+
deviance,
|
|
274
|
+
logLikelihood,
|
|
275
|
+
penalizedLogLikelihood: objective,
|
|
276
|
+
rank: qr.rank,
|
|
277
|
+
iterations,
|
|
278
|
+
converged,
|
|
279
|
+
separated,
|
|
280
|
+
};
|
|
281
|
+
}
|
|
282
|
+
//# sourceMappingURL=logistic-regression.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"logistic-regression.js","sourceRoot":"","sources":["../../src/forecast/logistic-regression.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAC5D,OAAO,EAEN,YAAY,EACZ,eAAe,GACf,MAAM,qBAAqB,CAAC;AAE7B,OAAO,EAAE,SAAS,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AACvD,OAAO,EAAE,iBAAiB,EAAE,MAAM,uBAAuB,CAAC;AAiH1D,MAAM,WAAW,GAAG,EAAE,GAAG,MAAM,CAAC,OAAO,CAAC;AACxC,MAAM,aAAa,GAAG,EAAE,CAAC;AAEzB,kDAAkD;AAClD,SAAS,aAAa,CAAC,CAAS,EAAE,IAAY;IAC7C,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC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CAAC,IAAI;QACb,UAAU;QACV,SAAS;QACT,SAAS;KACT,CAAC;AACH,CAAC"}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import type { RandomFn } from "@ac-kit/core";
|
|
2
|
+
import type { Matrix } from "@ac-kit/math-linear";
|
|
3
|
+
import type { ForecastWeightsOptions } from "./brier-score.js";
|
|
4
|
+
/** Options of {@link rankHistogram}. */
|
|
5
|
+
export type RankHistogramOptions = ForecastWeightsOptions & {
|
|
6
|
+
/**
|
|
7
|
+
* The uniform source that places an observation among members equal to it;
|
|
8
|
+
* `Math.random` by default. Pass a seeded one for a reproducible histogram.
|
|
9
|
+
*/
|
|
10
|
+
readonly random?: RandomFn | null;
|
|
11
|
+
};
|
|
12
|
+
/**
|
|
13
|
+
* The rank (Talagrand) histogram of an ensemble (Anderson 1996; Hamill 2001):
|
|
14
|
+
* for each case, the rank of the observation among the `m` members, counted
|
|
15
|
+
* into `m + 1` bins. Flat for a calibrated ensemble; U-shaped when it is
|
|
16
|
+
* underdispersed, domed when overdispersed, sloped when biased.
|
|
17
|
+
*
|
|
18
|
+
* An observation equal to `t` members takes a rank drawn uniformly among the `t +
|
|
19
|
+
* 1` it could have (Hamill and Colucci 1997), so discrete quantities —
|
|
20
|
+
* precipitation with many zeros — do not pile into the lowest bin. A case whose
|
|
21
|
+
* observation or any member is `NaN` is skipped.
|
|
22
|
+
*
|
|
23
|
+
* O(n · m) time, O(m) memory.
|
|
24
|
+
*
|
|
25
|
+
* @param members The ensemble, one case per row and one member per column.
|
|
26
|
+
* @param observations One observation per case (`members.rows`).
|
|
27
|
+
* @param options Case weights and the tie-breaking source.
|
|
28
|
+
* @returns The (weighted) count of each rank `0 … m`.
|
|
29
|
+
* @throws {RangeError} When the lengths differ or the weights are invalid.
|
|
30
|
+
*/
|
|
31
|
+
export declare function rankHistogram(members: Matrix, observations: ArrayLike<number>, options?: RankHistogramOptions): Float64Array;
|
|
32
|
+
//# sourceMappingURL=rank-histogram.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"rank-histogram.d.ts","sourceRoot":"","sources":["../../src/forecast/rank-histogram.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,cAAc,CAAC;AAC7C,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,qBAAqB,CAAC;AAIlD,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,kBAAkB,CAAC;AAE/D,wCAAwC;AACxC,MAAM,MAAM,oBAAoB,GAAG,sBAAsB,GAAG;IAC3D;;;OAGG;IACH,QAAQ,CAAC,MAAM,CAAC,EAAE,QAAQ,GAAG,IAAI,CAAC;CAClC,CAAC;AAEF;;;;;;;;;;;;;;;;;;GAkBG;AACH,wBAAgB,aAAa,CAC5B,OAAO,EAAE,MAAM,EACf,YAAY,EAAE,SAAS,CAAC,MAAM,CAAC,EAC/B,OAAO,CAAC,EAAE,oBAAoB,GAC5B,YAAY,CAwDd"}
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import { randomInteger } from "@ac-kit/math-random";
|
|
2
|
+
import { assertSameLength_, weightTotal_ } from "./_forecast-checks.js";
|
|
3
|
+
/**
|
|
4
|
+
* The rank (Talagrand) histogram of an ensemble (Anderson 1996; Hamill 2001):
|
|
5
|
+
* for each case, the rank of the observation among the `m` members, counted
|
|
6
|
+
* into `m + 1` bins. Flat for a calibrated ensemble; U-shaped when it is
|
|
7
|
+
* underdispersed, domed when overdispersed, sloped when biased.
|
|
8
|
+
*
|
|
9
|
+
* An observation equal to `t` members takes a rank drawn uniformly among the `t +
|
|
10
|
+
* 1` it could have (Hamill and Colucci 1997), so discrete quantities —
|
|
11
|
+
* precipitation with many zeros — do not pile into the lowest bin. A case whose
|
|
12
|
+
* observation or any member is `NaN` is skipped.
|
|
13
|
+
*
|
|
14
|
+
* O(n · m) time, O(m) memory.
|
|
15
|
+
*
|
|
16
|
+
* @param members The ensemble, one case per row and one member per column.
|
|
17
|
+
* @param observations One observation per case (`members.rows`).
|
|
18
|
+
* @param options Case weights and the tie-breaking source.
|
|
19
|
+
* @returns The (weighted) count of each rank `0 … m`.
|
|
20
|
+
* @throws {RangeError} When the lengths differ or the weights are invalid.
|
|
21
|
+
*/
|
|
22
|
+
export function rankHistogram(members, observations, options) {
|
|
23
|
+
const cases = members.rows;
|
|
24
|
+
const size = members.columns;
|
|
25
|
+
assertSameLength_("rankHistogram", "members.rows", cases, "observations", observations.length);
|
|
26
|
+
const weights = options?.weights ?? null;
|
|
27
|
+
weightTotal_("rankHistogram", weights, cases);
|
|
28
|
+
const random = options?.random ?? Math.random;
|
|
29
|
+
const counts = new Float64Array(size + 1);
|
|
30
|
+
const data = members.data;
|
|
31
|
+
if (data.length !== cases * size) {
|
|
32
|
+
throw new RangeError(`rankHistogram: members.data must hold ${cases} × ${size} entries, got ${data.length}`);
|
|
33
|
+
}
|
|
34
|
+
for (let row = 0; row < cases; row++) {
|
|
35
|
+
const observation = observations[row];
|
|
36
|
+
if (observation !== observation) {
|
|
37
|
+
continue;
|
|
38
|
+
}
|
|
39
|
+
let below = 0;
|
|
40
|
+
let ties = 0;
|
|
41
|
+
let missing = false;
|
|
42
|
+
for (let column = 0; column < size; column++) {
|
|
43
|
+
const member = data[cases * column + row];
|
|
44
|
+
if (member < observation) {
|
|
45
|
+
below++;
|
|
46
|
+
}
|
|
47
|
+
else if (member === observation) {
|
|
48
|
+
ties++;
|
|
49
|
+
}
|
|
50
|
+
else if (member !== member) {
|
|
51
|
+
missing = true;
|
|
52
|
+
break;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
if (missing) {
|
|
56
|
+
continue;
|
|
57
|
+
}
|
|
58
|
+
const rank = ties === 0 ? below : below + randomInteger(0, ties + 1, random);
|
|
59
|
+
counts[rank] += weights === null ? 1 : weights[row];
|
|
60
|
+
}
|
|
61
|
+
return counts;
|
|
62
|
+
}
|
|
63
|
+
//# sourceMappingURL=rank-histogram.js.map
|
|
@@ -0,0 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CAAC,CAAC;QACd,IAAI,IAAI,GAAG,CAAC,CAAC;QACb,IAAI,OAAO,GAAG,KAAK,CAAC;QAEpB,KAAK,IAAI,MAAM,GAAG,CAAC,EAAE,MAAM,GAAG,IAAI,EAAE,MAAM,EAAE,EAAE,CAAC;YAC9C,MAAM,MAAM,GAAG,IAAI,CAAC,KAAK,GAAG,MAAM,GAAG,GAAG,CAAE,CAAC;YAE3C,IAAI,MAAM,GAAG,WAAW,EAAE,CAAC;gBAC1B,KAAK,EAAE,CAAC;YACT,CAAC;iBAAM,IAAI,MAAM,KAAK,WAAW,EAAE,CAAC;gBACnC,IAAI,EAAE,CAAC;YACR,CAAC;iBAAM,IAAI,MAAM,KAAK,MAAM,EAAE,CAAC;gBAC9B,OAAO,GAAG,IAAI,CAAC;gBACf,MAAM;YACP,CAAC;QACF,CAAC;QACD,IAAI,OAAO,EAAE,CAAC;YACb,SAAS;QACV,CAAC;QACD,MAAM,IAAI,GACT,IAAI,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,KAAK,GAAG,aAAa,CAAC,CAAC,EAAE,IAAI,GAAG,CAAC,EAAE,MAAM,CAAC,CAAC;QAEjE,MAAM,CAAC,IAAI,CAAE,IAAI,OAAO,KAAK,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,GAAG,CAAE,CAAC;IACvD,CAAC;IAED,OAAO,MAAM,CAAC;AACf,CAAC"}
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import { type RandomFn } from "@ac-kit/core";
|
|
2
|
+
import type { ForecastWeightsOptions, ProbabilityBinning } from "./brier-score.js";
|
|
3
|
+
/** Bröcker and Smith's consistency resampling for {@link reliabilityDiagram}. */
|
|
4
|
+
export type ReliabilityConsistencyOptions = {
|
|
5
|
+
/** The uniform source of the resampling; a seeded one reproduces the bars. */
|
|
6
|
+
readonly random: RandomFn;
|
|
7
|
+
/** Surrogate data sets drawn; a positive integer, `1000` by default. */
|
|
8
|
+
readonly resamples?: number;
|
|
9
|
+
/** The probability the bars span, in `(0, 1)`; `0.9` by default. */
|
|
10
|
+
readonly level?: number;
|
|
11
|
+
};
|
|
12
|
+
/** Options of {@link reliabilityDiagram}. */
|
|
13
|
+
export type ReliabilityDiagramOptions = ForecastWeightsOptions & {
|
|
14
|
+
/** The binning of the forecasts; `10` equal bins by default. */
|
|
15
|
+
readonly bins?: ProbabilityBinning;
|
|
16
|
+
/** Draws consistency bars when given; without it they are all `NaN`. */
|
|
17
|
+
readonly consistency?: ReliabilityConsistencyOptions | null;
|
|
18
|
+
};
|
|
19
|
+
/**
|
|
20
|
+
* A reliability diagram, one entry per bin in every column. A bin no forecast
|
|
21
|
+
* fell in has weight `0` and `NaN` elsewhere.
|
|
22
|
+
*/
|
|
23
|
+
export type ReliabilityDiagram = {
|
|
24
|
+
/** The lower edge of each bin (its value, for `"unique"` bins). */
|
|
25
|
+
readonly binLower: Float64Array;
|
|
26
|
+
/** The upper edge of each bin (its value, for `"unique"` bins). */
|
|
27
|
+
readonly binUpper: Float64Array;
|
|
28
|
+
/** The (weighted) number of forecasts in each bin. */
|
|
29
|
+
readonly weight: Float64Array;
|
|
30
|
+
/** The mean forecast probability of each bin: the abscissa. */
|
|
31
|
+
readonly meanForecast: Float64Array;
|
|
32
|
+
/** The observed relative frequency of the event in each bin: the ordinate. */
|
|
33
|
+
readonly observedFrequency: Float64Array;
|
|
34
|
+
/**
|
|
35
|
+
* The lower end of each bin's consistency bar: where the observed frequency
|
|
36
|
+
* would fall with probability `(1 − level)/2` if the forecasts were
|
|
37
|
+
* reliable.
|
|
38
|
+
*/
|
|
39
|
+
readonly consistencyLower: Float64Array;
|
|
40
|
+
/** The upper end of each bin's consistency bar. */
|
|
41
|
+
readonly consistencyUpper: Float64Array;
|
|
42
|
+
};
|
|
43
|
+
/**
|
|
44
|
+
* The reliability diagram of probability forecasts against binary outcomes
|
|
45
|
+
* (Murphy and Winkler 1977): for each bin, the mean forecast probability
|
|
46
|
+
* against the observed frequency of the event, which lie on the diagonal for
|
|
47
|
+
* reliable forecasts. Columnar: one `Float64Array` per quantity.
|
|
48
|
+
*
|
|
49
|
+
* **Consistency bars** (Bröcker and Smith 2007) show how far from the diagonal
|
|
50
|
+
* a reliable forecast's points still stray by chance, given how few cases each
|
|
51
|
+
* bin holds. Each surrogate data set redraws `n` forecasts from the given ones
|
|
52
|
+
* (by their weights) and each outcome as a Bernoulli trial of its own forecast
|
|
53
|
+
* — reliable by construction — and records, per bin, the observed frequency
|
|
54
|
+
* minus the mean forecast. A bar is the bin's mean forecast plus the `(1 ±
|
|
55
|
+
* level)/2` quantiles of that deviation, so it surrounds the diagonal at the
|
|
56
|
+
* point's abscissa; a point outside its bar is evidence of miscalibration at
|
|
57
|
+
* that level.
|
|
58
|
+
*
|
|
59
|
+
* O(n log n + resamples · n log n) time (one binary search per weighted draw),
|
|
60
|
+
* O(bins · resamples) memory.
|
|
61
|
+
*
|
|
62
|
+
* @param probabilities The forecast probabilities, in `[0, 1]`.
|
|
63
|
+
* @param outcomes The binary outcomes, `0` or `1`.
|
|
64
|
+
* @param options Binning, case weights, consistency resampling.
|
|
65
|
+
* @returns The diagram's columns.
|
|
66
|
+
* @throws {RangeError} When the lengths differ, a probability lies outside `[0,
|
|
67
|
+
* 1]`, an outcome is not `0` or `1`, or an option is out of range.
|
|
68
|
+
*/
|
|
69
|
+
export declare function reliabilityDiagram(probabilities: ArrayLike<number>, outcomes: ArrayLike<number>, options?: ReliabilityDiagramOptions): ReliabilityDiagram;
|
|
70
|
+
//# sourceMappingURL=reliability-diagram.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"reliability-diagram.d.ts","sourceRoot":"","sources":["../../src/forecast/reliability-diagram.ts"],"names":[],"mappings":"AACA,OAAO,EAAgC,KAAK,QAAQ,EAAE,MAAM,cAAc,CAAC;AAU3E,OAAO,KAAK,EACX,sBAAsB,EACtB,kBAAkB,EAClB,MAAM,kBA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