From a34b6ca363c5be50ede33e46a25b59e8ea7c183a Mon Sep 17 00:00:00 2001 From: Justin Purnell Date: Sat, 21 Nov 2026 11:03:27 -0500 Subject: [PATCH 01/13] docs(proposal): grouped-ranking toolkit (owner approved 2026-11-21) Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_017dtpLZ6XGCJVmSqc1u4qUt --- .../proposals/BusinessMathGroupedRanking.md | 371 ++++++++++++++++++ 1 file changed, 371 insertions(+) create mode 100644 project/plans/proposals/BusinessMathGroupedRanking.md diff --git a/project/plans/proposals/BusinessMathGroupedRanking.md b/project/plans/proposals/BusinessMathGroupedRanking.md new file mode 100644 index 00000000..ffa10c0f --- /dev/null +++ b/project/plans/proposals/BusinessMathGroupedRanking.md @@ -0,0 +1,371 @@ +# Design Proposal: `Statistics/GroupedRanking` — conditional logit, Plackett-Luce, a prior-centred penalty (also on `LogisticRegression`), per-group ranking metrics, group bootstrap, grouped cross-validation and a held-out comparison + +**Status:** Proposed 2026-11-21. Owner decisions of 2026-11-21 are built in (section 16a). Nothing is built in BusinessMath; no BusinessMath file other than this one was touched. This is the BusinessMath-side proposal derived from ClassGraph's draft of the same name (ClassGraph branch `bm-grouped-ranking-proposal`, commit `8c01683`, which stays there as history). +**Master Plan Reference:** `project/master_plan.md` (Statistics area); the portfolio principle that generic machinery lives here and what is specific to a consumer stays there (ClassGraph ADR-014 moved its generic graph metrics here, ADR-010 here took the eigenvector-by-component measure); new **ADR-011** (ADR-010 is the last in `project/decisions/architecture_decisions.md`, checked 2026-11-21). +**Source:** ClassGraph `Sources/ClassGraphCore/Backtest/` at `main` c81c833 (7 files, about 2,100 lines: a conditional-logit fitter, a per-group ranking evaluator, a group bootstrap and a nested grouped 5-fold, and `BacktestRandom`, a copy of SplitMix64), its ADR-022 and `YearbookMentionGraph.md` Amendment A. Read only; nothing is copied until phase B1. +**Upstream check (done 2026-11-21):** BusinessMath is at `v3.0.0-alpha.17` (`main`, release commit `99de37f5`). ClassGraph pins revision `ae06466`, which is 4 commits behind; those commits touch only `Sources/BusinessMath/Network` (4 files, +416 lines). Nothing in `Statistics` changed, so none of what follows exists upstream. WineTaster 4 pins `3.0.0-alpha.16` exactly and is unaffected until it chooses to move. + +--- + +## 1. Objective + +Add a domain-free **grouped-ranking toolkit** to `Statistics/`, so that any analysis of the shape "within each group, which items were chosen, and what predicts the choice" has a correct, tested implementation, ClassGraph deletes its private copy, and the same pieces are exposed through the MCP server (a follow-up in that repository, section 5). + +The shape, with no reference to any domain: there are **groups** (a customer, a user, a query, a rater). Each group has a **candidate set** of items, each described by a feature vector, and either a **chosen subset** (the positives) or a **ranking** of its top choices. The data are one row per group-and-item. A model scores items; we want to (1) fit the feature weights, (2) measure how well they rank each group's chosen items among that group's own candidates, and (3) say how sure we are, and whether a refit beats a reference set of weights on groups the fit never saw. + +Seven pieces, each separately useful and separately gated: + +1. **Conditional logit over groups** (the exact subset likelihood, `likelihood: .subset`). +2. **Plackett-Luce** (the ordered top-*m* likelihood, `likelihood: .ranking`) on the same data type. The two coincide when each group chooses exactly one item and differ otherwise (section 3.2). +3. **A prior-centred penalty** with optional non-negativity, for the grouped models. +4. **The same kind of penalty on the existing `LogisticRegression`**, which today refuses separated data (section 3.9). +5. **Per-group ranking metrics** (mean percentile, top-*k* share) with a stated tie rule. +6. **Bootstrap over groups** and **grouped and nested k-fold**. +7. **`HeldOutComparison`**, a generic result type for "does a refit beat the reference weights on held-out groups": the paired difference in a metric, its bootstrap interval, and whether the interval excludes zero. It carries no decision threshold. + +**The split with ClassGraph (agreed 2026-11-21).** Here: the estimators, the metrics, the resampling, the held-out comparison. Stays in ClassGraph: the label definitions (what counts as "named"), the mapping of its 16 weights to features, the candidate weights file, the rescale-to-keep-density step, the privacy rules, and the **adoption thresholds** (a weight must move 25 percent, a feature needs 20 named pairs). Those thresholds are decision policy, not statistics; the library reports the interval and the counts and the caller decides. + +## 2. Motivation + +**The problem the pieces answer.** Pooling every group-and-item row into one ordinary logistic regression learns *which groups choose a lot*, not *what makes an item chosen*. In ClassGraph's backtest this was the central design decision: a talkative group (a person who names many others) contributes many positives, and a pooled model assigns weight to any feature that merely correlates with talkative groups. Comparing each group only against itself removes that. `LogisticRegression` is the pooled model; it cannot do this. + +**Why it belongs here.** +- It is domain-neutral, which this library already values: `ClassifierEvaluation` documents that it lives in `Statistics/` and not under marketing because a response model, a credit scorecard and a churn model are the same object. A choice model over groups is likewise the same object in discrete-choice demand, search and recommendation ranking, offer selection, and any "which of these did they pick" data. +- The consumer's own rule (its `Package.swift`, `shared_packages.md`) is that generic machinery is not hand-rolled in a consumer. The backtest breaks it twice: the statistics, and `BacktestRandom`, a copy of the SplitMix64 that SwiftDeterminism provides and this library re-exports. +- **It is easy to get subtly wrong, and the first version was.** The first likelihood was a softmax per chosen item; ClassGraph's build agent measured a scale bias of about 40 percent on a synthetic class generated from the intended model (a measurement from that build, not re-measured for this proposal) and replaced it with the exact conditional likelihood. A library with a recovery test that fails the softmax is where that lesson should live. +- It closes a gap this library's own documentation states. `LogisticRegression` says the remedy for separation is Firth's penalised likelihood, "not implemented here". A penalised fit is the natural next step (section 3.9). + +## 3. Proposed Architecture + +### 3.1 Where it lives, and why not a shared `Statistics/Ranking` + +``` +Statistics/GroupedRanking/ + GroupedChoiceData.swift // groups, candidates, chosen flags or rankings, validation, sparse form + ChoiceLikelihood.swift // .subset (conditional logit) and .ranking (Plackett-Luce): value and gradient + GroupedChoiceFit.swift // the penalised, optionally non-negative fit, prior-centred + GroupRankingMetrics.swift // per-group percentile, top-k share, summary, pooled helper + GroupResampling.swift // bootstrap weights, fold assignment + GroupedCrossValidation.swift // held-out likelihood, nested penalty selection + HeldOutComparison.swift // paired difference, interval, excludes-zero +Statistics/Regression/LogisticRegression.swift // gains a penalised fit (additive; section 3.9) +``` + +**Decision on a shared `Statistics/Ranking` area (owner asked for it to be considered).** Not proposed. What was read: `Statistics/Comparison Statistics/` holds Friedman, Kendall's W, rank sums (exact distribution and critical values), the exact tie-aware Spearman test and Nemenyi's critical difference. WineTaster 4 reaches them through `Significance Breakpoints/BusinessMathBridge.swift` (`kendallW`, `friedmanChiSquare`, `concordanceAnalysis`, `fStatistic`, `spearmanCriticalValues`, and the rank-sum critical values named in its `Package.swift` comments and README). Every one takes a judge-by-item matrix of ranks and answers **"do the judges agree, and is this pair or this wine significant"**. The new toolkit takes **feature rows** and answers **"what predicts the choice, and how well does it rank"**. Different inputs, different question, no shared code. A parent folder would either force moving `Comparison Statistics` (churn in a folder WineTaster's pinned API depends on, for no gain) or be an empty umbrella. So: new folder `GroupedRanking`, nothing existing moves, and the DocC article cross-links the two so a reader looking for "ranking" finds both. I read only WineTaster's README, `Package.swift` and the bridge file, not its other sources, so I make no claim about what else it might want; nothing there currently needs this toolkit. + +### 3.2 The two likelihoods, and exactly how they relate + +For a group *g* with *n* candidates, linear scores `s_i = β · x_i`, `w_i = exp(s_i)`. + +- **Subset (conditional logit).** If the group chose exactly *m* items as an unordered set *S*, then with a per-group intercept that cancels, `P(S) = Π_{i∈S} w_i / e_m(w)`, where `e_m` is the *m*-th elementary symmetric polynomial of the `w_i` (the sum over every size-*m* subset of the product). It is computed by dynamic programming in `O(n·m)` per group with a forward table and a rolling backward sum giving each item's inclusion probability for the gradient, with a log-sum-exp shift for stability. How many items a group chooses cannot move the weights (the intercept cancels). +- **Ranking (Plackett-Luce).** If the group's top *m* choices are an ordered list `π_1,…,π_m`, then `P = Π_{j=1..m} w_{π_j} / Σ_{l ≥ j} w_{π_l}` with the sum over the items not yet taken (the first denominator is the whole candidate set). `O(n·m)` per group. + +**Precisely what "special case" means.** With **exactly one chosen item per group** the two are the same function (both reduce to `w_i / Σ w`, the multinomial logit). With *m* > 1 they are **different likelihoods**: the subset form does not know an order, and Plackett-Luce multiplied over an arbitrary order of an unordered set would make the answer depend on the order chosen. The API therefore takes one data type and a `likelihood:` argument, and the unordered-set case must use `.subset`. (This is also the correct reading of the failed softmax: a softmax per chosen item over the *whole* candidate set never removes items already taken, which Plackett-Luce does, and which the subset form accounts for by conditioning on the set.) + +**Why not a softmax per chosen item.** Stated above. The recovery test (section 11) makes the failure permanent: it includes the softmax as a deliberately wrong comparison to show it is biased and the subset likelihood is not. + +**Groups with no variation** (no chosen item, or every item chosen) carry no information and are skipped, exactly as in the backtest; the count of skipped groups is reported. + +### 3.3 The prior-centred penalty (grouped models) + +The fitted weights are multiplicative on a **reference**: `β_k = m_k · r_k`, where `r_k ≥ 0` is the supplied reference weight and `m_k ≥ 0` a multiplier. The objective is + +`NLL(m) / (total chosen) + (λ / 2) · Σ_k (m_k − 1)²` + +so λ pulls each multiplier toward 1 (the reference) and `m_k ≥ 0` is enforced by projection. The solver is projected accelerated gradient descent with a backtracking line search and a restart when the objective rises; the objective is convex, so the optimum is unique. A **scale** (one number turning reference points into log-odds) is fitted first by bracketed secant search with the Illinois correction, then held fixed; the API exposes it as a separate step so a joint fit can be added later without changing the data types. + +**Relative-change form only (owner, 2026-11-21).** The penalty is on `m_k − 1`, not on the weight in its own units. A stated consequence: features with small reference values can barely be distinguished from the reference, so they will usually read "hold". An absolute form is Future Directions. (For `LogisticRegression` there is no reference scale, so section 3.9 uses the coefficient form; that is a flagged deviation, Open Question 1.) + +### 3.4 Per-group ranking metrics + +For each group with at least one chosen and one unchosen item: +- **Percentile:** for each chosen item, the share of the group's unchosen items scored strictly below it, ties counting half, averaged over the group's chosen items. 0.5 is chance. It is the group-wise analogue of AUC, computed per group so a large group does not dominate. +- **Top-own:** the share of the group's chosen items inside its top *m* (*m* = how many it chose), places shared out among tied scores. +- **Top-*k*:** the same for a stated *k*. + +The summary averages over groups (each group counts once) and reports how many were compared. The **pooled** ROC area is not reimplemented: it is `ClassifierEvaluation(scores:outcomes:).auc` applied to the pooled comparable rows, and the toolkit provides the pooling helper. (ClassGraph's equivalent swap is already built, phase M0a.) + +### 3.5 Bootstrap over groups + +Resample **groups** with replacement; a resample is a vector of integer weights (how many times each group appears), so a fit takes `groupWeights` and never copies data. Intervals are percentile intervals over the resamples. Group-level resampling matters because rows within a group share the group's propensity; a row-level bootstrap would understate uncertainty. + +### 3.6 Grouped and nested k-fold + +- **Fold assignment:** balanced, shuffled by seed, every fold used, whole groups per fold. +- **Held-out likelihood and metrics:** fit on the training groups; score the held-out groups by conditional log-likelihood and the metrics of section 3.4. +- **Nested selection:** the penalty λ (and which features are free) is chosen **inside each training set** by an inner grouped k-fold on the training groups only; the outer fold never chooses it. Ties go to the stronger penalty. + +### 3.7 `HeldOutComparison` (the generic part of the adoption question) + +A value type holding, for a chosen metric: the per-fold and pooled **reference** and **refit** values, the **paired difference** (refit minus reference) over held-out groups, its **bootstrap interval** at a stated level, the number of held-out groups, and `intervalExcludesZero` (lower end above zero for a "better" test). It states a fact about the data. It does **not** say "adopt", and it does not know about 25 percent moves or minimum counts: those thresholds are ClassGraph policy and stay there. The toolkit also exposes the per-feature counts of chosen items carrying each feature so the caller can apply its own evidence rule. + +### 3.8 Randomness and determinism + +Generators come from SwiftDeterminism (`SplitMix64`; `Xoshiro256StarStar` is also available), which this library already depends on and re-exports. **SwiftDeterminism is the ground truth (owner, 2026-11-21).** Every public function that draws takes a generator (`inout`) or a seed and documents that the same seed gives the same result; none touches the system generator. ClassGraph's `BacktestRandom` is a hand-rolled copy and is to be **replaced** (phase M0b); if its mixing differs from SwiftDeterminism's, the fold assignment and resamples in the real-archive backtest change and its figures (0.22 points held-out improvement, interval -0.07 to 0.45) may shift slightly. The owner accepted that the parity re-run is recorded both ways (the old figures stay in the ADR amendment as the baseline). Whether the two generators are bit-identical was **not** checked here; the parity test answers it. + +### 3.9 The penalty on `LogisticRegression` + +Today `LogisticRegression.fit` calls `refuseSeparation()` and throws `LogisticRegressionError.separation(variables:)`; its documentation names Firth's penalised likelihood as the remedy and says it is not implemented. This proposal adds a **ridge-type penalty centred on a supplied value** as an additive entry point: + +`NLL(β) + (λ / 2) · Σ_{k ∈ slopes} (β_k − c_k)²`, centre `c` defaulting to zero, the intercept unpenalised. + +With λ > 0 the objective is strictly convex, so the estimate exists and is unique under separation and under a rank-deficient design; the penalised path therefore does not throw `separation` or `rankDeficient` (it still throws `malformedInput` and `didNotConverge`). **The existing `fit(maxIterations:tolerance:)` is untouched**, so every current caller behaves exactly as before; the penalised fit is a new method (`fit(penalty:maxIterations:tolerance:)`), not a new default. The coefficient-space form is the only meaningful one here because `LogisticRegression` has no reference weights; it is **not** the relative-change form of section 3.3, and that difference is flagged as Open Question 1. It is not Firth's penalty (Jeffreys-prior) and the documentation will say so; adding Firth later is not precluded. Standard errors under a penalty are not the classical ones; Open Question 3. + +## 4. API Surface (sketch; names are proposals) + +Conventions read from the current library: generic over `T: Real & Sendable & BinaryFloatingPoint` (as `ClassifierEvaluation`, `LogisticRegression`); failable `init?` when the data cannot support the call; a typed `Error` enum with associated detail; public value types are `Sendable`, and `Codable` for fits (as `LogisticFit`); DocC with a worked example on every public symbol; tab indentation. + +```swift +public enum ChoiceLikelihood: Sendable, Equatable { case subset, ranking } + +public struct GroupedChoiceData: Sendable { + public let groupCount: Int + public init?(groups: [[(features: [T], chosen: Bool)]]) // subset form + public init?(rankedGroups: [(candidates: [[T]], ranking: [Int])]) // top-m by candidate index + public init?(sparseGroups: ...) // Open Question 4: in B1 + public var informativeGroups: [Int] { get } +} + +public enum GroupedChoiceError: Error, Sendable, Equatable { + case noInformativeGroups + case malformedInput(reason: String) + case didNotConverge(iterations: Int, gradientNorm: Double) +} + +public struct GroupedChoiceFit: Sendable, Codable { // multipliers, scale, iterations, converged + public let multipliers: [T]; public let scale: T; public let iterations: Int; public let converged: Bool +} + +public struct GroupedChoiceModel { + public init(data: GroupedChoiceData, reference: [T], likelihood: ChoiceLikelihood) + public func negativeLogLikelihood(_ fit: GroupedChoiceFit, groupWeights: [T]) -> (total: T, chosen: T) + public func fit(groupWeights: [T], penalty: T, frozen: Set = [], start: [T]? = nil) throws -> GroupedChoiceFit +} + +public enum GroupRankingMetrics { + public static func perGroup(scores: [T], data: GroupedChoiceData, k: Int) -> [GroupRanking?] + public static func summary(_ r: [GroupRanking?]) -> GroupRankingSummary + public static func pooledEvaluation(scores: [T], data: GroupedChoiceData) -> ClassifierEvaluation? +} +public enum GroupResampling { + public static func bootstrapWeights(groups: Int, using: inout G) -> [Double] + public static func foldAssignment(groups: Int, folds: Int, using: inout G) -> [Int] +} +public enum GroupedCrossValidation { choosePenalty(...); heldOutComparison(...) -> HeldOutComparison } +public struct HeldOutComparison: Sendable, Codable { reference, refit, difference, interval, level, groups, intervalExcludesZero } + +extension LogisticRegression { // Regression/, additive + public func fit(penalty: LogisticPenalty, maxIterations: Int = 25, tolerance: T = T(1) / T(100_000_000)) throws -> LogisticFit +} +public struct LogisticPenalty { public let lambda: T; public let centre: [T]? } // centre nil = zero +``` + +`penalty` is non-optional in `fit`: "do not refit" is the caller keeping the reference, not a mode of the fitter (an unpenalised grouped fit can diverge under quasi-separation, so it is not offered; a very small λ gives the nearly unpenalised optimum). Public names are settled at review; the shape is the point. + +## 5. MCP Schema + +**Wanted for all seven pieces (owner, 2026-11-21); built as a follow-up in `businessMathMCP`, a separate repository** that pins this library, has its own `CLAUDE.md` and its own design-proposal process (it names this repository's `design_proposal.md` template), and registers tools with `MCPToolInputSchema` / `MCPSchemaProperty`. **Correction to the ClassGraph draft:** that draft said a dataset does not fit the MCP pattern. It does: `multiple_linear_regression` there already takes a predictor matrix `X` as an array of rows, so a grouped dataset is an array of groups of rows. Nothing in this proposal blocks the tools; none is built here. + +Tools to be specified in that repository's proposal, one thin tool per capability: `fit_conditional_logit`, `fit_plackett_luce`, `group_ranking_metrics`, `group_bootstrap_intervals`, `grouped_held_out_comparison`, `fit_penalized_logistic`. Every tool takes a **required `seed`** where anything is drawn, so results are reproducible. Sketch of the core one: + +````markdown +**Tool Description:** Fit a conditional-logit (or Plackett-Luce) choice model within groups, with a penalty toward reference weights. Each group is compared only with its own candidates; a pair nobody chose is unknown, not rejected, so scores are rankings, not probabilities. + +**REQUIRED STRUCTURE (JSON):** +```json +{ + "likelihood": "subset", + "groups": [ + { "features": [[1, 0], [0, 1], [1, 1]], "chosen": [0, 2] }, + { "features": [[0, 1], [1, 0]], "chosen": [1] } + ], + "reference": [2.0, 1.5], + "penalty": 0.05, + "seed": 42 +} +``` + +**Parameter Types:** +- likelihood (string): "subset" (unordered chosen set) or "ranking" (ordered top choices, Plackett-Luce). +- groups (array): each group has features (array of rows, one per candidate, equal width) and chosen (array of candidate indices; for "ranking", in order, best first). +- reference (array of numbers, >= 0): one per feature column. +- penalty (number, > 0): pull toward the reference; larger = closer to it. +- seed (integer): required where resampling is used. +```` + +The MCP-side proposal finalises names and adds a registry test per tool; this repository's gate is unaffected. + +## 6. Constraints & Compliance + +- Swift 6 strict concurrency: value types, `Sendable`; the generator is passed `inout` and none is held. +- No force unwraps, `try!` or force casts; division guards on every ratio (empty groups, zero chosen, zero total weight); guard-driven early returns; fail-silent principle (never return a plausible-but-wrong result): non-convergence and no-informative-groups throw. +- Numerical stability: log-sum-exp shift; groups where `e_m` is not positive and finite are skipped and counted. +- **Type-checking discipline (this repository's `CLAUDE.md`):** CI is Swift 6.2.1; local 6.4 is no evidence about timeouts. At most 3 arithmetic operators per generic expression; intermediates bound to named `let`s with explicit `: T`; no arithmetic inside `#expect` messages. This matters here because the inner loops are generic arithmetic over `T`. +- Floating-point comparisons in tests use accuracy, never `==`; tolerances are measured, per `correct_answers.md`. +- DocC on every public symbol with a worked example; this repository's `.quality-gate.yml` and baseline apply. + +## 7. Source & API Compatibility + +**Breaking changes: none.** Everything is additive: a new folder, and one additive method on `LogisticRegression`. No existing symbol changes; `LogisticRegression.fit(maxIterations:tolerance:)` is untouched, still refuses separation and rank deficiency, and its tests are untouched and must stay green. No existing default changes. `Statistics/Comparison Statistics` is not touched, so WineTaster's pinned API is unaffected. New public type names (`GroupedChoiceData`, `GroupedChoiceModel`, `GroupRankingMetrics`, `HeldOutComparison`, `ChoiceLikelihood`, `LogisticPenalty`) are checked against the library for collisions before B1. Consumers: ClassGraph pins by revision, so nothing changes there until the pin is bumped (phase C); WineTaster pins `alpha.16` exactly and moves only by its own decision. **Type-checking risk:** new generic overloads on an existing type (`fit`) are the shape that has caused CI timeouts here; the penalised `fit` has a different label set and is not an overload of the existing call. + +## 8. Backend Abstraction + +N/A. CPU, pure Swift, no Accelerate. Cost: `O(n·m)` per group per likelihood evaluation. ClassGraph's measured baseline for the code being generalised: 200 bootstrap resamples on a 532-group, about 141,000-row class took 229 seconds in a release build with a flat sparse layout (`zStart/zIndex/zValue`); a dense `[[T]]` layout would be slower, which is why Open Question 4 asks to put a sparse constructor in the first phase. + +## 9. Dependencies + +None new. `Numerics` (for `Real`), already used by `ClassifierEvaluation`; SwiftDeterminism (already a dependency, `from: 1.2.0`) for the generator. + +## 10. Resource budget + +Allocation is `O(rows × features)` for the data plus `O(n·m)` scratch per group (reused). The bootstrap holds weight vectors, not data copies. No new global state. + +## 11. Test Strategy + +Strict TDD (this repository's rule), deterministic synthetic data, reference truth independent of the code (`correct_answers.md`). + +- **Likelihood, hand-computed:** two groups, three candidates, one or two chosen; `e_m` computed by hand **and by brute-force subset enumeration** in the test, compared to the dynamic-programming value to 1e-12; the gradient against a central finite difference. For Plackett-Luce: brute-force over permutations for small *n*, and the first-choice case equals the multinomial logit exactly. +- **The two likelihoods differ:** a hand-worked group with *m* = 2 where the subset and ranking probabilities are computed by hand and are different numbers; with *m* = 1 they are equal. Asserts the section 3.2 statement. +- **Recovery (the test that fails the softmax):** generate groups from known β with group intercepts (some groups choose many, some few); the subset fit recovers β within a measured tolerance on a fixed seed; the softmax-per-choice likelihood is included as a deliberately wrong comparison and is shown biased. A Plackett-Luce recovery test generates rankings by sequential draws and recovers β. +- **Null:** no signal: multipliers stay near 1 under a positive penalty, mean percentile near 0.5, the held-out interval includes zero. +- **Talkative-group bias:** a feature predicting only *which groups choose many* gets no weight from the conditional fit while a pooled `LogisticRegression` assigns it weight; both asserted. +- **Penalty and constraints:** λ very large returns the reference; λ tiny approaches the unpenalised optimum; non-negativity binds (a feature that truly predicts the opposite way ends at 0); `frozen` features stay at 1. +- **Penalised `LogisticRegression`:** perfectly separated data that the existing `fit` refuses gives a finite, unique estimate under λ > 0; λ → large gives the centre; on non-separated data and small λ it approaches the existing unpenalised fit within a measured tolerance; **the existing `fit` is byte-identical in behaviour** (its current tests run unchanged); a rank-deficient design fits under λ > 0. +- **`HeldOutComparison`:** the same model as reference and refit gives difference exactly 0 and an interval containing 0; a deliberately better model gives a lower bound above 0; counts are reported; no threshold is applied. +- **Ranking metrics with ties:** all-equal scores give percentile 0.5 and top-*k* share equal to chance; hand-computed half-credit and shared-places cases; groups without variation return `nil`. +- **Determinism:** same seed gives identical folds, resamples and intervals, a different seed differs; no dependence on `Set` iteration order; a golden run in 10+ separate processes (as ADR-010's did). +- **Fold discipline:** no group in both training and held-out; inner folds never see the outer held-out groups (an adversarial held-out group on a synthetic class). +- **Edge cases:** no informative groups; one group; more folds than groups; zero total group weight; non-finite features rejected at `init?`; a ranking with an index out of range or repeated. +- **Parity (for ClassGraph phase C):** a fixed-seed synthetic class run through the new toolkit and a verbatim copy of ClassGraph's private code gives the same multipliers to a measured tolerance; kept as a regression test. +- **Mutation audit** by the builder (commit before mutating), 50+ mutants across the likelihoods, the penalty and the metrics. +- **Linux:** not runnable locally; the 6.2.1 budget rules of section 6 are followed and the CI run is watched. + +## 12. Architecture Decision Review + +- [x] Reviewed `architecture_decisions.md` (through ADR-010). +- [ ] Supersedes an existing ADR: No. +- [x] Amends: none. Note for ADR-011 that it does not change `LogisticRegression`'s existing refusals; it adds a penalised path beside them. +- [x] New ADR required: **ADR-011**, "Grouped choice models live in `Statistics/GroupedRanking`; the subset likelihood is the conditional logit and is distinct from Plackett-Luce; the penalty is prior-centred." Cross-reference ClassGraph ADR-022 (the origin) and, in ClassGraph, an ADR-022 amendment recording that the private implementation moved here. + +## 13. Adversarial Review + +**Strongest case for a different approach: leave it in ClassGraph.** The code works, is gated, mutation-audited (50 of 50 killed) and used once. Moving it costs a proposal, an upstream build, a pin bump and a parity migration for one consumer today. *Response:* the owner decided to upstream (2026-11-21) on the portfolio rule, on a plausible second use (any "who chose what" data, and the MCP exposure he wants), and because a private copy is where the softmax error would be re-learned. If no second use appears the saving is only the rule and the MCP tools; the proposal stops at B-phases that stand on their own (each is gated and useful separately). + +**Critic: "this ships an analysis protocol, not a library tool."** The *combination* (prior-centred penalty, non-negativity, nested grouped CV, group bootstrap) is a particular protocol. *Response:* each piece is separately exposed and tested, the protocol is a thin layer a caller can ignore, and **the decision policy is deliberately not here**: `HeldOutComparison` reports an interval and counts; "adopt if the lower end is above zero and one weight moved 25 percent with at least 20 pairs" stays in ClassGraph. + +**Critic: "Plackett-Luce is scope creep."** *Response:* it shares the data type, the group structure, the metrics, the bootstrap and the folds, and costs one likelihood function and its tests; it is its own phase (B5) so it can be dropped without touching the rest. Nothing I read in WineTaster needs it today; I do not claim it does. + +**Failure modes named.** +- **Quasi-separation** in the grouped fit: a feature that perfectly picks the chosen items drives its multiplier up. The penalty bounds it; an unpenalised grouped fit is not offered. +- **Candidate-set choice is a modelling decision.** "Everyone else with a page" is a different universe from "everyone"; the data type makes the candidate set explicit. +- **Unlabelled negatives.** An unchosen item is unknown, not rejected. The documentation says so in its first paragraph, because absolute probabilities are not calibrated; the outputs are rankings, by design. +- **Subset versus ranking misuse.** Passing an unordered set to `.ranking` makes the answer depend on an arbitrary order. The constructors are separate (`groups:` versus `rankedGroups:`), so the unordered form cannot be built as a ranking by accident. +- **The relative penalty** makes small-reference features hard to move (section 3.3); stated, with the absolute form as Future Directions. +- **The coefficient-space penalty on `LogisticRegression` differs from the relative form** and the centre defaults to zero, which can surprise a caller who expects shrinkage toward a reference. Documented; Open Question 1. +- **A parity migration can mask a real difference** (including the generator swap); the parity test runs before ClassGraph's copy is deleted and stays as a regression test. +- **Speed.** Dense rows are slower than the sparse layout the backtest uses (section 8); hence Open Question 4. + +## 14. Alternatives Considered + +**Alternative 1: leave it in ClassGraph.** Zero cost, working. Violates the portfolio rule, no MCP exposure, a second consumer would copy it. Rejected by the owner's decision; remains the fallback if no second use appears. + +**Alternative 2: a separate small package.** Small clean dependency. Another repository and pin; this library already holds `ClassifierEvaluation`, Spearman and the SwiftDeterminism dependency these compose with, and the portfolio's direction has been toward folding generic pieces into this library (SwiftGraphMetrics into `Network`, ClassGraph ADR-014). Not recommended. + +**Alternative 3: `LogisticRegression` with a group-indicator column per group (fixed effects as dummies).** No new fitting code. With hundreds of groups it hits the separation and rank-deficiency refusals (groups with none or all chosen), is slow (an `(n+k)` system), and gives the unconditional fixed-effects logit, biased with few choices per group. The conditional likelihood exists to avoid exactly this. Rejected. + +**Alternative 4: swap only the evaluation pieces and keep the fit private.** Smallest change. That is phase M0 in ClassGraph, a step in this plan, already partly built; it does not remove the duplicated fitter. + +**Alternative 5: pooled regression with a "talkative-group" covariate.** The covariate is a proxy; the conditional likelihood removes the group effect exactly. Rejected. + +**Alternative 6: a shared `Statistics/Ranking` parent with `Comparison Statistics` moved under it.** Considered at the owner's request; rejected in section 3.1 (churn in a folder a pinned consumer depends on, no shared code, a different question). + +## 15. Future Directions + +Each would be its own gated proposal; none is promised. +- Joint fit of scale and multipliers; an **absolute** penalty and an L1 option; Firth's penalty on `LogisticRegression`. +- Ties inside a Plackett-Luce ranking; group-level covariates; time-varying choices. +- Plackett-Luce with no covariates (latent item strengths from judge rankings), which would sit next to, not inside, `Comparison Statistics`; only worth a proposal if a consumer (WineTaster is the obvious candidate, not read beyond its README, `Package.swift` and bridge here) asks for it. +- A calibration step for absolute probabilities where unchosen items are known negatives. + +## 16. Documentation Strategy + +- A DocC article beside `2.7-SpearmanSignificance.md` ("Choosing among candidates: conditional logit, Plackett-Luce and ranking evaluation"), with the talkative-group example, the unlabelled-negatives warning, the subset-versus-ranking table, and a cross-link to the Comparison Statistics articles. A short section on the penalised `LogisticRegression` in its article, replacing "not implemented here" with what is and is not. +- `CHANGELOG.md` entry per phase; ADR-011; `project/master_plan.md` Statistics entry reconciled at the end. +- ClassGraph (its own repository): ADR-022 amendment, CHANGELOG, runbook line, master plan; the `weights backtest` output and meaning are unchanged. + +### 16a. Owner decisions incorporated (2026-11-21) + +Split agreed; held-out comparison result type upstream, thresholds stay in ClassGraph; Plackett-Luce included with the first-choice case shared (made precise in 3.2); the penalty also on `LogisticRegression`; generic over `T: Real & Sendable & BinaryFloatingPoint`; relative-change penalty only for now; SwiftDeterminism is the ground truth and the generator swap is accepted with both runs recorded; MCP exposure for everything, as a follow-up in `businessMathMCP`; do it now as a diversion and return to ClassGraph when resolved; upstream check done. + +--- + +## Phasing and process + +| Step | What | Where | Gate | +|---|---|---|---| +| 0 | This proposal and ADR-011 (proposed) | BusinessMath | **owner approval**, section 17 | +| M0a | Replace the hand-written pooled ROC area and the score-band table with `ClassifierEvaluation`; add `BusinessMath` as a `ClassGraphCore` dependency (ADR-022 note). **Built** on ClassGraph branch `backtest-businessmath` at `84f988b` (per its build report; I did not inspect the branch); calibration and gains were not swapped because their buckets do not match the score bands. Awaiting merge | ClassGraph | its gate passed 51/51 | +| M0b | Replace `BacktestRandom` with SwiftDeterminism's `SplitMix64`; parity run and record both figures. **Not built.** Can wait for C | ClassGraph | gate 0/0; real-archive re-run, counts only | +| B1 | `GroupedChoiceData` (dense, and sparse per Q4) and the **subset** likelihood with gradient, unpenalised evaluation only; brute-force and finite-difference tests | BusinessMath | repo gate 0/0; mutation audit | +| B2 | The prior-centred penalty, non-negativity, scale step, `fit`; recovery (fails the softmax), null, talkative-group, penalty tests | BusinessMath | gate; mutation audit | +| B3 | Per-group metrics and the pooled helper | BusinessMath | gate; mutation audit | +| B4 | Group bootstrap, grouped and nested k-fold, `HeldOutComparison` | BusinessMath | gate; mutation audit; determinism across processes | +| B5 | Plackett-Luce (`likelihood: .ranking`), tests including "the two likelihoods differ" | BusinessMath | gate; mutation audit | +| B6 | Penalised `LogisticRegression.fit(penalty:)`; separation and rank-deficiency tests; the existing `fit` unchanged | BusinessMath | gate; mutation audit; existing tests untouched | +| B7 | DocC article, CHANGELOG, ADR-011 accepted, `master_plan.md`; a release tag only on the owner's decision (Open Question 5) | BusinessMath | gate 0/0 | +| C | Bump ClassGraph's pin; parity test (new toolkit versus the private code on a fixed-seed class); delete `BacktestFitter`, the metrics, `BacktestRandom`, the bootstrap and fold code; ADR-022 amendment | ClassGraph | gate 0/0; real-archive re-run reproduces the recorded figures within the stated tolerance | +| D | The MCP tools (section 5), after B7, in `businessMathMCP` under its own proposal and process, pinning this library | businessMathMCP | that repository's gate | + +B1 to B7 are separately gated and each is useful alone; B5 and B6 are independent of B2 to B4 once B1 exists and can be reordered or dropped. For scale: the ClassGraph code being generalised is about 2,100 lines across 7 files and was built, gated and mutation-audited in one agent build cycle; B1 to B7 add generics, a second likelihood, the `LogisticRegression` addition and documentation, so expect more than one cycle, in separate worktrees, one phase per branch. + +Process: merges only on the owner's explicit approval after `git branch --show-current`; no push and no tag without asking; builds in sibling worktrees; builders use synthetic data only; the real-archive runs are the ClassGraph parent's, counts and figures only. + +## 17. Open Questions (those that truly remain) + +1. **Penalty form on `LogisticRegression`.** The owner's "relative change only, for now" applies to the grouped models, which have a reference scale. `LogisticRegression` has none, so I propose the coefficient-space form `(β_k − c_k)²`, centre default zero (ridge), not Firth's. Recommended: **yes, coefficient form on `LogisticRegression`, relative form on the grouped models**, documented side by side. +2. **Plackett-Luce scope.** Strict, untied, top-*m* orderings only; the unordered-set case stays on `.subset`; ties in a ranking are Future Directions. Recommended: **yes**. +3. **Inference under a penalty.** Classical standard errors are not valid for a penalised fit. Proposed: the penalised `LogisticRegression` fit returns the coefficients and convergence but **no classical standard errors**; intervals come from the group bootstrap (grouped models) or a caller-supplied bootstrap. Recommended: **yes**. +4. **Sparse constructor in B1 or later?** The backtest's 229-second figure depends on a flat sparse layout; a dense-only first release would make ClassGraph's parity run slower. Recommended: **include the sparse constructor in B1**, not in Future Directions. +5. **Release cadence.** ClassGraph pins by revision, so a tag is not needed for it; WineTaster pins an exact tag and does not need this. Recommended: **one tag (the next alpha) after B7, at the owner's decision**, not per phase. + +## Proposal Review Checklist + +### Architecture +- [x] Module placement follows the `Statistics/` layout (section 3.1); no shared-parent move (reasoned) +- [x] Naming and error style follow `ClassifierEvaluation` and `LogisticRegression` +- [x] Swift 6 concurrency (value types, `Sendable`, generator passed in) +- [x] No forbidden patterns +- [x] Domain-free: nothing about people or friendship in the toolkit + +### Compatibility & Evolution +- [x] Additive; the existing `LogisticRegression.fit` untouched; `Comparison Statistics` untouched (section 7) +- [x] Incremental adoption (phases separately gated) +- [x] Future directions use "could" or are separately gated +- [x] Six alternatives with advantages and disadvantages + +### MCP Readiness +- [x] Schema sketched and follow-up phase D defined (section 5); a stale claim in the draft corrected + +### Backend Abstraction +- [x] N/A (section 8) + +### Testing & Dependencies +- [x] Hand-computed, brute-force, finite-difference, recovery (fails the softmax), null, talkative-group, penalty, determinism, ties, edge cases, parity +- [x] Reference truth independent of the code +- [x] No new dependencies +- [x] Open questions listed with recommendations + +### Adversarial Review +- [x] Counter-design (section 13, Alternative 1) +- [x] Failure modes named +- [x] Critics' objections with responses + +### Honest limits of this proposal +- No BusinessMath code was written or run; the API in section 4 is a sketch, and names are proposals. +- ClassGraph's M0a branch (`backtest-businessmath`, `84f988b`) is described from its build report, not inspected; M0b's generator swap is not built. +- The "about 40 percent" softmax scale bias is the ClassGraph build agent's measurement on a synthetic class, recorded in its ADR-022; it was not re-measured here. +- Whether ClassGraph's `BacktestRandom` is bit-identical to SwiftDeterminism's `SplitMix64` was not checked. +- That the penalised `LogisticRegression` path can skip the separation and rank-deficiency checks safely was reasoned from the objective's convexity, not by reading every line of `fit`; B6's first tests settle it. +- WineTaster was read at its README, `Package.swift` and `BusinessMathBridge.swift` only. +- The `businessMathMCP` tool pattern was read from `multiple_linear_regression` and its `CLAUDE.md`, not from the whole repository, and its pinned BusinessMath revision was not checked. +- Linux (Swift 6.2.1) behaviour of the generic code is unverified until CI runs. From ca9ff4eae4b58b1c21f7fc3d7a83a07af5a7ed61 Mon Sep 17 00:00:00 2001 From: Justin Purnell Date: Sat, 21 Nov 2026 11:28:20 -0500 Subject: [PATCH 02/13] feat(regression): penalised LogisticRegression.fit(penalty:) (ridge, centred, intercept unpenalised) Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_017dtpLZ6XGCJVmSqc1u4qUt --- .../LogisticRegression+Penalty.swift | 281 +++++++++++ .../Regression/LogisticRegression.swift | 12 +- .../PenalisedLogisticRegressionTests.swift | 439 ++++++++++++++++++ 3 files changed, 729 insertions(+), 3 deletions(-) create mode 100644 Sources/BusinessMath/Statistics/Regression/LogisticRegression+Penalty.swift create mode 100644 Tests/BusinessMathTests/Regression Tests/PenalisedLogisticRegressionTests.swift diff --git a/Sources/BusinessMath/Statistics/Regression/LogisticRegression+Penalty.swift b/Sources/BusinessMath/Statistics/Regression/LogisticRegression+Penalty.swift new file mode 100644 index 00000000..01715533 --- /dev/null +++ b/Sources/BusinessMath/Statistics/Regression/LogisticRegression+Penalty.swift @@ -0,0 +1,281 @@ +// +// LogisticRegression+Penalty.swift +// BusinessMath +// +// A ridge-type penalised fit for ``LogisticRegression``. Additive: the unpenalised +// `fit(maxIterations:tolerance:)` is not touched. +// + +import Foundation +import Numerics + +/// A ridge penalty, centred on a supplied value, for ``LogisticRegression/fit(penalty:maxIterations:tolerance:)``. +/// +/// The fit maximises +/// +/// ``` +/// log L(β) − (λ / 2) · Σ over slopes k of (β_k − c_k)² +/// ``` +/// +/// The intercept is never penalised. With `centre` omitted, `c` is zero and this is +/// ordinary ridge regression; with a centre it shrinks the slopes toward values you +/// supply (a reference model, a previous fit) instead of toward zero. +/// +/// This penalty is in **coefficient space**: it measures how far a coefficient is from its +/// centre in the coefficient's own units, so it depends on how the predictors are scaled. +/// Standardise predictors first, as for any ridge fit. It is not Firth's penalty (a +/// Jeffreys-prior term); it does remove the infinite estimates that separation causes, but +/// by a different route. +/// +/// ```swift +/// let ridge = LogisticPenalty(lambda: 1.0) +/// let towardReference = LogisticPenalty(lambda: 0.5, centre: [0.8, -0.2]) +/// ``` +public struct LogisticPenalty: Sendable, Codable, Equatable { + + /// The penalty strength λ. Must be positive and finite. A very small value gives a fit + /// close to the unpenalised optimum where one exists; zero is refused, because it asks + /// for the unpenalised fit, which is what ``LogisticRegression/fit(maxIterations:tolerance:)`` + /// is for. + public let lambda: T + + /// The value each slope is pulled toward, one per predictor and in the same order, + /// without an entry for the intercept. `nil` means zero for every slope. + public let centre: [T]? + + /// Creates a penalty. + /// + /// Nothing is validated here; ``LogisticRegression/fit(penalty:maxIterations:tolerance:)`` + /// checks the strength and the centre against the data, as the unpenalised fit checks its + /// inputs, so a caller building penalties in a loop gets its errors at one place. + /// + /// - Parameters: + /// - lambda: The penalty strength. + /// - centre: The slopes' reference values, or `nil` for zero. + public init(lambda: T, centre: [T]? = nil) { + self.lambda = lambda + self.centre = centre + } +} + +/// A penalised binomial GLM fit. +/// +/// This carries no standard errors. The classical ones, from `(XᵀWX)⁻¹`, describe the +/// unpenalised estimator and are not valid for a penalised one, and a penalised estimate is +/// biased by design. Resample the observations (a bootstrap) for intervals. +public struct PenalisedLogisticFit: Sendable, Codable { + + /// The coefficients, intercept first when one was fitted. + public let coefficients: [T] + + /// The ordinary log-likelihood of the data at ``coefficients``, without the penalty. + public let logLikelihood: T + + /// The maximised objective: ``logLikelihood`` minus the penalty term. + public let penalisedObjective: T + + /// How many Newton steps were taken. + public let iterations: Int + + /// Whether an intercept was fitted, which decides how ``probability(_:)`` reads its argument. + public let hasIntercept: Bool + + /// The penalty this fit was made with. + public let penalty: LogisticPenalty + + /// The probability of a positive outcome at a point. + /// + /// - Parameter predictors: One value per predictor, *without* an intercept term; the + /// intercept is applied here if the fit has one. + /// - Returns: A probability in [0, 1], or one half if the argument is the wrong width + /// (a probability is the return type, so this cannot throw; it matches + /// ``LogisticFit/probability(_:)``). + public func probability(_ predictors: [T]) -> T { + let offset = hasIntercept ? 1 : 0 + guard predictors.count == coefficients.count - offset else { return T(1) / T(2) } + var linear: T = hasIntercept ? coefficients[0] : T.zero + for index in 0...logistic(linear) + } +} + +extension LogisticRegression { + + /// Fits by Newton's method on the penalised log-likelihood. + /// + /// With λ > 0 the objective is strictly concave, so a maximum exists and is unique + /// whatever the data: under **separation**, where the unpenalised fit throws + /// ``LogisticRegressionError/separation(variables:)``, and under a **rank-deficient** + /// design, where it throws ``LogisticRegressionError/rankDeficient(columns:)``, this + /// returns a fit. Identical columns share their effect equally. There is one exception, + /// below. + /// + /// ```swift + /// let model = LogisticRegression(predictors: [[1], [2], [3], [4], [5], [6]], + /// outcomes: [false, false, false, true, true, true]) + /// let fit = try model.fit(penalty: LogisticPenalty(lambda: 1.0)) // separated; fitted anyway + /// ``` + /// + /// ## What it still refuses + /// + /// - **A constant outcome with an intercept.** The intercept is not penalised, so with + /// every outcome the same class it still runs off to infinity; this throws + /// ``LogisticRegressionError/separation(variables:)`` with no variables, as the + /// unpenalised fit does. Without an intercept the same data has a finite penalised fit. + /// - **Malformed input**, including a penalty that is not positive and finite and a + /// centre of the wrong width. + /// - **An exhausted budget**, as ``LogisticRegressionError/didNotConverge(iterations:gradientNorm:)``. + /// A penalty so small it is nearly the unpenalised problem on separated data takes + /// many steps for the same reason the unpenalised fit diverges. + /// + /// Each Newton step is shortened by halving until the penalised objective does not fall, + /// so a poor first step on strongly separated data cannot overshoot. + /// + /// - Parameters: + /// - penalty: The strength and centre. + /// - maxIterations: Newton steps allowed. + /// - tolerance: Convergence is declared when the largest absolute coefficient change + /// in a full Newton step falls below this. + /// - Returns: The fit. It carries no standard errors; see ``PenalisedLogisticFit``. + /// - Throws: ``LogisticRegressionError``. + public func fit(penalty: LogisticPenalty, + maxIterations: Int = 25, + tolerance: T = T(1) / T(100_000_000)) throws -> PenalisedLogisticFit { + let design = try validatedDesign(requireIdentifiable: false) + let rows = design.count + let columns = design[0].count + let slopes = predictors[0].count + let offset = intercept ? 1 : 0 + + guard penalty.lambda.isFinite, penalty.lambda > T.zero else { + throw LogisticRegressionError.malformedInput(reason: "the penalty must be positive and finite") + } + let centre: [T] = penalty.centre ?? [T](repeating: T.zero, count: slopes) + guard centre.count == slopes else { + throw LogisticRegressionError.malformedInput( + reason: "a centre of \(centre.count) values for \(slopes) predictors") + } + guard centre.allSatisfy({ $0.isFinite }) else { + throw LogisticRegressionError.malformedInput(reason: "a centre value is not finite") + } + if intercept, let first = outcomes.first, outcomes.allSatisfy({ $0 == first }) { + throw LogisticRegressionError.separation(variables: []) + } + + let lambda: T = penalty.lambda + var beta = [T](repeating: T.zero, count: columns) + for index in 0.. 0: the information plus lambda on the slopes is + // positive definite. A singular result here is a numerical failure, reported as + // one rather than as a fit. + throw LogisticRegressionError.didNotConverge(iterations: step, gradientNorm: Double.infinity) + } + var largest: T = T.zero + for index in 0.. largest { largest = size } + } + guard largest.isFinite else { + throw LogisticRegressionError.didNotConverge(iterations: step, gradientNorm: Double.infinity) + } + + // Halve the step until the objective does not fall. A full Newton step is accepted + // whenever it improves, so the quadratic convergence near the optimum is kept. + // "Does not fall" is judged to the rounding floor of the objective: near the + // optimum a correct step changes it by less than the last digit, and rejecting + // those steps would shrink them to nothing and stall short of the tolerance. + let magnitude: T = objective < T.zero ? -objective : objective + let slack: T = T(64) * T.ulpOfOne * Swift.max(T(1), magnitude) + var scale: T = T(1) + var next = beta + var nextObjective = objective + var halvings = 0 + while halvings <= 40 { + for index in 0..= objective - slack { break } + scale /= T(2) + halvings += 1 + } + if halvings <= 40 { + beta = next + objective = nextObjective + } + if largest < tolerance { break } + if step == Swift.max(1, maxIterations) { + let norm: Double = Self.approximateDouble(largest) + throw LogisticRegressionError.didNotConverge(iterations: step, gradientNorm: norm) + } + } + + var probabilities = [T](repeating: T.zero, count: rows) + for row in 0.. T { + var total: T = T.zero + for row in 0.. T.zero ? z + T.log(1 + T.exp(-z)) : T.log(1 + T.exp(z)) + let term: T = observed * z - softplus + total += term + } + var cost: T = T.zero + for index in 0..: S /// unusually good model. This throws ``LogisticRegressionError/separation(variables:)`` /// instead, naming the predictors responsible. The remedy is Firth's penalised /// likelihood, which has a finite estimate under separation; it is not implemented here, -/// and saying so is better than returning the artifact. +/// and saying so is better than returning the artifact. A ridge-type penalised fit, which +/// also has a finite estimate under separation, is available as +/// ``fit(penalty:maxIterations:tolerance:)``; it is a different estimator, not Firth's. /// /// The same reasoning applies to a **rank-deficient** design, where two collinear columns /// can trade effect between them without changing the fit at all. @@ -240,9 +242,13 @@ extension LogisticRegression { /// The design matrix, with an intercept column prepended when one is wanted. /// + /// - Parameter requireIdentifiable: Whether to insist on more observations than + /// predictors, which the unpenalised fit needs to identify its coefficients. The + /// penalised fit identifies them by the penalty and passes `false`. Defaults to `true`, + /// so the unpenalised path is exactly as it was. /// - Returns: One row per observation. /// - Throws: ``LogisticRegressionError/malformedInput(reason:)``. - func validatedDesign() throws -> [[T]] { + func validatedDesign(requireIdentifiable: Bool = true) throws -> [[T]] { guard !predictors.isEmpty, !outcomes.isEmpty else { throw LogisticRegressionError.malformedInput(reason: "no observations") } @@ -260,7 +266,7 @@ extension LogisticRegression { guard predictors.allSatisfy({ $0.allSatisfy { $0.isFinite } }) else { throw LogisticRegressionError.malformedInput(reason: "a predictor is not finite") } - guard predictors.count > width else { + guard !requireIdentifiable || predictors.count > width else { throw LogisticRegressionError.malformedInput( reason: "\(predictors.count) observations cannot identify \(width) predictors") } diff --git a/Tests/BusinessMathTests/Regression Tests/PenalisedLogisticRegressionTests.swift b/Tests/BusinessMathTests/Regression Tests/PenalisedLogisticRegressionTests.swift new file mode 100644 index 00000000..4e6dd2df --- /dev/null +++ b/Tests/BusinessMathTests/Regression Tests/PenalisedLogisticRegressionTests.swift @@ -0,0 +1,439 @@ +// +// PenalisedLogisticRegressionTests.swift +// BusinessMath +// +// The penalised fit: `NLL(β) + (λ/2)·Σ_slopes (β_k − c_k)²`, intercept unpenalised. +// +// Where the expected values come from (see development-guidelines/rules/correct_answers.md): +// +// * The reference coefficients were computed outside this library with a BFGS run on the +// penalised objective (a quasi-Newton route, not the exact-Newton route the +// implementation takes), to a gradient below 1e-10. The objective is strictly convex for +// λ > 0, so the optimum is unique and any correct route reaches it. +// * The stationarity tests do not use a reference at all. The optimum is characterised by +// its gradient: for every slope `Σ x_ik (y_i − p_i) = λ (β_k − c_k)`, and for the +// intercept `Σ (y_i − p_i) = 0`. The test computes both sides from the data and the +// returned coefficients. +// * The duplicated-column identity is derived on paper: two identical columns with equal +// coefficients `b` give the same predictor as one column with coefficient `2b`, and cost +// `λ·b² = (λ/2)/2 · (2b)²` of penalty, so the duplicated fit at λ must predict like the +// single-column fit at λ/2. +// + +import Testing +import Foundation +import Numerics +@testable import BusinessMath + +@Suite("Penalised logistic regression") +struct PenalisedLogisticRegressionTests { + + // MARK: - Fixtures + + /// Not separated: the same ten rows the unpenalised suite fits. + static let overlapX: [[Double]] = (1...10).map { [Double($0)] } + static let overlapY: [Bool] = [false, false, false, false, true, false, true, true, true, true] + + /// Six positives in ten, so the base rate is 0.6 and its logit is not zero. + static let skewedY: [Bool] = [false, false, true, false, true, true, true, true, false, true] + + /// Completely separated by a threshold on the one predictor. + static let separatedX: [[Double]] = (1...8).map { [Double($0)] } + static let separatedY: [Bool] = [false, false, false, false, true, true, true, true] + + /// Both sides of the stationarity condition, as the largest absolute difference. + /// + /// - Returns: the largest absolute value, over every coefficient, of the gradient of the + /// penalised log-likelihood at `coefficients`. + static func largestGradient(x: [[Double]], y: [Bool], coefficients: [Double], + lambda: Double, centre: [Double], intercept: Bool) -> Double { + let offset: Int = intercept ? 1 : 0 + var gradient = [Double](repeating: 0, count: coefficients.count) + for row in 0.. zeroCentred, "a centre above the fit must raise the slope") + } + + // MARK: - The characterisation of the optimum + + @Test("The returned coefficients satisfy the penalised score equations") + func stationarity() throws { + let x: [[Double]] = [[1, 5], [2, 3], [3, 8], [4, 2], [5, 7], [6, 4], + [7, 9], [8, 1], [9, 6], [10, 10], [2, 9], [7, 2]] + let y: [Bool] = [false, false, false, false, true, false, + true, false, true, true, false, true] + let model = LogisticRegression(predictors: x, outcomes: y) + var checked = 0 + for lambda in [0.01, 0.5, 3.0, 40.0] { + for centre in [[0.0, 0.0], [0.7, -0.3]] { + let fit = try model.fit(penalty: LogisticPenalty(lambda: lambda, centre: centre)) + let residual = Self.largestGradient(x: x, y: y, coefficients: fit.coefficients, + lambda: lambda, centre: centre, intercept: true) + #expect(residual < 1e-6, "lambda \(lambda), centre \(centre): gradient \(residual)") + checked += 1 + } + } + #expect(checked == 8) + } + + @Test("The intercept is not penalised: fitted probabilities average to the observed rate") + func interceptUnpenalised() throws { + let model = LogisticRegression(predictors: Self.overlapX, outcomes: Self.skewedY) + for lambda in [0.1, 5.0, 1000.0] { + let fit = try model.fit(penalty: LogisticPenalty(lambda: lambda)) + var total: Double = 0 + for row in Self.overlapX { total += fit.probability(row) } + let mean: Double = total / Double(Self.overlapX.count) + #expect(Swift.abs(mean - 0.6) < 1e-8, "lambda \(lambda): mean fitted probability \(mean)") + } + } + + @Test("An enormous penalty leaves the slopes at the centre and the intercept at the base-rate logit") + func enormousPenalty() throws { + let model = LogisticRegression(predictors: Self.overlapX, outcomes: Self.skewedY) + let fit = try model.fit(penalty: LogisticPenalty(lambda: 1e9, centre: [0.25])) + #expect(Swift.abs(fit.coefficients[1] - 0.25) < 1e-6, "slope \(fit.coefficients[1])") + + let flat = try model.fit(penalty: LogisticPenalty(lambda: 1e9)) + let baseRateLogit: Double = Double.log(0.6 / 0.4) + #expect(Swift.abs(flat.coefficients[1]) < 1e-6, "slope \(flat.coefficients[1])") + #expect(Swift.abs(flat.coefficients[0] - baseRateLogit) < 1e-6, + "intercept \(flat.coefficients[0]), wanted \(baseRateLogit)") + } + + @Test("The reported objective is the log-likelihood minus the penalty, and the optimum beats its neighbours") + func objectiveIsConsistent() throws { + let model = LogisticRegression(predictors: Self.overlapX, outcomes: Self.overlapY) + let lambda = 2.0 + let centre = [0.5] + let fit = try model.fit(penalty: LogisticPenalty(lambda: lambda, centre: centre)) + let shift: Double = fit.coefficients[1] - 0.5 + let penalty: Double = 0.5 * lambda * shift * shift + let wanted: Double = fit.logLikelihood - penalty + #expect(Swift.abs(fit.penalisedObjective - wanted) < 1e-10, + "objective \(fit.penalisedObjective), wanted \(wanted)") + + // Concavity: no nearby point does better, which is what makes this the maximum. + func objective(_ b0: Double, _ b1: Double) -> Double { + var total: Double = 0 + for (row, outcome) in zip(Self.overlapX, Self.overlapY) { + let linear: Double = b0 + b1 * row[0] + let observed: Double = outcome ? 1 : 0 + total += observed * linear - Double.log(1 + Double.exp(linear)) + } + let moved: Double = b1 - 0.5 + let cost: Double = 0.5 * lambda * moved * moved + return total - cost + } + let here = objective(fit.coefficients[0], fit.coefficients[1]) + var worse = 0 + for (d0, d1) in [(0.01, 0.0), (-0.01, 0.0), (0.0, 0.01), (0.0, -0.01), (0.01, 0.01), (-0.01, -0.01)] { + if objective(fit.coefficients[0] + d0, fit.coefficients[1] + d1) < here { worse += 1 } + } + #expect(worse == 6, "only \(worse) of 6 neighbours were worse") + } + + // MARK: - Separation: the case the unpenalised fit refuses + + @Test("Separated data is refused by the unpenalised fit and fitted, finitely, by the penalised one") + func separationFitted() throws { + let model = LogisticRegression(predictors: Self.separatedX, outcomes: Self.separatedY) + #expect(throws: LogisticRegressionError.self) { try model.fit() } + + let fit = try model.fit(penalty: LogisticPenalty(lambda: 1.0)) + let wanted: [Double] = [-5.263947796974564, 1.1697661771053738] + for (got, want) in zip(fit.coefficients, wanted) { + #expect(got.isFinite) + #expect(Swift.abs(got - want) < 1e-6, "coefficient \(got), wanted \(want)") + } + let weaker = try model.fit(penalty: LogisticPenalty(lambda: 0.1)) + let weakerWanted: [Double] = [-12.046345095863714, 2.67696557685767] + for (got, want) in zip(weaker.coefficients, weakerWanted) { + #expect(Swift.abs(got - want) < 1e-5, "coefficient \(got), wanted \(want)") + } + #expect(weaker.coefficients[1] > fit.coefficients[1], + "a weaker penalty must allow a larger slope on separated data") + } + + @Test("On separated data the penalised slope is finite and ordered across a wide range of lambda") + func separationMonotone() throws { + let model = LogisticRegression(predictors: Self.separatedX, outcomes: Self.separatedY) + var previous: Double = .infinity + var steps = 0 + for lambda in [1e-3, 1e-2, 1e-1, 1.0, 10.0, 100.0] { + let slope = try model.fit(penalty: LogisticPenalty(lambda: lambda, centre: [0.0])).coefficients[1] + #expect(slope.isFinite && slope > 0, "lambda \(lambda): slope \(slope)") + #expect(slope < previous, "slope must shrink as lambda grows; lambda \(lambda): \(slope) after \(previous)") + previous = slope + steps += 1 + } + #expect(steps == 6) + } + + @Test("A constant outcome with an intercept still has no maximum, because the intercept is unpenalised") + func constantOutcomeWithIntercept() { + let model = LogisticRegression(predictors: [[1], [2], [3], [4]], + outcomes: [true, true, true, true]) + #expect(throws: LogisticRegressionError.separation(variables: [])) { + try model.fit(penalty: LogisticPenalty(lambda: 1.0)) + } + } + + @Test("A constant outcome without an intercept has a finite penalised fit") + func constantOutcomeWithoutIntercept() throws { + let model = LogisticRegression(predictors: [[1], [2], [3], [4]], + outcomes: [true, true, true, true], intercept: false) + let fit = try model.fit(penalty: LogisticPenalty(lambda: 1.0)) + #expect(fit.coefficients.count == 1) + #expect(fit.coefficients[0].isFinite && fit.coefficients[0] > 0) + let residual = Self.largestGradient(x: [[1], [2], [3], [4]], y: [true, true, true, true], + coefficients: fit.coefficients, lambda: 1.0, + centre: [0], intercept: false) + #expect(residual < 1e-6, "gradient \(residual)") + } + + // MARK: - Rank deficiency + + @Test("A duplicated column is fitted, and predicts like the single column at half the penalty") + func duplicatedColumn() throws { + let single = Self.overlapX + let doubled: [[Double]] = Self.overlapX.map { [$0[0], $0[0]] } + let unpenalisedDoubled = LogisticRegression(predictors: doubled, outcomes: Self.overlapY) + #expect(throws: LogisticRegressionError.self) { try unpenalisedDoubled.fit() } + + let lambda = 2.0 + let both = try unpenalisedDoubled.fit(penalty: LogisticPenalty(lambda: lambda)) + let one = try LogisticRegression(predictors: single, outcomes: Self.overlapY) + .fit(penalty: LogisticPenalty(lambda: lambda / 2)) + #expect(Swift.abs(both.coefficients[1] - both.coefficients[2]) < 1e-8, + "the ridge must split the effect equally between identical columns") + var compared = 0 + for row in single { + let a: Double = both.probability([row[0], row[0]]) + let b: Double = one.probability(row) + #expect(Swift.abs(a - b) < 1e-8, "doubled \(a), single at half the penalty \(b)") + compared += 1 + } + #expect(compared == 10) + } + + @Test("More predictors than observations is identified by the penalty") + func wide() throws { + let x: [[Double]] = [[1, 0, 2, 1, 0], [0, 1, 1, 0, 3], [2, 2, 0, 1, 1], [1, 3, 1, 2, 0]] + let y: [Bool] = [true, false, true, false] + let model = LogisticRegression(predictors: x, outcomes: y) + #expect(throws: LogisticRegressionError.self) { try model.fit() } + let fit = try model.fit(penalty: LogisticPenalty(lambda: 1.0)) + #expect(fit.coefficients.count == 6) + let residual = Self.largestGradient(x: x, y: y, coefficients: fit.coefficients, lambda: 1.0, + centre: [0, 0, 0, 0, 0], intercept: true) + #expect(residual < 1e-6, "gradient \(residual)") + } + + // MARK: - Validation + + @Test("A penalty that is not positive and finite is refused") + func badLambda() { + let model = LogisticRegression(predictors: Self.overlapX, outcomes: Self.overlapY) + var refused = 0 + for lambda in [0.0, -1.0, Double.nan, Double.infinity] { + do { + _ = try model.fit(penalty: LogisticPenalty(lambda: lambda)) + } catch LogisticRegressionError.malformedInput { + refused += 1 + } catch { + Issue.record("lambda \(lambda): wrong error \(error)") + } + } + #expect(refused == 4, "only \(refused) of 4 bad penalties were refused") + } + + @Test("A centre of the wrong width, or not finite, is refused") + func badCentre() { + let model = LogisticRegression(predictors: Self.overlapX, outcomes: Self.overlapY) + var refused = 0 + for centre in [[0.0, 0.0], [], [Double.nan]] { + do { + _ = try model.fit(penalty: LogisticPenalty(lambda: 1.0, centre: centre)) + } catch LogisticRegressionError.malformedInput { + refused += 1 + } catch { + Issue.record("centre \(centre): wrong error \(error)") + } + } + #expect(refused == 3, "only \(refused) of 3 bad centres were refused") + } + + @Test("Malformed data is refused as the unpenalised fit refuses it") + func malformedData() { + let penalty = LogisticPenalty(lambda: 1.0) + var refused = 0 + let models: [LogisticRegression] = [ + LogisticRegression(predictors: [], outcomes: []), + LogisticRegression(predictors: [[1], [2]], outcomes: [true]), + LogisticRegression(predictors: [[1], [2, 3], [4]], outcomes: [true, false, true]), + LogisticRegression(predictors: [[1], [Double.nan], [3]], outcomes: [true, false, true]), + LogisticRegression(predictors: [[], [], []], outcomes: [true, false, true], intercept: false) + ] + for model in models { + do { + _ = try model.fit(penalty: penalty) + } catch LogisticRegressionError.malformedInput { + refused += 1 + } catch { + Issue.record("wrong error \(error)") + } + } + #expect(refused == 5, "only \(refused) of 5 malformed inputs were refused") + } + + @Test("An exhausted iteration budget is reported, not returned as a fit") + func didNotConverge() { + let model = LogisticRegression(predictors: Self.separatedX, outcomes: Self.separatedY) + #expect(throws: LogisticRegressionError.self) { + try model.fit(penalty: LogisticPenalty(lambda: 1e-9), maxIterations: 2) + } + } + + // MARK: - Behaviour of the result + + @Test("Probabilities are inside (0, 1), and a wrong-width argument returns one half") + func probabilityBehaviour() throws { + let fit = try LogisticRegression(predictors: Self.overlapX, outcomes: Self.overlapY) + .fit(penalty: LogisticPenalty(lambda: 1.0)) + for value in [-100.0, 0.0, 5.0, 100.0] { + let p = fit.probability([value]) + #expect(p >= 0 && p <= 1, "p \(p)") + #expect(p.isFinite) + } + let wrongWidth: Double = fit.probability([1.0, 2.0]) + #expect(Swift.abs(wrongWidth - 0.5) < 1e-12, "a wrong-width argument returned \(wrongWidth)") + #expect(fit.hasIntercept) + let low = fit.probability([1.0]) + let high = fit.probability([10.0]) + #expect(high > low, "a positive slope must raise the probability") + } + + @Test("Fitting twice gives identical results") + func deterministic() throws { + let model = LogisticRegression(predictors: Self.overlapX, outcomes: Self.overlapY) + let first = try model.fit(penalty: LogisticPenalty(lambda: 0.7, centre: [0.2])) + let second = try model.fit(penalty: LogisticPenalty(lambda: 0.7, centre: [0.2])) + #expect(first.coefficients == second.coefficients) + #expect(first.iterations == second.iterations) + } + + @Test("The same fit in single precision agrees with double precision") + func floatAgrees() throws { + let doubleFit = try LogisticRegression(predictors: Self.overlapX, outcomes: Self.overlapY) + .fit(penalty: LogisticPenalty(lambda: 1.0)) + let floatX: [[Float]] = Self.overlapX.map { $0.map { Float($0) } } + let floatFit = try LogisticRegression(predictors: floatX, outcomes: Self.overlapY) + .fit(penalty: LogisticPenalty(lambda: 1.0), tolerance: 1e-5) + for (single, double) in zip(floatFit.coefficients, doubleFit.coefficients) { + let gap: Double = Swift.abs(Double(single) - double) + #expect(gap < 1e-3, "Float \(single), Double \(double)") + } + } + + @Test("The result and the penalty round-trip through JSON") + func codable() throws { + let fit = try LogisticRegression(predictors: Self.overlapX, outcomes: Self.overlapY) + .fit(penalty: LogisticPenalty(lambda: 1.0, centre: [0.1])) + let data = try JSONEncoder().encode(fit) + let back = try JSONDecoder().decode(PenalisedLogisticFit.self, from: data) + #expect(back.coefficients == fit.coefficients) + #expect(back.penalty == fit.penalty) + #expect(Swift.abs(back.penalty.lambda - 1.0) < 1e-12) + let centre: [Double] = back.penalty.centre ?? [] + #expect(centre.count == 1 && Swift.abs(centre[0] - 0.1) < 1e-12, "centre \(centre)") + } + + @Test("Without an intercept every coefficient is penalised and probability reads the whole row") + func noIntercept() throws { + let x: [[Double]] = [[1, 2], [2, 1], [3, 5], [4, 3], [5, 6], [6, 2]] + let y: [Bool] = [false, false, true, false, true, true] + let fit = try LogisticRegression(predictors: x, outcomes: y, intercept: false) + .fit(penalty: LogisticPenalty(lambda: 1.0, centre: [0.1, -0.1])) + #expect(fit.coefficients.count == 2) + #expect(!fit.hasIntercept) + let residual = Self.largestGradient(x: x, y: y, coefficients: fit.coefficients, lambda: 1.0, + centre: [0.1, -0.1], intercept: false) + #expect(residual < 1e-6, "gradient \(residual)") + } + + // MARK: - The existing fit is untouched + + @Test("The unpenalised fit still returns its documented reference values") + func existingFitUnchanged() throws { + let fit = try LogisticRegression(predictors: Self.overlapX, outcomes: Self.overlapY).fit() + #expect(Swift.abs(fit.coefficients[0] - (-7.1590107413)) < 1e-6) + #expect(Swift.abs(fit.coefficients[1] - 1.3016383086) < 1e-6) + #expect(fit.standardErrors.count == 2) + } +} From 6a828ae4aebd0de0a6a4cd1565480b65c595ab14 Mon Sep 17 00:00:00 2001 From: Justin Purnell Date: Sat, 21 Nov 2026 12:23:10 -0500 Subject: [PATCH 03/13] feat(grouped-ranking): GroupedChoiceData and the subset (conditional-logit) likelihood (B1) Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_017dtpLZ6XGCJVmSqc1u4qUt --- .../GroupedRanking/GroupedChoiceData.swift | 174 +++++++++++ .../GroupedRanking/GroupedChoiceModel.swift | 270 ++++++++++++++++++ .../GroupedChoiceLikelihoodTests.swift | 250 ++++++++++++++++ .../GroupedChoiceSynthetic.swift | 67 +++++ 4 files changed, 761 insertions(+) create mode 100644 Sources/BusinessMath/Statistics/GroupedRanking/GroupedChoiceData.swift create mode 100644 Sources/BusinessMath/Statistics/GroupedRanking/GroupedChoiceModel.swift create mode 100644 Tests/BusinessMathTests/Grouped Ranking Tests/GroupedChoiceLikelihoodTests.swift create mode 100644 Tests/BusinessMathTests/Grouped Ranking Tests/GroupedChoiceSynthetic.swift diff --git a/Sources/BusinessMath/Statistics/GroupedRanking/GroupedChoiceData.swift b/Sources/BusinessMath/Statistics/GroupedRanking/GroupedChoiceData.swift new file mode 100644 index 00000000..ad1718cd --- /dev/null +++ b/Sources/BusinessMath/Statistics/GroupedRanking/GroupedChoiceData.swift @@ -0,0 +1,174 @@ +// +// GroupedChoiceData.swift +// BusinessMath +// + +import Foundation +import Numerics + +/// Which of the likelihoods a grouped choice model uses. +/// +/// - ``subset``: the group chose an unordered set of its candidates (the *conditional logit*). +public enum ChoiceLikelihood: Sendable, Equatable { + /// The group chose an unordered set of items; how many it chose does not move the weights. + case subset +} + +/// Why a grouped choice model could not be built or fitted. +public enum GroupedChoiceError: Error, Sendable, Equatable { + /// No group has both a chosen and an unchosen candidate with positive weight, so there is nothing to compare. + case noInformativeGroups + /// An argument was the wrong shape or not finite. + case malformedInput(reason: String) + /// The search stopped before the estimate settled. + case didNotConverge(iterations: Int, gradientNorm: Double) +} + +/// Candidates grouped by who chose among them, for fitting what predicts a choice **within** each group. +/// +/// Each group is one chooser's set of candidates: a person and everyone they could have named, a shopper and the +/// products they saw, a query and the results it returned. A candidate is **chosen** or not, and has a row of +/// numeric features. Comparing each group only with itself removes how much each chooser chooses: a talkative group +/// contributes many choices, and a pooled regression would credit any feature that merely correlates with talkative +/// groups. A candidate nobody chose is **unknown**, not rejected, so everything fitted from this data ranks; it does +/// not estimate probabilities. +/// +/// ```swift +/// let data = GroupedChoiceData(groups: [ +/// [(features: [1, 0], chosen: true), (features: [0, 1], chosen: false), (features: [0, 0], chosen: false)], +/// [(features: [1, 1], chosen: true), (features: [0, 0], chosen: false)], +/// ]) +/// // data?.groupCount == 2, data?.featureCount == 2, data?.informativeGroups == [0, 1] +/// ``` +/// +/// Features are stored sparsely (only non-zero entries), so a wide, mostly-zero feature matrix costs memory in +/// proportion to what is present. +public struct GroupedChoiceData: Sendable { + + /// How many groups, including any with no candidates. + public let groupCount: Int + + /// How many feature columns every candidate has. + public let featureCount: Int + + /// How many candidates in all. + public let rowCount: Int + + let groupStart: [Int] + let rowEntryStart: [Int] + let entryFeature: [Int] + let entryValue: [T] + let rowChosen: [Bool] + let rowOffset: [T] + + /// Creates data from dense feature rows. + /// + /// - Parameters: + /// - groups: One array per group; each candidate is its feature row and whether it was chosen. Every row has the + /// same width, and every value is finite. + /// - offsets: Optionally, one fixed number per candidate (same shape as `groups`): a contribution to the score + /// that the fit does not adjust (for example a deduction held at its reference value). Finite values only. + /// - Returns: `nil` for no candidates, rows of different widths, zero width, a non-finite value, or offsets of the + /// wrong shape. + public init?(groups: [[(features: [T], chosen: Bool)]], offsets: [[T]]? = nil) { + guard let width = groups.lazy.compactMap({ $0.first?.features.count }).first, width > 0 else { return nil } + var sparse: [[(features: [(feature: Int, value: T)], chosen: Bool)]] = [] + sparse.reserveCapacity(groups.count) + for group in groups { + var rows: [(features: [(feature: Int, value: T)], chosen: Bool)] = [] + rows.reserveCapacity(group.count) + for candidate in group { + guard candidate.features.count == width else { return nil } + var entries: [(feature: Int, value: T)] = [] + for (index, value) in candidate.features.enumerated() where value != T.zero { + entries.append((feature: index, value: value)) + } + rows.append((features: entries, chosen: candidate.chosen)) + } + sparse.append(rows) + } + self.init(sparseGroups: sparse, featureCount: width, offsets: offsets) + } + + /// Creates data from sparse feature rows: only the features a candidate has, by column index. + /// + /// - Parameters: + /// - sparseGroups: One array per group; each candidate is its `(feature, value)` entries and whether it was chosen. + /// A feature may appear once per candidate; a value of zero is dropped. + /// - featureCount: How many feature columns there are; every index is in `0.. 0, !sparseGroups.isEmpty else { return nil } + if let offsets { + guard offsets.count == sparseGroups.count else { return nil } + for (index, group) in sparseGroups.enumerated() { + guard offsets[index].count == group.count, offsets[index].allSatisfy({ $0.isFinite }) else { return nil } + } + } + var groupStart: [Int] = [0] + var rowEntryStart: [Int] = [0] + var entryFeature: [Int] = [] + var entryValue: [T] = [] + var rowChosen: [Bool] = [] + var rowOffset: [T] = [] + for (groupIndex, group) in sparseGroups.enumerated() { + for (position, candidate) in group.enumerated() { + var seen = Set() + for entry in candidate.features { + guard entry.feature >= 0, entry.feature < featureCount, entry.value.isFinite else { return nil } + guard seen.insert(entry.feature).inserted else { return nil } + guard entry.value != T.zero else { continue } + entryFeature.append(entry.feature) + entryValue.append(entry.value) + } + rowEntryStart.append(entryFeature.count) + rowChosen.append(candidate.chosen) + rowOffset.append(offsets?[groupIndex][position] ?? T.zero) + } + groupStart.append(rowChosen.count) + } + guard !rowChosen.isEmpty else { return nil } + self.groupCount = sparseGroups.count + self.featureCount = featureCount + self.rowCount = rowChosen.count + self.groupStart = groupStart + self.rowEntryStart = rowEntryStart + self.entryFeature = entryFeature + self.entryValue = entryValue + self.rowChosen = rowChosen + self.rowOffset = rowOffset + } + + /// The rows (flat candidate positions) belonging to `group`. + /// + /// Scores handed to the ranking metrics are one per row, in this order. + public func rows(ofGroup group: Int) -> Range { + guard group >= 0, group < groupCount else { return 0..<0 } + return groupStart[group].. Bool { + guard row >= 0, row < rowCount else { return false } + return rowChosen[row] + } + + /// How many candidates `group` chose. + public func chosenCount(group: Int) -> Int { + rows(ofGroup: group).reduce(0) { rowChosen[$1] ? $0 + 1 : $0 } + } + + /// The groups that carry information: at least one chosen and at least one unchosen candidate. + /// + /// A group that chose nothing, or everything, says nothing about what distinguishes a chosen candidate. + public var informativeGroups: [Int] { + (0.. 0 && chosen < rows(ofGroup: group).count + } + } +} diff --git a/Sources/BusinessMath/Statistics/GroupedRanking/GroupedChoiceModel.swift b/Sources/BusinessMath/Statistics/GroupedRanking/GroupedChoiceModel.swift new file mode 100644 index 00000000..f31360a3 --- /dev/null +++ b/Sources/BusinessMath/Statistics/GroupedRanking/GroupedChoiceModel.swift @@ -0,0 +1,270 @@ +// +// GroupedChoiceModel.swift +// BusinessMath +// + +import Foundation +import Numerics + +/// A choice model over groups: what the likelihood of the observed choices is under a set of weights. +/// +/// Each candidate's score is +/// +/// `scale × (offset + Σ multiplier[k] × reference[k] × feature[k])` +/// +/// so the weights being fitted are **multiples of a supplied reference**: a multiplier of `1` leaves a feature at its +/// reference value. A group's chance of having chosen the set it chose is the *conditional logit*: with a propensity of +/// its own to choose (which cancels), the probability of the chosen set is the product of its candidates' `exp(score)` +/// over the sum of that product across every possible set of the same size. That sum is computed exactly, by dynamic +/// programming, in time proportional to candidates times chosen. How many a group chooses therefore cannot move the +/// weights. +/// +/// This is **not** a softmax per chosen candidate over the whole candidate set. That never removes candidates already +/// taken, and on data generated from the intended model it is biased (in the recovery test, a single feature of true weight 1 is fitted at about 0.64); the exact form is not. The two +/// coincide only when every group chooses exactly one. +/// +/// ```swift +/// let data = GroupedChoiceData(groups: [ +/// [(features: [1], chosen: true), (features: [0], chosen: false)], +/// ])! +/// let model = GroupedChoiceModel(data: data, reference: [1], likelihood: .subset)! +/// let nll = model.negativeLogLikelihood(multipliers: [1], scale: 1, groupWeights: [1]) +/// // nll.total == log(1 + e^-1), the chance the chosen candidate was the one with the feature +/// ``` +public struct GroupedChoiceModel: Sendable { + + /// The candidates and which were chosen. + public let data: GroupedChoiceData + + /// The reference weight for each feature column; each is finite and not negative. + public let reference: [T] + + /// Which likelihood the model uses. + public let likelihood: ChoiceLikelihood + + let entryZ: [T] + + /// Creates a model, or `nil` when the reference does not fit the data. + /// + /// - Parameters: + /// - data: The candidates grouped by chooser. + /// - reference: One finite, non-negative weight per feature column. A feature whose reference is `0` contributes + /// nothing and cannot be fitted. + /// - likelihood: The likelihood to use. + public init?(data: GroupedChoiceData, reference: [T], likelihood: ChoiceLikelihood) { + guard reference.count == data.featureCount else { return nil } + guard reference.allSatisfy({ $0.isFinite && $0 >= T.zero }) else { return nil } + self.data = data + self.reference = reference + self.likelihood = likelihood + self.entryZ = zip(data.entryFeature, data.entryValue).map { reference[$0] * $1 } + } + + /// What a fit measured while it was being evaluated. + struct Evaluation { + var negativeLogLikelihood: T = T.zero + var chosen: T = T.zero + var gradient: [T] + var groupsUsed: Int = 0 + } + + /// Working space for one group, reused across groups. + struct Work { + var forward: [T] = [] + var backward: [T] = [] + var terms: [T] = [] + var inclusion: [T] = [] + var taken: [Bool] = [] + } + + /// Each candidate's score under `multipliers` and `scale`, in row order. + func rowScores(multipliers: [T], scale: T) -> [T] { + var result = [T](repeating: T.zero, count: data.rowCount) + for row in 0.. (total: T, chosen: T)? { + guard let evaluation = evaluate(multipliers: multipliers, scale: scale, groupWeights: groupWeights, gradient: false) else { + return nil + } + return (evaluation.negativeLogLikelihood, evaluation.chosen) + } + + /// The likelihood, and optionally its gradient with respect to the multipliers. + func evaluate(multipliers: [T], scale: T, groupWeights: [T], gradient wantGradient: Bool) -> Evaluation? { + guard multipliers.count == data.featureCount, groupWeights.count == data.groupCount else { return nil } + guard groupWeights.allSatisfy({ $0.isFinite && $0 >= T.zero }), scale.isFinite else { return nil } + guard multipliers.allSatisfy({ $0.isFinite }) else { return nil } + let scores = rowScores(multipliers: multipliers, scale: scale) + return evaluate(scores: scores, scale: scale, groupWeights: groupWeights, gradient: wantGradient) + } + + /// The same, from scores already computed. + func evaluate(scores: [T], scale: T, groupWeights: [T], gradient wantGradient: Bool) -> Evaluation { + var evaluation = Evaluation(gradient: [T](repeating: T.zero, count: data.featureCount)) + var work = Work() + var expected = [T](repeating: T.zero, count: data.featureCount) + var taken = [T](repeating: T.zero, count: data.featureCount) + for group in 0.. T.zero, + let result = groupLikelihood(group: group, scores: scores, work: &work, wantInclusion: wantGradient) + else { continue } + let steps: T = T(result.steps) + evaluation.chosen += weight * steps + evaluation.negativeLogLikelihood -= weight * result.logLikelihood + evaluation.groupsUsed += 1 + guard wantGradient else { continue } + for k in 0.. (logLikelihood: T, steps: Int)? { + switch likelihood { + case .subset: + return subsetGroup(group: group, scores: scores, work: &work, wantInclusion: wantInclusion) + } + } + + private func subsetGroup(group: Int, scores: [T], work: inout Work, wantInclusion: Bool) -> (logLikelihood: T, steps: Int)? { + let rows = data.rows(ofGroup: group) + let count = rows.count + var friends = 0 + var maximum: T = -T.infinity + var friendTotal: T = T.zero + for row in rows { + let score: T = scores[row] + maximum = Swift.max(maximum, score) + if data.rowChosen[row] { friends += 1; friendTotal += score } + } + guard friends > 0, friends < count, maximum.isFinite else { return nil } + if work.terms.count < count { + work.terms = [T](repeating: T.zero, count: count) + work.inclusion = work.terms + } + work.taken = rows.map { data.rowChosen[$0] } + for (position, row) in rows.enumerated() { + let shifted: T = scores[row] - maximum + work.terms[position] = T.exp(shifted) + } + let steps: T = T(friends) + let shift: T = steps * maximum + guard wantInclusion else { + let rolled = Self.rollingSum(terms: work.terms, count: count, friends: friends, work: &work.backward) + guard rolled > T.zero, rolled.isFinite else { return nil } + let logRolled: T = T.log(rolled) + let logLikelihood: T = friendTotal - shift - logRolled + return (logLikelihood, friends) + } + let total = Self.inclusion( + terms: work.terms, count: count, friends: friends, forward: &work.forward, backward: &work.backward, + inclusion: &work.inclusion) + guard total > T.zero, total.isFinite else { return nil } + let logTotal: T = T.log(total) + let logLikelihood: T = friendTotal - shift - logTotal + return (logLikelihood, friends) + } + + /// The sum, over every set of `friends` of the first `count` terms, of the product of the set's terms. + static func rollingSum(terms: [T], count: Int, friends: Int, work: inout [T]) -> T { + let width = friends + 1 + if work.count < width { work = [T](repeating: T.zero, count: width) } + for j in 0..= 1 { + let carried: T = value * work[j - 1] + work[j] += carried + j -= 1 + } + } + return work[friends] + } + + /// The same sum, and for each term the chance it is in the set: the term times the sum over sets of `friends - 1` of + /// the others, over the total. + /// + /// A forward table gives the sums over the terms before each one; a rolling backward sum gives the sums over those + /// after it; the two are combined for each term. + static func inclusion( + terms: [T], count: Int, friends: Int, forward: inout [T], backward: inout [T], inclusion: inout [T] + ) -> T { + let width = friends + 1 + let needed = (count + 1) * width + if forward.count < needed { forward = [T](repeating: T.zero, count: needed) } + if backward.count < width { backward = [T](repeating: T.zero, count: width) } + if inclusion.count < count { inclusion = [T](repeating: T.zero, count: count) } + for j in 0.. T.zero, total.isFinite else { return total } + for j in 0..= 1 { + let value: T = terms[i - 1] + let before = (i - 1) * width + var without: T = T.zero + for j in 0..= 1 { + let carried: T = value * backward[j - 1] + backward[j] += carried + j -= 1 + } + i -= 1 + } + return total + } +} diff --git a/Tests/BusinessMathTests/Grouped Ranking Tests/GroupedChoiceLikelihoodTests.swift b/Tests/BusinessMathTests/Grouped Ranking Tests/GroupedChoiceLikelihoodTests.swift new file mode 100644 index 00000000..2b1bb956 --- /dev/null +++ b/Tests/BusinessMathTests/Grouped Ranking Tests/GroupedChoiceLikelihoodTests.swift @@ -0,0 +1,250 @@ +// +// GroupedChoiceLikelihoodTests.swift +// BusinessMath +// +// The subset (conditional-logit) likelihood of grouped choices. +// +// The oracle is brute force. The implementation computes the sum over every set of the chosen size with a dynamic +// programme; the test enumerates the sets themselves and sums their products. Different computations over different +// intermediate structures, so agreement is evidence, and it is exact to rounding. +// + +import Testing +import Foundation +import Numerics +@testable import BusinessMath + +@Suite("Grouped choice: data and subset likelihood") +struct GroupedChoiceLikelihoodTests { + + // MARK: - Helpers + + /// log of the sum, over every size-`size` subset of `scores`, of exp(sum of the subset's scores). By enumeration. + private func bruteForceLogNormaliser(scores: [Double], size: Int) -> Double { + var total = 0.0 + let count = scores.count + for mask in 0..<(1 << count) where mask.nonzeroBitCount == size { + var sum = 0.0 + for bit in 0.. Double { + let size = chosen.filter { $0 }.count + var chosenSum = 0.0 + for (index, score) in scores.enumerated() where chosen[index] { chosenSum += score } + return -(chosenSum - bruteForceLogNormaliser(scores: scores, size: size)) + } + + private func model( + _ groups: [[(features: [Double], chosen: Bool)]], reference: [Double], offsets: [[Double]]? = nil + ) throws -> GroupedChoiceModel { + let data = try #require(GroupedChoiceData(groups: groups, offsets: offsets)) + return try #require(GroupedChoiceModel(data: data, reference: reference, likelihood: .subset)) + } + + // MARK: - Data + + @Test("Dense and sparse construction describe the same data") + func denseEqualsSparse() throws { + let dense = try #require(GroupedChoiceData(groups: [ + [(features: [1, 0, 2], chosen: true), (features: [0, 0, 0], chosen: false)], + [(features: [0, 3, 0], chosen: false), (features: [4, 0, 0], chosen: true)], + ])) + let sparse = try #require(GroupedChoiceData( + sparseGroups: [ + [(features: [(feature: 0, value: 1), (feature: 2, value: 2)], chosen: true), (features: [], chosen: false)], + [(features: [(feature: 1, value: 3)], chosen: false), (features: [(feature: 0, value: 4)], chosen: true)], + ], featureCount: 3)) + #expect(dense.groupCount == 2) + #expect(dense.featureCount == 3) + #expect(dense.rowCount == 4) + #expect(dense.entryFeature == sparse.entryFeature) + #expect(dense.entryValue == sparse.entryValue) + #expect(dense.rowChosen == sparse.rowChosen) + #expect(dense.groupStart == sparse.groupStart) + } + + @Test("Data the model cannot use is refused at construction") + func refusals() { + typealias Row = (features: [Double], chosen: Bool) + #expect(GroupedChoiceData(groups: []) == nil) + #expect(GroupedChoiceData(groups: [[]]) == nil) + #expect(GroupedChoiceData(groups: [[(features: [], chosen: true)]]) == nil) + let ragged: [[Row]] = [[(features: [1, 2], chosen: true), (features: [1], chosen: false)]] + #expect(GroupedChoiceData(groups: ragged) == nil) + let nan: [[Row]] = [[(features: [Double.nan], chosen: true)]] + #expect(GroupedChoiceData(groups: nan) == nil) + let infinite: [[Row]] = [[(features: [Double.infinity], chosen: true)]] + #expect(GroupedChoiceData(groups: infinite) == nil) + let valid: [[Row]] = [[(features: [1], chosen: true), (features: [0], chosen: false)]] + #expect(GroupedChoiceData(groups: valid, offsets: [[0]]) == nil) + #expect(GroupedChoiceData(groups: valid, offsets: [[0, Double.nan]]) == nil) + #expect(GroupedChoiceData(groups: valid, offsets: [[0, 0], [0]]) == nil) + typealias Sparse = (features: [(feature: Int, value: Double)], chosen: Bool) + let outOfRange: [[Sparse]] = [[(features: [(feature: 2, value: 1)], chosen: true)]] + #expect(GroupedChoiceData(sparseGroups: outOfRange, featureCount: 2) == nil) + let negativeIndex: [[Sparse]] = [[(features: [(feature: -1, value: 1)], chosen: true)]] + #expect(GroupedChoiceData(sparseGroups: negativeIndex, featureCount: 2) == nil) + let repeated: [[Sparse]] = [[(features: [(feature: 0, value: 1), (feature: 0, value: 2)], chosen: true)]] + #expect(GroupedChoiceData(sparseGroups: repeated, featureCount: 1) == nil) + #expect(GroupedChoiceData(sparseGroups: outOfRange, featureCount: 0) == nil) + } + + @Test("Informative groups are those with a chosen and an unchosen candidate") + func informative() throws { + let data = try #require(GroupedChoiceData(groups: [ + [(features: [1], chosen: false), (features: [0], chosen: false)], + [(features: [1], chosen: true), (features: [0], chosen: false)], + [(features: [1], chosen: true), (features: [0], chosen: true)], + [], + [(features: [1], chosen: true), (features: [0], chosen: false), (features: [1], chosen: true)], + ])) + #expect(data.informativeGroups == [1, 4]) + #expect(data.chosenCount(group: 4) == 2) + #expect(data.rows(ofGroup: 3).isEmpty) + #expect(data.rows(ofGroup: 4) == 6..<9) + #expect(data.isChosen(row: data.rows(ofGroup: 1).lowerBound)) + #expect(data.rows(ofGroup: 99).isEmpty) + #expect(!data.isChosen(row: -1)) + let first = try #require(GroupedChoiceData(groups: [[(features: [1], chosen: true), (features: [0], chosen: false)]])) + #expect(first.isChosen(row: 0)) + #expect(!first.isChosen(row: 1)) + #expect(!first.isChosen(row: 2)) + } + + @Test("A model refuses a reference that does not fit the data") + func modelRefusals() throws { + let data = try #require(GroupedChoiceData(groups: [[(features: [1, 2], chosen: true), (features: [0, 0], chosen: false)]])) + #expect(GroupedChoiceModel(data: data, reference: [1], likelihood: .subset) == nil) + #expect(GroupedChoiceModel(data: data, reference: [1, -1], likelihood: .subset) == nil) + #expect(GroupedChoiceModel(data: data, reference: [1, Double.nan], likelihood: .subset) == nil) + _ = try #require(GroupedChoiceModel(data: data, reference: [1, 2], likelihood: .subset)) + } + + @Test("Wrong-length or negative weights and non-finite inputs return nil, not a number") + func evaluationRefusals() throws { + let model = try model([[(features: [1], chosen: true), (features: [0], chosen: false)]], reference: [1]) + #expect(model.negativeLogLikelihood(multipliers: [1, 1], scale: 1, groupWeights: [1]) == nil) + #expect(model.negativeLogLikelihood(multipliers: [1], scale: 1, groupWeights: [1, 1]) == nil) + #expect(model.negativeLogLikelihood(multipliers: [1], scale: 1, groupWeights: [-1]) == nil) + #expect(model.negativeLogLikelihood(multipliers: [1], scale: 1, groupWeights: [Double.nan]) == nil) + #expect(model.negativeLogLikelihood(multipliers: [Double.nan], scale: 1, groupWeights: [1]) == nil) + #expect(model.negativeLogLikelihood(multipliers: [1], scale: Double.infinity, groupWeights: [1]) == nil) + } + + // MARK: - Likelihood + + @Test("One chosen of two: the likelihood is the logistic of the score gap (hand value)") + func twoCandidates() throws { + // scores: chosen = scale * m * ref * x = 2 * 1.5 * 1 * 1 = 3; other = 0. P(chosen) = e^3 / (e^3 + 1). + let model = try model([[(features: [1], chosen: true), (features: [0], chosen: false)]], reference: [1]) + let result = try #require(model.negativeLogLikelihood(multipliers: [1.5], scale: 2, groupWeights: [1])) + let expected = log(1 + exp(-3.0)) + #expect(abs(result.total - expected) < 1e-12) + #expect(result.chosen == 1) + } + + @Test("Matches brute-force enumeration for chosen sets of every size") + func bruteForceAgreement() throws { + // Four candidates, two features, chosen set sizes 1, 2, 3. + let features: [[Double]] = [[1, 0.5], [0, 2], [3, 0], [0.5, 1]] + let reference = [2.0, 0.5] + let multipliers = [1.3, 0.7] + let scale = 0.9 + let scores = features.map { scale * (multipliers[0] * reference[0] * $0[0] + multipliers[1] * reference[1] * $0[1]) } + for chosen in [[true, false, false, false], [true, false, true, false], [false, true, true, true], [true, true, false, true]] { + let group = zip(features, chosen).map { (features: $0, chosen: $1) } + let model = try model([group], reference: reference) + let got = try #require(model.negativeLogLikelihood(multipliers: multipliers, scale: scale, groupWeights: [1])) + let want = bruteForceNLL(scores: scores, chosen: chosen) + #expect(abs(got.total - want) < 1e-12) + #expect(abs(got.chosen - Double(chosen.filter { $0 }.count)) < 1e-12) + } + } + + @Test("Offsets add to a candidate's score and are scaled but not multiplied") + func offsets() throws { + let group: [(features: [Double], chosen: Bool)] = [(features: [1], chosen: true), (features: [0], chosen: false), (features: [0], chosen: false)] + let model = try model([group], reference: [2], offsets: [[0, -1.5, 0.25]]) + let scale = 0.8 + let multiplier = 1.25 + let scores = [scale * (multiplier * 2), scale * -1.5, scale * 0.25] + let got = try #require(model.negativeLogLikelihood(multipliers: [multiplier], scale: scale, groupWeights: [1])) + let want = bruteForceNLL(scores: scores, chosen: [true, false, false]) + #expect(abs(got.total - want) < 1e-12) + } + + @Test("Group weights count a group that many times; zero leaves it out") + func groupWeights() throws { + let a: [(features: [Double], chosen: Bool)] = [(features: [1], chosen: true), (features: [0], chosen: false), (features: [2], chosen: false)] + let b: [(features: [Double], chosen: Bool)] = [(features: [0], chosen: true), (features: [1], chosen: false)] + let both = try model([a, b], reference: [1]) + let onlyA = try model([a], reference: [1]) + let onlyB = try model([b], reference: [1]) + let one = try #require(onlyA.negativeLogLikelihood(multipliers: [1.1], scale: 1, groupWeights: [1])) + let two = try #require(onlyB.negativeLogLikelihood(multipliers: [1.1], scale: 1, groupWeights: [1])) + let mixed = try #require(both.negativeLogLikelihood(multipliers: [1.1], scale: 1, groupWeights: [2, 0])) + #expect(abs(mixed.total - 2 * one.total) < 1e-12) + #expect(mixed.chosen == 2) + let sum = try #require(both.negativeLogLikelihood(multipliers: [1.1], scale: 1, groupWeights: [1, 1])) + #expect(abs(sum.total - (one.total + two.total)) < 1e-12) + #expect(sum.chosen == 2) + } + + @Test("Groups with nothing to compare contribute nothing and are not counted") + func uninformativeSkipped() throws { + let none: [(features: [Double], chosen: Bool)] = [(features: [1], chosen: false), (features: [0], chosen: false)] + let all: [(features: [Double], chosen: Bool)] = [(features: [1], chosen: true), (features: [0], chosen: true)] + let good: [(features: [Double], chosen: Bool)] = [(features: [1], chosen: true), (features: [0], chosen: false)] + let model = try model([none, all, good, []], reference: [1]) + let evaluation = try #require(model.evaluate(multipliers: [1], scale: 1, groupWeights: [1, 1, 1, 1], gradient: true)) + #expect(evaluation.groupsUsed == 1) + #expect(evaluation.chosen == 1) + let alone = try self.model([good], reference: [1]) + let want = try #require(alone.negativeLogLikelihood(multipliers: [1], scale: 1, groupWeights: [1])) + #expect(abs(evaluation.negativeLogLikelihood - want.total) < 1e-12) + } + + @Test("Scores far apart stay finite (the sums are shifted by the largest score)") + func stability() throws { + let group: [(features: [Double], chosen: Bool)] = [(features: [1], chosen: true), (features: [0], chosen: false), (features: [0.5], chosen: false)] + let model = try model([group], reference: [1]) + // Scores 800, 0 and 400: exp(800) overflows a Double; the shifted computation does not. + let result = try #require(model.negativeLogLikelihood(multipliers: [1], scale: 800, groupWeights: [1])) + #expect(result.total.isFinite) + // The chosen candidate is overwhelmingly the most likely, so the NLL is ~ log(1 + e^-400 + e^-800) ~ 0. + #expect(abs(result.total) < 1e-12) + } + + // MARK: - Gradient + + @Test("The analytic gradient matches a central finite difference") + func gradientMatchesFiniteDifference() throws { + let g1: [(features: [Double], chosen: Bool)] = [ + (features: [1, 0.5, 0], chosen: true), (features: [0, 2, 1], chosen: false), (features: [3, 0, 0.5], chosen: true), + (features: [0.5, 1, 0], chosen: false), + ] + let g2: [(features: [Double], chosen: Bool)] = [ + (features: [0, 1, 1], chosen: true), (features: [2, 0, 0], chosen: false), (features: [1, 1, 1], chosen: false), + ] + let model = try model([g1, g2], reference: [2, 0.5, 1.5], offsets: [[0, 0.1, -0.2, 0], [0, 0, 0.3]]) + let multipliers = [1.2, 0.8, 1.1] + let scale = 0.7 + let weights = [1.0, 2.0] + let analytic = try #require(model.evaluate(multipliers: multipliers, scale: scale, groupWeights: weights, gradient: true)).gradient + let step = 1e-6 + for k in 0..<3 { + var up = multipliers, down = multipliers + up[k] += step + down[k] -= step + let high = try #require(model.negativeLogLikelihood(multipliers: up, scale: scale, groupWeights: weights)).total + let low = try #require(model.negativeLogLikelihood(multipliers: down, scale: scale, groupWeights: weights)).total + let numeric = (high - low) / (2 * step) + #expect(abs(analytic[k] - numeric) < 1e-7) + } + } +} diff --git a/Tests/BusinessMathTests/Grouped Ranking Tests/GroupedChoiceSynthetic.swift b/Tests/BusinessMathTests/Grouped Ranking Tests/GroupedChoiceSynthetic.swift new file mode 100644 index 00000000..d5aad0b0 --- /dev/null +++ b/Tests/BusinessMathTests/Grouped Ranking Tests/GroupedChoiceSynthetic.swift @@ -0,0 +1,67 @@ +// +// GroupedChoiceSynthetic.swift +// BusinessMath +// +// Synthetic grouped choices drawn from the exact model the toolkit fits, so the fit has a known answer. +// + +import Foundation +@testable import BusinessMath + +/// Groups of candidates whose chosen sets are drawn from the conditional-logit distribution with known weights. +enum GroupedChoiceSynthetic { + + typealias Group = [(features: [Double], chosen: Bool)] + + /// Draws `groups` groups of `candidates` candidates. A group picks its size from `sizes` (round-robin, so some groups + /// choose many and some few), then a subset of that size with probability proportional to the product of + /// `exp(beta · features)` over the subset: the exact conditional-logit distribution. + /// + /// Feature `j` is binary with chance 0.3 (`j % 3 == 0`), binary with chance 0.5 (`j % 3 == 1`), or uniform on [0, 2). + static func make(seed: UInt64, groups: Int, candidates: Int, sizes: [Int], beta: [Double]) -> [Group] { + var generator = SplitMix64(seed: seed) + var result: [Group] = [] + result.reserveCapacity(groups) + for index in 0.. Set { + let count = weights.count + var masks: [Int] = [] + var cumulative: [Double] = [] + var total = 0.0 + for mask in 0..<(1 << count) where mask.nonzeroBitCount == size { + var product = 1.0 + for bit in 0..= target } ?? (masks.count - 1) + let mask = masks[picked] + return Set((0.. Date: Sat, 21 Nov 2026 12:34:28 -0500 Subject: [PATCH 04/13] feat(grouped-ranking): the prior-centred penalty, non-negativity, scale step and fit (B2) Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_017dtpLZ6XGCJVmSqc1u4qUt --- .../GroupedRanking/GroupedChoiceFit.swift | 294 ++++++++++++++++++ .../GroupedChoiceFitTests.swift | 281 +++++++++++++++++ 2 files changed, 575 insertions(+) create mode 100644 Sources/BusinessMath/Statistics/GroupedRanking/GroupedChoiceFit.swift create mode 100644 Tests/BusinessMathTests/Grouped Ranking Tests/GroupedChoiceFitTests.swift diff --git a/Sources/BusinessMath/Statistics/GroupedRanking/GroupedChoiceFit.swift b/Sources/BusinessMath/Statistics/GroupedRanking/GroupedChoiceFit.swift new file mode 100644 index 00000000..6d8e992a --- /dev/null +++ b/Sources/BusinessMath/Statistics/GroupedRanking/GroupedChoiceFit.swift @@ -0,0 +1,294 @@ +// +// GroupedChoiceFit.swift +// BusinessMath +// + +import Foundation +import Numerics + +/// The result of fitting a ``GroupedChoiceModel``. +/// +/// A candidate's score under the fit is `scale × (offset + Σ multipliers[k] × reference[k] × feature[k])`. +public struct GroupedChoiceFit: Sendable, Equatable { + + /// How much each feature's reference weight was multiplied; `1` leaves the reference value. + public let multipliers: [T] + + /// Log-odds per reference point: the scale at which the reference weights best explain the choices. + public let scale: T + + /// How many steps the search took (zero for a scale-only fit). + public let iterations: Int + + /// Whether the search stopped because it stopped moving. + public let converged: Bool + + /// Creates a fit. + public init(multipliers: [T], scale: T, iterations: Int, converged: Bool) { + self.multipliers = multipliers + self.scale = scale + self.iterations = iterations + self.converged = converged + } +} + +extension GroupedChoiceFit: Codable where T: Codable {} + +extension GroupedChoiceModel { + + /// The negative log-likelihood of the observed choices under `fit`; see ``negativeLogLikelihood(multipliers:scale:groupWeights:)``. + public func negativeLogLikelihood(_ fit: GroupedChoiceFit, groupWeights: [T]) -> (total: T, chosen: T)? { + negativeLogLikelihood(multipliers: fit.multipliers, scale: fit.scale, groupWeights: groupWeights) + } + + /// Each candidate's score under `fit`, one per row of the data, for ranking. + public func scores(for fit: GroupedChoiceFit) -> [T]? { + guard fit.multipliers.count == data.featureCount, fit.scale.isFinite, fit.multipliers.allSatisfy({ $0.isFinite }) else { return nil } + return rowScores(multipliers: fit.multipliers, scale: fit.scale) + } + + /// The scale that best turns the reference weights into log-odds: the single number the multipliers are then fitted around. + /// + /// The log-likelihood is concave in the scale, so its derivative is bracketed and the root found by regula falsi with the + /// Illinois correction. A derivative that is not positive even at a tiny scale (the reference weights explain nothing) + /// gives the floor, `1e-6`. + /// + /// - Parameter groupWeights: How much each group counts; see ``negativeLogLikelihood(multipliers:scale:groupWeights:)``. + /// - Throws: ``GroupedChoiceError/malformedInput(reason:)`` for weights of the wrong length or not finite and non-negative, + /// ``GroupedChoiceError/noInformativeGroups`` when no group with positive weight has anything to compare. + public func fitScale(groupWeights: [T]) throws -> T { + try validate(groupWeights: groupWeights) + let ones = [T](repeating: T(1), count: data.featureCount) + let unscaled = rowScores(multipliers: ones, scale: T(1)) + var work = Work() + + func derivative(_ scale: T) -> T { + let scores = unscaled.map { $0 * scale } + var total: T = T.zero + for group in 0.. T.zero, + groupLikelihood(group: group, scores: scores, work: &work, wantInclusion: true) != nil + else { continue } + var taken: T = T.zero + var expected: T = T.zero + for (position, row) in data.rows(ofGroup: group).enumerated() { + let value: T = unscaled[row] + if work.taken[position] { taken += value } + let share: T = work.inclusion[position] * value + expected += share + } + let gap: T = taken - expected + total += weight * gap + } + return total + } + + let floor: T = T(1) / T(1_000_000) + var low: T = floor + var high: T = T(1) + var lowValue: T = derivative(low) + guard lowValue > T.zero else { return floor } + var highValue: T = derivative(high) + var growth = 0 + while highValue > T.zero, growth < 40 { + low = high + lowValue = highValue + high *= T(2) + highValue = derivative(high) + growth += 1 + } + var retained = 0 + var estimate: T = (low + high) / T(2) + let tolerance: T = T(1) / T(10_000_000) + let flat: T = T(1) / T(1_000_000_000) + for _ in 0..<60 { + guard lowValue > highValue else { break } + let span: T = high - low + let next: T = low + span * lowValue / (lowValue - highValue) + guard next > low, next < high else { break } + let value: T = derivative(next) + estimate = next + if value > T.zero { + low = next + lowValue = value + if retained > 0 { highValue /= T(2) } + retained = 1 + } else { + high = next + highValue = value + if retained < 0 { lowValue /= T(2) } + retained = -1 + } + let width: T = high - low + let bound: T = tolerance * (T(1) + low) + if width <= bound || Swift.abs(value) < flat { break } + } + return Swift.max(estimate, floor) + } + + /// A fit that keeps every multiplier at `1` and fits only the scale: the reference weights, calibrated. + /// + /// - Throws: As for ``fitScale(groupWeights:)``. + public func referenceFit(groupWeights: [T]) throws -> GroupedChoiceFit { + let scale = try fitScale(groupWeights: groupWeights) + return GroupedChoiceFit( + multipliers: [T](repeating: T(1), count: data.featureCount), scale: scale, iterations: 0, converged: true) + } + + /// Fits the scale, then the multipliers around the reference. + /// + /// With the scale held, the multipliers `m` (each at least zero) minimise + /// `negativeLogLikelihood / chosen + (penalty / 2) × Σ (m[k] − 1)²`. The penalty pulls each weight toward its reference + /// value, on the **relative** change, so a data set has to argue for any move: a very large penalty returns the reference + /// and a very small one approaches the unpenalised optimum. The objective is convex, so the optimum is unique. It is solved + /// by projected accelerated gradient descent with a backtracking line search and a restart whenever the objective rises. + /// + /// A feature whose reference is `0` cannot move (its multiplier is not identified) and stays at `1`. + /// + /// - Parameters: + /// - groupWeights: How much each group counts: `0` leaves it out, `2` counts it twice, as in a resample. + /// - penalty: The pull toward the reference; finite and not negative. + /// - frozen: Feature columns that keep a multiplier of `1`. + /// - start: Where to begin, one value per feature (negative values are raised to zero); `nil` starts at the reference. + /// - maxIterations: The most steps to take. + /// - Throws: ``GroupedChoiceError/malformedInput(reason:)``, ``GroupedChoiceError/noInformativeGroups``, or + /// ``GroupedChoiceError/didNotConverge(iterations:gradientNorm:)`` when the steps run out or the line search fails + /// while the projected gradient is still large. A result that did not settle is never returned as if it had. + public func fit( + groupWeights: [T], penalty: T, frozen: Set = [], start: [T]? = nil, maxIterations: Int = 300 + ) throws -> GroupedChoiceFit { + try validate(groupWeights: groupWeights) + guard penalty.isFinite, penalty >= T.zero else { throw GroupedChoiceError.malformedInput(reason: "penalty must be finite and not negative") } + guard maxIterations > 0 else { throw GroupedChoiceError.malformedInput(reason: "maxIterations must be positive") } + if let start { + guard start.count == data.featureCount, start.allSatisfy({ $0.isFinite }) else { + throw GroupedChoiceError.malformedInput(reason: "start must have one finite value per feature") + } + } + let scale = try fitScale(groupWeights: groupWeights) + let ones = [T](repeating: T(1), count: data.featureCount) + let free = (0.. T.zero } + guard !free.isEmpty else { return GroupedChoiceFit(multipliers: ones, scale: scale, iterations: 0, converged: true) } + var totalChosen: T = T.zero + for group in data.informativeGroups { + let weighted: T = groupWeights[group] * T(data.chosenCount(group: group)) + totalChosen += weighted + } + guard totalChosen > T.zero else { throw GroupedChoiceError.noInformativeGroups } + let half: T = T(1) / T(2) + + func objective(_ multipliers: [T], gradient wantGradient: Bool) -> (value: T, gradient: [T])? { + guard let evaluated = evaluate(multipliers: multipliers, scale: scale, groupWeights: groupWeights, gradient: wantGradient) else { + return nil + } + var value: T = evaluated.negativeLogLikelihood / totalChosen + var gradient = [T](repeating: T.zero, count: data.featureCount) + for k in free { + let distance: T = multipliers[k] - T(1) + let square: T = distance * distance + value += half * penalty * square + let likelihoodPart: T = evaluated.gradient[k] / totalChosen + gradient[k] = likelihoodPart + penalty * distance + } + return (value, gradient) + } + + var current = ones + if let start { for k in free { current[k] = Swift.max(start[k], T.zero) } } + var extrapolated = current + var momentum: T = T(1) + var step: T = half + guard var currentValue = objective(current, gradient: false)?.value else { + throw GroupedChoiceError.malformedInput(reason: "the objective is not finite at the starting point") + } + var iterations = 0 + var converged = false + var stalled = false + let settle: T = T(1) / T(1_000_000) + let rounding: T = T(1) / T(100_000_000_000_000) + while iterations < maxIterations { + iterations += 1 + guard let here = objective(extrapolated, gradient: true) else { break } + var candidate = extrapolated + var candidateValue: T = T.zero + var accepted = false + var attempts = 0 + while attempts < 40 { + attempts += 1 + guard step > T.zero else { break } + for k in free { + let moved: T = extrapolated[k] - step * here.gradient[k] + candidate[k] = Swift.max(moved, T.zero) + } + guard let tried = objective(candidate, gradient: false) else { step *= half; continue } + candidateValue = tried.value + var directional: T = T.zero + var squared: T = T.zero + for k in free { + let move: T = candidate[k] - extrapolated[k] + directional += here.gradient[k] * move + squared += move * move + } + let quadratic: T = squared / (T(2) * step) + let bound: T = here.value + directional + quadratic + if candidateValue <= bound + rounding { accepted = true; break } + step *= half + } + guard accepted else { stalled = true; break } + var largest: T = T.zero + for k in free { let moved: T = Swift.abs(candidate[k] - current[k]); largest = Swift.max(largest, moved) } + let restart: Bool = candidateValue > currentValue + let inside: T = T(1) + T(4) * momentum * momentum + let root: T = inside.squareRoot() + let nextMomentum: T = restart ? T(1) : (T(1) + root) / T(2) + let blend: T = restart ? T.zero : (momentum - T(1)) / nextMomentum + for k in free { + let pushed: T = candidate[k] + blend * (candidate[k] - current[k]) + extrapolated[k] = Swift.max(pushed, T.zero) + } + current = candidate + currentValue = candidateValue + momentum = nextMomentum + step *= T(3) / T(2) + if largest < settle { converged = true; break } + } + if !converged { + let norm = projectedGradientNorm(at: current, free: free, objective: { objective($0, gradient: true) }) + let accepted: T = T(1) / T(100_000) + guard stalled, norm <= accepted else { + throw GroupedChoiceError.didNotConverge(iterations: iterations, gradientNorm: Double(norm)) + } + converged = true + } + return GroupedChoiceFit(multipliers: current, scale: scale, iterations: iterations, converged: converged) + } + + /// The size of the gradient that the non-negativity constraint leaves free to act: a component pushing a multiplier that + /// sits at zero further below zero does not count. + private func projectedGradientNorm( + at multipliers: [T], free: [Int], objective: ([T]) -> (value: T, gradient: [T])? + ) -> T { + guard let here = objective(multipliers) else { return T.infinity } + var sum: T = T.zero + for k in free { + let component: T = here.gradient[k] + let pinned: Bool = multipliers[k] <= T.zero && component > T.zero + guard !pinned else { continue } + sum += component * component + } + return sum.squareRoot() + } + + private func validate(groupWeights: [T]) throws { + guard groupWeights.count == data.groupCount else { + throw GroupedChoiceError.malformedInput(reason: "groupWeights must have one entry per group") + } + guard groupWeights.allSatisfy({ $0.isFinite && $0 >= T.zero }) else { + throw GroupedChoiceError.malformedInput(reason: "groupWeights must be finite and not negative") + } + var informative = false + for group in data.informativeGroups where groupWeights[group] > T.zero { informative = true; break } + guard informative else { throw GroupedChoiceError.noInformativeGroups } + } +} diff --git a/Tests/BusinessMathTests/Grouped Ranking Tests/GroupedChoiceFitTests.swift b/Tests/BusinessMathTests/Grouped Ranking Tests/GroupedChoiceFitTests.swift new file mode 100644 index 00000000..391048ba --- /dev/null +++ b/Tests/BusinessMathTests/Grouped Ranking Tests/GroupedChoiceFitTests.swift @@ -0,0 +1,281 @@ +// +// GroupedChoiceFitTests.swift +// BusinessMath +// +// Fitting the grouped choice model: recovery of known weights, the failure of the per-choice softmax, the penalty +// and its constraints, and refusals. +// +// Reference truth is the data-generating weights, which the code never sees. Tolerances are measured, not guessed: +// they are set from the spread of the estimate over seeds (see each test). +// + +import Testing +import Foundation +import Numerics +@testable import BusinessMath + +@Suite("Grouped choice: fitting") +struct GroupedChoiceFitTests { + + private typealias Group = GroupedChoiceSynthetic.Group + + private func model(_ groups: [Group], reference: [Double]) throws -> GroupedChoiceModel { + let data = try #require(GroupedChoiceData(groups: groups)) + return try #require(GroupedChoiceModel(data: data, reference: reference, likelihood: .subset)) + } + + private func ones(_ model: GroupedChoiceModel) -> [Double] { [Double](repeating: 1, count: model.data.groupCount) } + + // MARK: - Recovery + + @Test("Recovers known weights, from groups that choose different numbers of candidates") + func recovery() throws { + let beta = [0.9, 0.4, 0.7] + let groups = GroupedChoiceSynthetic.make(seed: 11, groups: 1500, candidates: 8, sizes: [1, 2, 3, 4, 5], beta: beta) + let model = try model(groups, reference: [1, 1, 1]) + let fit = try model.fit(groupWeights: ones(model), penalty: 1e-6) + #expect(fit.converged) + for k in 0..<3 { + let effective = fit.scale * fit.multipliers[k] + #expect(abs(effective - beta[k]) < RecoveryTolerance.weight) + } + } + + @Test("A softmax per chosen candidate is biased on the same data; the conditional likelihood is not") + func softmaxFails() throws { + let groups = GroupedChoiceSynthetic.make(seed: 7, groups: 3000, candidates: 8, sizes: [2, 3, 4], beta: [1.0]) + // The conditional fit. + let model = try model(groups, reference: [1]) + let fit = try model.fit(groupWeights: ones(model), penalty: 1e-6) + let conditional = fit.scale * fit.multipliers[0] + // The deliberately wrong comparison: for every chosen candidate, a softmax over the WHOLE candidate set. + func derivative(_ weight: Double) -> Double { + var total = 0.0 + for group in groups { + let denominator = group.reduce(0.0) { $0 + exp(weight * $1.features[0]) } + let expected = group.reduce(0.0) { $0 + $1.features[0] * exp(weight * $1.features[0]) } / denominator + for candidate in group where candidate.chosen { total += candidate.features[0] - expected } + } + return total + } + var low = 0.0, high = 5.0 + for _ in 0..<60 { + let middle = (low + high) / 2 + if derivative(middle) > 0 { low = middle } else { high = middle } + } + let softmax = (low + high) / 2 + #expect(abs(conditional - 1.0) < 0.1) + #expect(abs(softmax - 1.0) > 0.25) + } + + @Test("With no signal the effective weights are close to zero") + func nullFit() throws { + let groups = GroupedChoiceSynthetic.make(seed: 3, groups: 800, candidates: 8, sizes: [2, 3], beta: [0, 0, 0]) + let model = try model(groups, reference: [1, 1, 1]) + let fit = try model.fit(groupWeights: ones(model), penalty: 0.5) + for k in 0..<3 { #expect(abs(fit.scale * fit.multipliers[k]) < 0.15) } + } + + @Test("A feature that only separates groups cannot be given weight; a pooled regression gives it weight") + func talkativeGroupBias() throws { + // Feature 0 predicts the choice. Feature 1 is 1 for every candidate in the groups that choose many and 0 in the + // groups that choose few: it predicts which GROUPS choose, not which candidates. + let base = GroupedChoiceSynthetic.make(seed: 21, groups: 1200, candidates: 8, sizes: [1, 5], beta: [0.8]) + let groups: [Group] = base.enumerated().map { index, group in + let talkative: Double = index % 2 == 1 ? 1 : 0 + return group.map { (features: [$0.features[0], talkative], chosen: $0.chosen) } + } + let model = try model(groups, reference: [1, 1]) + let fit = try model.fit(groupWeights: ones(model), penalty: 0.01) + // The conditional fit leaves the group-level feature exactly where it started: its gradient is zero. + #expect(abs(fit.multipliers[1] - 1) < 1e-9) + // A pooled regression assigns it a large coefficient. + var predictors: [[Double]] = [] + var outcomes: [Bool] = [] + for group in groups { for row in group { predictors.append(row.features); outcomes.append(row.chosen) } } + let pooled = try LogisticRegression(predictors: predictors, outcomes: outcomes).fit() + #expect(pooled.coefficients[2] > 0.8) + } + + // MARK: - The scale + + @Test("The scale is the maximiser of the likelihood in the scale") + func scaleIsMaximiser() throws { + let groups = GroupedChoiceSynthetic.make(seed: 5, groups: 600, candidates: 8, sizes: [2, 3], beta: [0.6, 0.3]) + let model = try model(groups, reference: [1, 1]) + let weights = ones(model) + let scale = try model.fitScale(groupWeights: weights) + func nll(_ value: Double) -> Double { + model.negativeLogLikelihood(multipliers: [1, 1], scale: value, groupWeights: weights)?.total ?? .infinity + } + for neighbour in [scale * 0.9, scale * 0.99, scale * 1.01, scale * 1.1] { #expect(nll(scale) < nll(neighbour)) } + let reference = try model.referenceFit(groupWeights: weights) + #expect(reference.multipliers == [1, 1]) + #expect(reference.scale == scale) + #expect(reference.iterations == 0) + } + + // MARK: - Penalty and constraints + + @Test("A very large penalty returns the reference; a very small one the unpenalised optimum") + func penaltyEnds() throws { + let groups = GroupedChoiceSynthetic.make(seed: 13, groups: 900, candidates: 8, sizes: [2, 3, 4], beta: [0.9, 0.4]) + let model = try model(groups, reference: [1, 1]) + let weights = ones(model) + let pinned = try model.fit(groupWeights: weights, penalty: 1e7) + for value in pinned.multipliers { #expect(abs(value - 1) < 1e-4) } + let loose = try model.fit(groupWeights: weights, penalty: 1e-9) + let looser = try model.fit(groupWeights: weights, penalty: 1e-12) + for k in 0..<2 { #expect(abs(loose.multipliers[k] - looser.multipliers[k]) < 1e-3) } + #expect(abs(loose.multipliers[0] - 1) > 0.05 || abs(loose.multipliers[1] - 1) > 0.05) + } + + @Test("The fit sits at the optimum: the gradient of the penalised objective is zero for every multiplier above zero") + func firstOrderOptimality() throws { + let groups = GroupedChoiceSynthetic.make(seed: 37, groups: 600, candidates: 8, sizes: [2, 3, 4], beta: [0.9, 0.4, 0.7]) + let model = try model(groups, reference: [1, 1, 1]) + let weights = ones(model) + for penalty in [0.5, 0.05] { + let fit = try model.fit(groupWeights: weights, penalty: penalty) + let evaluated = try #require(model.evaluate(multipliers: fit.multipliers, scale: fit.scale, groupWeights: weights, gradient: true)) + for k in 0..<3 where fit.multipliers[k] > 1e-9 { + let slope = evaluated.gradient[k] / evaluated.chosen + penalty * (fit.multipliers[k] - 1) + #expect(abs(slope) < 1e-3) + } + } + } + + @Test("A penalty of zero is allowed and recovers the weights on well-posed data") + func zeroPenalty() throws { + let beta = [0.9, 0.4] + let groups = GroupedChoiceSynthetic.make(seed: 83, groups: 1200, candidates: 8, sizes: [2, 3, 4], beta: beta) + let model = try model(groups, reference: [1, 1]) + let fit = try model.fit(groupWeights: ones(model), penalty: 0) + for k in 0..<2 { #expect(abs(fit.scale * fit.multipliers[k] - beta[k]) < RecoveryTolerance.weight) } + } + + @Test("A feature that truly predicts the opposite way ends at zero, never negative") + func nonNegativity() throws { + let groups = GroupedChoiceSynthetic.make(seed: 17, groups: 1200, candidates: 8, sizes: [2, 3, 4], beta: [0.9, -0.8]) + let model = try model(groups, reference: [1, 1]) + let fit = try model.fit(groupWeights: ones(model), penalty: 1e-6) + #expect(fit.multipliers[1] == 0) + #expect(fit.multipliers[0] > 0.3) + } + + @Test("Frozen features and features with a zero reference stay at one") + func frozenAndZeroReference() throws { + let groups = GroupedChoiceSynthetic.make(seed: 19, groups: 800, candidates: 8, sizes: [2, 3], beta: [0.9, 0.4, 0.7]) + let weights = [Double](repeating: 1, count: 800) + let frozenModel = try model(groups, reference: [1, 1, 1]) + let frozen = try frozenModel.fit(groupWeights: weights, penalty: 1e-6, frozen: [1]) + #expect(frozen.multipliers[1] == 1) + #expect(frozen.multipliers[0] != 1) + let zeroModel = try model(groups, reference: [1, 0, 1]) + let zero = try zeroModel.fit(groupWeights: weights, penalty: 1e-6) + #expect(zero.multipliers[1] == 1) + let allFrozen = try frozenModel.fit(groupWeights: weights, penalty: 1e-6, frozen: [0, 1, 2]) + #expect(allFrozen.multipliers == [1, 1, 1]) + #expect(allFrozen.iterations == 0) + } + + @Test("Counting a group twice is the same as repeating it") + func weightsEqualDuplication() throws { + let groups = GroupedChoiceSynthetic.make(seed: 23, groups: 40, candidates: 6, sizes: [1, 2, 3], beta: [0.7, 0.3]) + let weighted = try model(groups, reference: [1, 1]) + var counts = [Double](repeating: 1, count: 40) + counts[3] = 2 + counts[10] = 0 + counts[11] = 3 + var repeated: [Group] = [] + for (index, group) in groups.enumerated() { for _ in 0..= 0) } + for k in 0..<2 { #expect(abs(clamped.multipliers[k] - cold.multipliers[k]) < 1e-3) } + } + + @Test("Scores under a fit are one per candidate, and a fit of the wrong width or with a non-finite value has none") + func scoresForFit() throws { + let groups = GroupedChoiceSynthetic.make(seed: 91, groups: 20, candidates: 5, sizes: [2], beta: [0.9, 0.4]) + let model = try model(groups, reference: [1, 2]) + let fit = GroupedChoiceFit(multipliers: [1.5, 0.5], scale: 2, iterations: 0, converged: true) + let scores = try #require(model.scores(for: fit)) + #expect(scores.count == model.data.rowCount) + // The first candidate's score by hand: scale x (m0 x r0 x f0 + m1 x r1 x f1) = 2 x (1.5 x 1 x f0 + 0.5 x 2 x f1). + let first = groups[0][0].features + #expect(abs(scores[0] - 2 * (1.5 * first[0] + 1.0 * first[1])) < 1e-12) + #expect(model.scores(for: GroupedChoiceFit(multipliers: [1], scale: 1, iterations: 0, converged: true)) == nil) + #expect(model.scores(for: GroupedChoiceFit(multipliers: [1, Double.nan], scale: 1, iterations: 0, converged: true)) == nil) + #expect(model.scores(for: GroupedChoiceFit(multipliers: [1, 1], scale: Double.infinity, iterations: 0, converged: true)) == nil) + } + + @Test("The same data and seed give the same fit") + func deterministic() throws { + let groups = GroupedChoiceSynthetic.make(seed: 29, groups: 300, candidates: 8, sizes: [2, 3], beta: [0.5, 0.5]) + let model = try model(groups, reference: [1, 1]) + let first = try model.fit(groupWeights: ones(model), penalty: 0.1) + let second = try model.fit(groupWeights: ones(model), penalty: 0.1) + #expect(first == second) + } + + @Test("A fit can be recovered from its own coding") + func codable() throws { + let fit = GroupedChoiceFit(multipliers: [1.5, 0], scale: 0.7, iterations: 12, converged: true) + let decoded = try JSONDecoder().decode(GroupedChoiceFit.self, from: JSONEncoder().encode(fit)) + #expect(decoded == fit) + } + + // MARK: - Refusals + + @Test("Bad arguments throw, and a result that did not settle is never returned") + func refusals() throws { + let groups = GroupedChoiceSynthetic.make(seed: 31, groups: 100, candidates: 6, sizes: [2], beta: [0.9, 0.4]) + let model = try model(groups, reference: [1, 1]) + let weights = ones(model) + #expect(throws: GroupedChoiceError.malformedInput(reason: "penalty must be finite and not negative")) { + try model.fit(groupWeights: weights, penalty: -1) + } + #expect(throws: GroupedChoiceError.malformedInput(reason: "penalty must be finite and not negative")) { + try model.fit(groupWeights: weights, penalty: .nan) + } + #expect(throws: GroupedChoiceError.malformedInput(reason: "groupWeights must have one entry per group")) { + try model.fit(groupWeights: [1], penalty: 1) + } + #expect(throws: GroupedChoiceError.malformedInput(reason: "groupWeights must be finite and not negative")) { + try model.fit(groupWeights: [Double](repeating: -1, count: 100), penalty: 1) + } + #expect(throws: GroupedChoiceError.malformedInput(reason: "start must have one finite value per feature")) { + try model.fit(groupWeights: weights, penalty: 1, start: [1]) + } + #expect(throws: GroupedChoiceError.malformedInput(reason: "maxIterations must be positive")) { + try model.fit(groupWeights: weights, penalty: 1, maxIterations: 0) + } + #expect(throws: GroupedChoiceError.noInformativeGroups) { + try model.fit(groupWeights: [Double](repeating: 0, count: 100), penalty: 1) + } + #expect(throws: GroupedChoiceError.noInformativeGroups) { try model.fitScale(groupWeights: [Double](repeating: 0, count: 100)) } + #expect(throws: GroupedChoiceError.self) { try model.fit(groupWeights: weights, penalty: 1e-9, maxIterations: 1) } + } +} + +/// Tolerances measured from the spread of the estimate over seeds (see the tests that use them). +enum RecoveryTolerance { + /// Effective weight (scale × multiplier) against the truth, 1500 groups of 8, three features. + static let weight = 0.12 +} From f4d7895beb38113b8587745ea8e82cf53c345eee Mon Sep 17 00:00:00 2001 From: Justin Purnell Date: Sat, 21 Nov 2026 12:45:35 -0500 Subject: [PATCH 05/13] feat(grouped-ranking): per-group ranking metrics and the pooled evaluation (B3) Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_017dtpLZ6XGCJVmSqc1u4qUt --- .../GroupedRanking/GroupRankingMetrics.swift | 183 ++++++++++++++++++ .../GroupRankingMetricsTests.swift | 131 +++++++++++++ 2 files changed, 314 insertions(+) create mode 100644 Sources/BusinessMath/Statistics/GroupedRanking/GroupRankingMetrics.swift create mode 100644 Tests/BusinessMathTests/Grouped Ranking Tests/GroupRankingMetricsTests.swift diff --git a/Sources/BusinessMath/Statistics/GroupedRanking/GroupRankingMetrics.swift b/Sources/BusinessMath/Statistics/GroupedRanking/GroupRankingMetrics.swift new file mode 100644 index 00000000..39497d9f --- /dev/null +++ b/Sources/BusinessMath/Statistics/GroupedRanking/GroupRankingMetrics.swift @@ -0,0 +1,183 @@ +// +// GroupRankingMetrics.swift +// BusinessMath +// + +import Foundation +import Numerics + +/// How well a set of scores ranked one group's chosen candidates among its unchosen ones. +public struct GroupRanking: Sendable, Equatable { + + /// The average, over the group's chosen candidates, of the share of unchosen candidates scored below them, with a tie + /// counting half. `0.5` is chance; `1` ranks every chosen candidate above every unchosen one. + public let percentile: T + + /// The share of the group's chosen candidates inside its top *m*, where *m* is how many it chose. A tie shares its places. + public let topOwn: T + + /// The share of the group's chosen candidates inside its top `k`. A tie shares its places. + public let topK: T + + /// Creates a ranking result. + public init(percentile: T, topOwn: T, topK: T) { + self.percentile = percentile + self.topOwn = topOwn + self.topK = topK + } +} + +/// Ranking figures averaged over groups, each group counting once. +public struct GroupRankingSummary: Sendable, Equatable { + + /// How many groups were compared. + public let groups: Int + + /// The mean of ``GroupRanking/percentile``, or `nil` when no group was compared. + public let meanPercentile: T? + + /// The mean of ``GroupRanking/topOwn``, or `nil` when no group was compared. + public let topOwnShare: T? + + /// The mean of ``GroupRanking/topK``, or `nil` when no group was compared. + public let topKShare: T? + + /// Creates a summary. + public init(groups: Int, meanPercentile: T?, topOwnShare: T?, topKShare: T?) { + self.groups = groups + self.meanPercentile = meanPercentile + self.topOwnShare = topOwnShare + self.topKShare = topKShare + } +} + +/// Ranking metrics computed **within** each group. +/// +/// A pooled area under the ROC curve is dominated by large groups and mixes scores from different choosers. These +/// figures are computed per group and then averaged with each group counting once, so a group with a hundred +/// candidates does not outweigh one with five. An unchosen candidate is unknown, not rejected, so these measure how well +/// the scores rank, not how likely a choice is. +/// +/// ```swift +/// // One group of four: scores 3, 2, 1, 0; the first and third candidates were chosen. +/// let data = GroupedChoiceData(groups: [[ +/// (features: [3], chosen: true), (features: [2], chosen: false), +/// (features: [1], chosen: true), (features: [0], chosen: false), +/// ]])! +/// let rankings = GroupRankingMetrics.perGroup(scores: [3, 2, 1, 0], data: data, k: 1)! +/// // rankings[0]?.percentile == 0.75, topOwn == 0.5, topK == 0.5 +/// ``` +public enum GroupRankingMetrics { + + /// One result per group, or `nil` for a group with no chosen candidate, no unchosen candidate, or a score that is not finite. + /// + /// - Parameters: + /// - scores: One score per row of the data, higher meaning more likely chosen; see ``GroupedChoiceData/rows(ofGroup:)``. + /// - data: The grouped candidates. + /// - k: The cut-off for ``GroupRanking/topK``; at least `1`. + /// - Returns: `nil` when `scores` is not one per row or `k` is below `1`. + public static func perGroup( + scores: [T], data: GroupedChoiceData, k: Int + ) -> [GroupRanking?]? { + guard scores.count == data.rowCount, k >= 1 else { return nil } + return (0..(_ rankings: [GroupRanking?]) -> GroupRankingSummary { + let present = rankings.compactMap { $0 } + guard !present.isEmpty else { return GroupRankingSummary(groups: 0, meanPercentile: nil, topOwnShare: nil, topKShare: nil) } + let count: T = T(present.count) + let percentile: T = present.reduce(T.zero) { $0 + $1.percentile } / count + let own: T = present.reduce(T.zero) { $0 + $1.topOwn } / count + let cut: T = present.reduce(T.zero) { $0 + $1.topK } / count + return GroupRankingSummary(groups: present.count, meanPercentile: percentile, topOwnShare: own, topKShare: cut) + } + + /// The pooled evaluation (ROC area and the rest) over every comparable group's candidates, by ``ClassifierEvaluation``. + /// + /// Only groups with both a chosen and an unchosen candidate are pooled. The area is not reimplemented here. + /// + /// - Returns: `nil` when `scores` is not one per row, no group is comparable, or a score is not finite. + public static func pooledEvaluation( + scores: [T], data: GroupedChoiceData + ) -> ClassifierEvaluation? { + guard scores.count == data.rowCount else { return nil } + var pooledScores: [T] = [] + var outcomes: [Bool] = [] + for group in data.informativeGroups { + for row in data.rows(ofGroup: group) { + pooledScores.append(scores[row]) + outcomes.append(data.rowChosen[row]) + } + } + return ClassifierEvaluation(scores: pooledScores, outcomes: outcomes) + } + + static func ranking( + group: Int, scores: [T], data: GroupedChoiceData, k: Int + ) -> GroupRanking? { + var all: [T] = [] + var friends: [T] = [] + var others: [T] = [] + for row in data.rows(ofGroup: group) { + let score: T = scores[row] + guard score.isFinite else { return nil } + all.append(score) + if data.rowChosen[row] { friends.append(score) } else { others.append(score) } + } + guard !friends.isEmpty, !others.isEmpty else { return nil } + all.sort() + others.sort() + let count: T = T(all.count) + let unchosen: T = T(others.count) + let own: T = T(friends.count) + let cut: T = T(k) + let half: T = T(1) / T(2) + var percentile: T = T.zero + var topOwn: T = T.zero + var topK: T = T.zero + for score in friends { + let low = lowerBound(others, score) + let high = upperBound(others, score) + let below: T = T(low) + let tied: T = T(high - low) + let credit: T = below + half * tied + percentile += credit / unchosen + let sharedHigh = upperBound(all, score) + let sharedLow = lowerBound(all, score) + let above: T = count - T(sharedHigh) + let shared: T = T(sharedHigh - sharedLow) + guard shared > T.zero else { continue } + topOwn += clamp((own - above) / shared) + topK += clamp((cut - above) / shared) + } + return GroupRanking(percentile: percentile / own, topOwn: topOwn / own, topK: topK / own) + } + + private static func clamp(_ value: T) -> T { + Swift.min(Swift.max(value, T.zero), T(1)) + } + + /// The first index whose element is not below `value`. + private static func lowerBound(_ sorted: [T], _ value: T) -> Int { + var low = 0 + var high = sorted.count + while low < high { + let middle = (low + high) / 2 + if sorted[middle] < value { low = middle + 1 } else { high = middle } + } + return low + } + + /// The first index whose element is above `value`. + private static func upperBound(_ sorted: [T], _ value: T) -> Int { + var low = 0 + var high = sorted.count + while low < high { + let middle = (low + high) / 2 + if sorted[middle] <= value { low = middle + 1 } else { high = middle } + } + return low + } +} diff --git a/Tests/BusinessMathTests/Grouped Ranking Tests/GroupRankingMetricsTests.swift b/Tests/BusinessMathTests/Grouped Ranking Tests/GroupRankingMetricsTests.swift new file mode 100644 index 00000000..835bbfba --- /dev/null +++ b/Tests/BusinessMathTests/Grouped Ranking Tests/GroupRankingMetricsTests.swift @@ -0,0 +1,131 @@ +// +// GroupRankingMetricsTests.swift +// BusinessMath +// +// Per-group ranking metrics. Every expected value is worked by hand in the comment beside it. +// + +import Testing +import Foundation +import Numerics +@testable import BusinessMath + +@Suite("Grouped choice: ranking metrics") +struct GroupRankingMetricsTests { + + private func data(_ groups: [[Bool]]) throws -> GroupedChoiceData { + let rows = groups.map { group in group.map { (features: [1.0], chosen: $0) } } + return try #require(GroupedChoiceData(groups: rows)) + } + + @Test("Hand-worked group: scores 3, 2, 1, 0 with the first and third chosen") + func handWorked() throws { + // Chosen scores 3 and 1; unchosen 2 and 0. + // Percentile: for 3, both unchosen are below (1); for 1, one is below (0.5); mean 0.75. + // Top-own (m = 2): 3 is in the top 2 (1); 1 is third (0); mean 0.5. + // Top-1: 3 is first (1); 1 is not (0); mean 0.5. + let data = try data([[true, false, true, false]]) + let all = try #require(GroupRankingMetrics.perGroup(scores: [3, 2, 1, 0], data: data, k: 1)) + let result = try #require(all[0]) + #expect(abs(result.percentile - 0.75) < 1e-12) + #expect(abs(result.topOwn - 0.5) < 1e-12) + #expect(abs(result.topK - 0.5) < 1e-12) + } + + @Test("A tie with an unchosen candidate earns half credit and shares its places") + func tieHandWorked() throws { + // Scores 2, 2, 1; the first chosen. Unchosen scores 2 and 1: one below (1), one tied (0.5): (1 + 0.5) / 2 = 0.75. + // Top-own (m = 1): nothing is above; two candidates share score 2, so the chosen one has half a place: 1/2 = 0.5. + let data = try data([[true, false, false]]) + let all = try #require(GroupRankingMetrics.perGroup(scores: [2, 2, 1], data: data, k: 5)) + let result = try #require(all[0]) + #expect(abs(result.percentile - 0.75) < 1e-12) + #expect(abs(result.topOwn - 0.5) < 1e-12) + #expect(result.topK == 1) + } + + @Test("Equal scores everywhere give chance: percentile one half, top-own share m over n") + func allTied() throws { + let data = try data([[true, true, false, false, false]]) + let all = try #require(GroupRankingMetrics.perGroup(scores: [1, 1, 1, 1, 1], data: data, k: 2)) + let result = try #require(all[0]) + #expect(abs(result.percentile - 0.5) < 1e-12) + #expect(abs(result.topOwn - 2.0 / 5.0) < 1e-15) + #expect(abs(result.topK - 2.0 / 5.0) < 1e-15) + } + + @Test("Groups with nothing to compare, or a score that is not a number, have no result") + func noResult() throws { + let data = try data([[false, false], [true, true], [], [true, false], [true, false]]) + let scores: [Double] = [1, 2, 3, 4, 5, 6, Double.nan, 0] + // Rows: group 0 -> 0,1; group 1 -> 2,3; group 2 empty; group 3 -> 4,5; group 4 -> 6,7. + let results = try #require(GroupRankingMetrics.perGroup(scores: scores, data: data, k: 1)) + #expect(results.count == 5) + #expect(results[0] == nil) + #expect(results[1] == nil) + #expect(results[2] == nil) + _ = try #require(results[3]) + #expect(results[4] == nil) + } + + @Test("Wrong-length scores or a cut-off below one are refused") + func refusals() throws { + let data = try data([[true, false]]) + #expect(GroupRankingMetrics.perGroup(scores: [1], data: data, k: 1) == nil) + #expect(GroupRankingMetrics.perGroup(scores: [1, 0], data: data, k: 0) == nil) + #expect(GroupRankingMetrics.pooledEvaluation(scores: [1], data: data) == nil) + } + + @Test("The summary averages groups, each counting once, and counts them") + func summary() throws { + let rankings: [GroupRanking?] = [ + GroupRanking(percentile: 1, topOwn: 1, topK: 1), nil, GroupRanking(percentile: 0.5, topOwn: 0, topK: 0.5), + ] + let result = GroupRankingMetrics.summary(rankings) + #expect(result.groups == 2) + let mean = try #require(result.meanPercentile) + let own = try #require(result.topOwnShare) + let cut = try #require(result.topKShare) + #expect(abs(mean - 0.75) < 1e-12) + #expect(abs(own - 0.5) < 1e-12) + #expect(abs(cut - 0.75) < 1e-12) + let empty = GroupRankingMetrics.summary([GroupRanking?](arrayLiteral: nil, nil)) + #expect(empty.groups == 0) + #expect(empty.meanPercentile == nil) + } + + @Test("A large group does not outweigh a small one in the per-group mean, but does in the pooled area") + func groupWiseNotPooled() throws { + // A group of 100 ranked perfectly (percentile 1) and a group of 2 ranked wrongly (percentile 0). + var big = [Bool](repeating: false, count: 100) + big[0] = true + big[1] = true + let small = [true, false] + let data = try data([big, small]) + var scores = (0..<100).map { Double(200 - $0) } + scores += [0, 1] + let rankings = try #require(GroupRankingMetrics.perGroup(scores: scores, data: data, k: 1)) + let summary = GroupRankingMetrics.summary(rankings) + #expect(summary.groups == 2) + let groupMean = try #require(summary.meanPercentile) + #expect(abs(groupMean - 0.5) < 1e-12) + let pooled = try #require(GroupRankingMetrics.pooledEvaluation(scores: scores, data: data)) + // Pooled over 3 chosen and 99 unchosen rows, the large group's rows decide the area: it is far above one half. + #expect(pooled.auc > 0.6) + } + + @Test("The pooled evaluation covers only comparable groups, and is the ClassifierEvaluation of those rows") + func pooled() throws { + let data = try data([[true, false, false], [true, true], [false, false], [false, true]]) + let scores: [Double] = [3, 1, 2, 9, 9, 5, 5, 0, 4] + // Comparable groups: 0 (rows 0-2) and 3 (rows 7-8). + let expected = try #require(ClassifierEvaluation( + scores: [3, 1, 2, 0, 4], outcomes: [true, false, false, false, true])) + let pooled = try #require(GroupRankingMetrics.pooledEvaluation(scores: scores, data: data)) + #expect(pooled.positiveCount == expected.positiveCount) + #expect(pooled.negativeCount == expected.negativeCount) + #expect(pooled.auc == expected.auc) + let none = try self.data([[true, true], [false]]) + #expect(GroupRankingMetrics.pooledEvaluation(scores: [1, 2, 3], data: none) == nil) + } +} From 05abf47b3b1b00550c2a0496cd9768d4e6669fc5 Mon Sep 17 00:00:00 2001 From: Justin Purnell Date: Sat, 21 Nov 2026 12:55:44 -0500 Subject: [PATCH 06/13] feat(grouped-ranking): group bootstrap, grouped and nested k-fold, HeldOutComparison (B4) Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_017dtpLZ6XGCJVmSqc1u4qUt --- .../GroupedRanking/GroupResampling.swift | 64 ++++ .../GroupedCrossValidation.swift | 286 ++++++++++++++++++ .../GroupedRanking/HeldOutComparison.swift | 87 ++++++ .../GroupResamplingTests.swift | 114 +++++++ .../GroupedCrossValidationTests.swift | 217 +++++++++++++ 5 files changed, 768 insertions(+) create mode 100644 Sources/BusinessMath/Statistics/GroupedRanking/GroupResampling.swift create mode 100644 Sources/BusinessMath/Statistics/GroupedRanking/GroupedCrossValidation.swift create mode 100644 Sources/BusinessMath/Statistics/GroupedRanking/HeldOutComparison.swift create mode 100644 Tests/BusinessMathTests/Grouped Ranking Tests/GroupResamplingTests.swift create mode 100644 Tests/BusinessMathTests/Grouped Ranking Tests/GroupedCrossValidationTests.swift diff --git a/Sources/BusinessMath/Statistics/GroupedRanking/GroupResampling.swift b/Sources/BusinessMath/Statistics/GroupedRanking/GroupResampling.swift new file mode 100644 index 00000000..6d5e257f --- /dev/null +++ b/Sources/BusinessMath/Statistics/GroupedRanking/GroupResampling.swift @@ -0,0 +1,64 @@ +// +// GroupResampling.swift +// BusinessMath +// + +import Foundation +import Numerics + +/// Resampling whole groups, never rows. +/// +/// Rows within a group share the group's propensity to choose, so a row-level bootstrap or fold assignment would put +/// a group's candidates on both sides of a split and understate every uncertainty. Everything here works on groups, and +/// a resample is a vector of weights (how many times each group appears), so a fit takes `groupWeights` and no data is copied. +/// +/// ## Determinism +/// +/// Every function takes a generator, and the same generator state gives the same result. None touches the system +/// generator. Draws use ``below(_:using:)``, which is unbiased and does not depend on the standard library's own bounded-draw +/// algorithm, so a result does not change between Swift releases. Use ``SplitMix64`` (from SwiftDeterminism) for a seeded stream. +public enum GroupResampling { + + /// A whole number from zero up to, not including, `bound`, drawn without modulo bias; zero when `bound` is not positive. + public static func below(_ bound: Int, using generator: inout G) -> Int { + guard bound > 1 else { return 0 } + let limit = UInt64(bound) + // Reject the short final block of the 64-bit range so every residue is equally likely. + let threshold = (0 &- limit) % limit + var draw = generator.next() + while draw < threshold { draw = generator.next() } + return Int(draw % limit) + } + + /// How many times each of `groups` groups appears in one bootstrap resample: `groups` draws with replacement. + /// + /// The weights are whole numbers (as `T`), and sum to `groups`. + /// + /// - Returns: An empty array when `groups` is not positive. + public static func bootstrapWeights( + groups: Int, using generator: inout G + ) -> [T] { + guard groups > 0 else { return [] } + var counts = [Int](repeating: 0, count: groups) + for _ in 0..= folds`. + /// + /// - Returns: An empty array when `groups` or `folds` is not positive. + public static func foldAssignment(groups: Int, folds: Int, using generator: inout G) -> [Int] { + guard groups > 0, folds > 0 else { return [] } + var order = Array(0.. 0 { + let other = below(index + 1, using: &generator) + if other != index { order.swapAt(index, other) } + index -= 1 + } + var result = [Int](repeating: 0, count: groups) + for (position, group) in order.enumerated() { result[group] = position % folds } + return result + } +} diff --git a/Sources/BusinessMath/Statistics/GroupedRanking/GroupedCrossValidation.swift b/Sources/BusinessMath/Statistics/GroupedRanking/GroupedCrossValidation.swift new file mode 100644 index 00000000..1896888b --- /dev/null +++ b/Sources/BusinessMath/Statistics/GroupedRanking/GroupedCrossValidation.swift @@ -0,0 +1,286 @@ +// +// GroupedCrossValidation.swift +// BusinessMath +// + +import Foundation +import Numerics + +/// Grouped cross-validation, group bootstrap intervals and the held-out comparison of a refit against its reference. +/// +/// Folds hold whole groups. A penalty (and which features are free to move) is chosen **inside each training set** by an inner +/// grouped k-fold on the training groups only, so the outer held-out groups never influence it. +public enum GroupedCrossValidation { + + // MARK: - Evidence for a feature + + /// How many candidates carry each feature, and how many of those were chosen, over the informative groups with positive weight. + /// + /// Offered so a caller can apply its own evidence rule (for example, "do not refit a feature too few chosen candidates carry"). + public static func featureCounts( + model: GroupedChoiceModel, groupWeights: [T] + ) -> (carrying: [Int], chosenCarrying: [Int])? { + let data = model.data + guard groupWeights.count == data.groupCount else { return nil } + var carrying = [Int](repeating: 0, count: data.featureCount) + var chosen = [Int](repeating: 0, count: data.featureCount) + for group in data.informativeGroups where groupWeights[group] > T.zero { + for row in data.rows(ofGroup: group) { + for entry in data.rowEntryStart[row]..( + model: GroupedChoiceModel, groupWeights: [T], minimumChosen: Int + ) -> Set { + guard let counts = featureCounts(model: model, groupWeights: groupWeights) else { return [] } + return Set(counts.chosenCarrying.indices.filter { counts.chosenCarrying[$0] < minimumChosen }) + } + + // MARK: - Choosing a penalty + + /// The penalty with the best held-out likelihood, by cross-validation over the groups with positive weight. + /// + /// Each candidate is fitted on the training groups of each fold and scored by the conditional log-likelihood per chosen + /// candidate on the held-out groups. A candidate whose fit does not settle in a fold is not eligible. Ties go to the **stronger** + /// penalty (the data must do better to move a weight), with ``PenaltyChoice/reference`` the strongest of all. + /// + /// - Parameters: + /// - model: The model. + /// - groupWeights: How much each group counts; groups with weight zero are not used. + /// - penalties: The candidates. + /// - frozen: Features held at their reference value. + /// - folds: How many folds; at least two. + /// - seed: Seeds the fold assignment. + /// - Returns: The best candidate, or ``PenaltyChoice/reference`` when there are fewer than `2 × folds` groups to cross-validate + /// or no candidate could be scored. + public static func choosePenalty( + model: GroupedChoiceModel, groupWeights: [T], penalties: [PenaltyChoice], frozen: Set = [], folds: Int, seed: UInt64 + ) -> PenaltyChoice { + let slots = model.data.informativeGroups.filter { groupWeights.count == model.data.groupCount && groupWeights[$0] > T.zero } + guard folds >= 2, slots.count >= 2 * folds else { return .reference } + var generator = SplitMix64(seed: seed) + let assignment = GroupResampling.foldAssignment(groups: slots.count, folds: folds, using: &generator) + // Strongest first: the reference, then finite penalties from large to small. + let grid = penalties.filter { $0 == .reference } + finite(penalties).sorted(by: >).map { PenaltyChoice.penalty($0) } + var best: PenaltyChoice = .reference + var bestScore: T = T.infinity + var found = false + let margin: T = T(1) / T(1_000_000_000) + for candidate in grid { + var total: T = T.zero + var chosen: T = T.zero + var eligible = true + for fold in 0.. T.zero else { continue } + let score: T = total / chosen + if !found || score < bestScore - margin { + best = candidate + bestScore = score + found = true + } + } + return found ? best : .reference + } + + private static func finite(_ penalties: [PenaltyChoice]) -> [T] { + penalties.compactMap { choice -> T? in + guard case .penalty(let value) = choice, value.isFinite, value >= T.zero else { return nil } + return value + } + } + + private static func fit( + model: GroupedChoiceModel, weights: [T], choice: PenaltyChoice, frozen: Set + ) throws -> GroupedChoiceFit { + switch choice { + case .reference: return try model.referenceFit(groupWeights: weights) + case .penalty(let value): return try model.fit(groupWeights: weights, penalty: value, frozen: frozen) + } + } + + // MARK: - Bootstrap intervals for the multipliers + + /// Percentile intervals for each multiplier from refitting on bootstrap resamples of groups. + /// + /// Resamples whose fit does not settle, or that have nothing to compare, are dropped and counted. Each refit starts from `full`. + /// + /// - Parameters: + /// - model: The model. + /// - full: The fit on the groups as they are (its multipliers are the starting point of each refit). + /// - penalty: The penalty to refit with. + /// - frozen: Features held at their reference value. + /// - groupWeights: The groups to resample: those with positive weight, each counting once per draw. + /// - resamples: How many to draw. + /// - level: The share of resamples the interval covers, for example `0.9`. + /// - seed: Seeds the resampling. + /// - Returns: `nil` when no resample could be fitted. + public static func bootstrapIntervals( + model: GroupedChoiceModel, full: GroupedChoiceFit, penalty: T, frozen: Set = [], groupWeights: [T], + resamples: Int, level: T, seed: UInt64 + ) -> BootstrapIntervals? { + let data = model.data + guard groupWeights.count == data.groupCount, resamples > 0 else { return nil } + let slots = data.informativeGroups.filter { groupWeights[$0] > T.zero } + guard !slots.isEmpty else { return nil } + var generator = SplitMix64(seed: seed) + var draws: [[T]] = [] + var skipped = 0 + for _ in 0..( + model: GroupedChoiceModel, penalties: [PenaltyChoice], minimumChosen: Int, folds: Int, innerFolds: Int, + resamples: Int, level: T, seed: UInt64 + ) -> HeldOutComparison? { + let data = model.data + let slots = data.informativeGroups + guard folds >= 2, slots.count >= 2 * folds else { return nil } + var assigner = SplitMix64(seed: seed &+ 3) + let assignment = GroupResampling.foldAssignment(groups: slots.count, folds: folds, using: &assigner) + let ones = [T](repeating: T(1), count: data.featureCount) + let referenceScores = model.rowScores(multipliers: ones, scale: T(1)) + var sizes: [Int] = [] + var chosenPenalties: [PenaltyChoice] = [] + var differences: [T] = [] + var referenceSum: T = T.zero + var refitSum: T = T.zero + var referenceTop: T = T.zero + var refitTop: T = T.zero + for fold in 0.. 1 { + let mean: T = means.reduce(T.zero, +) / T(means.count) + var squares: T = T.zero + for value in means { + let gap: T = value - mean + squares += gap * gap + } + spread = (squares / T(means.count - 1)).squareRoot() + let sorted = means.sorted() + let tail = tailProbability(level: level) + lower = percentile(sorted, tail) + upper = percentile(sorted, T(1) - tail) + } + return HeldOutComparison( + foldSizes: sizes, penalties: chosenPenalties, groups: differences.count, referencePercentile: referenceSum / count, + refitPercentile: refitSum / count, referenceTopOwn: referenceTop / count, refitTopOwn: refitTop / count, + difference: improvement, spread: spread, lower: lower, upper: upper, level: level, resamples: means.count) + } + + // MARK: - Quantiles + + /// The probability left in each tail of an interval that covers `level` of the resamples. + static func tailProbability(level: T) -> T { + let clamped: T = Swift.min(Swift.max(level, T.zero), T(1)) + return (T(1) - clamped) / T(2) + } + + /// The value at quantile `q` of an ascending list, interpolating linearly. + static func percentile(_ sorted: [T], _ q: T) -> T { + guard sorted.count > 1, q.isFinite else { return sorted.first ?? T.zero } + let clamped: T = Swift.min(Swift.max(q, T.zero), T(1)) + let position: T = clamped * T(sorted.count - 1) + let below = Int(position.rounded(.down)) + let above = Swift.min(below + 1, sorted.count - 1) + let weight: T = position - T(below) + let near: T = sorted[below] * (T(1) - weight) + let far: T = sorted[above] * weight + return near + far + } +} diff --git a/Sources/BusinessMath/Statistics/GroupedRanking/HeldOutComparison.swift b/Sources/BusinessMath/Statistics/GroupedRanking/HeldOutComparison.swift new file mode 100644 index 00000000..3cea2c8d --- /dev/null +++ b/Sources/BusinessMath/Statistics/GroupedRanking/HeldOutComparison.swift @@ -0,0 +1,87 @@ +// +// HeldOutComparison.swift +// BusinessMath +// + +import Foundation +import Numerics + +/// One of the penalties a cross-validation may choose: keep the reference weights, or refit with a pull toward them. +public enum PenaltyChoice: Sendable, Equatable { + /// The reference weights unchanged: no refit. + case reference + /// Refit with this penalty (finite, not negative). + case penalty(T) +} + +/// Whether a refit ranked groups it never saw better than the reference weights did. +/// +/// It states a fact about held-out groups: the two mean percentiles, their paired difference, and a bootstrap interval for +/// the difference over groups. It does **not** say whether to adopt anything. A caller's own policy (how big a move counts, +/// how many chosen candidates must carry a feature) sits on top of these figures and is deliberately not here. +public struct HeldOutComparison: Sendable, Equatable { + + /// How many groups sat in each fold. + public let foldSizes: [Int] + + /// The penalty chosen inside each fold, on that fold's training groups only. + public let penalties: [PenaltyChoice] + + /// How many held-out groups were compared (each was held out exactly once). + public let groups: Int + + /// The reference weights' mean percentile over the held-out groups. + public let referencePercentile: T + + /// The refit's mean percentile over the same groups. + public let refitPercentile: T + + /// The reference weights' mean share of a group's chosen candidates inside its top *m*. + public let referenceTopOwn: T + + /// The refit's. + public let refitTopOwn: T + + /// Refit minus reference, in mean percentile, over held-out groups. + public let difference: T + + /// The bootstrap standard deviation of the difference (resampling held-out groups); zero without resamples. + public let spread: T + + /// The lower end of the bootstrap interval for the difference. + public let lower: T + + /// The upper end of the bootstrap interval. + public let upper: T + + /// The share of resamples the interval covers, for example `0.9`. + public let level: T + + /// How many bootstrap resamples were drawn. + public let resamples: Int + + /// Whether the interval for the difference lies wholly on one side of zero. + public var intervalExcludesZero: Bool { lower > T.zero || upper < T.zero } + + /// Whether the lower end of the interval is above zero: the refit ranked held-out groups better by more than chance. + public var refitBeatsReference: Bool { lower > T.zero } +} + +/// The fitted multipliers' bootstrap intervals, from refitting on resamples of groups. +public struct BootstrapIntervals: Sendable, Equatable { + + /// The lower end of the interval for each feature's multiplier. + public let lower: [T] + + /// The upper end. + public let upper: [T] + + /// The share of resamples the intervals cover. + public let level: T + + /// How many resamples were fitted and used. + public let resamples: Int + + /// How many resamples were dropped because their fit did not settle or they had nothing to compare. + public let skipped: Int +} diff --git a/Tests/BusinessMathTests/Grouped Ranking Tests/GroupResamplingTests.swift b/Tests/BusinessMathTests/Grouped Ranking Tests/GroupResamplingTests.swift new file mode 100644 index 00000000..2b76e84c --- /dev/null +++ b/Tests/BusinessMathTests/Grouped Ranking Tests/GroupResamplingTests.swift @@ -0,0 +1,114 @@ +// +// GroupResamplingTests.swift +// BusinessMath +// +// Group-level resampling: unbiased draws, bootstrap weights, balanced folds, quantiles. +// + +import Testing +import Foundation +import Numerics +@testable import BusinessMath + +/// A generator that returns a scripted sequence of draws, so the rejection path can be reached on purpose. +private struct ScriptedGenerator: RandomNumberGenerator { + var draws: [UInt64] + var used = 0 + mutating func next() -> UInt64 { + let value = draws[used % draws.count] + used += 1 + return value + } +} + +@Suite("Grouped choice: resampling") +struct GroupResamplingTests { + + @Test("A bounded draw stays in range and returns zero for a bound that is not above one") + func belowRange() { + var generator = SplitMix64(seed: 1) + for bound in [1, 2, 3, 7, 100] { + for _ in 0..<200 { let value = GroupResampling.below(bound, using: &generator); #expect(value >= 0 && value < bound) } + } + #expect(GroupResampling.below(0, using: &generator) == 0) + #expect(GroupResampling.below(-5, using: &generator) == 0) + } + + @Test("A draw in the biased short block is rejected and the next one used") + func belowRejects() { + // 2^64 mod 3 = 1, so a draw of 0 falls in the rejected block for bound 3; the next draw, 5, gives 5 % 3 = 2. + var generator = ScriptedGenerator(draws: [0, 5]) + let value = GroupResampling.below(3, using: &generator) + #expect(value == 2) + #expect(generator.used == 2) + // A draw of 1 is the first accepted one: 1 % 3 = 1, with no second draw. + var accepting = ScriptedGenerator(draws: [1]) + #expect(GroupResampling.below(3, using: &accepting) == 1) + #expect(accepting.used == 1) + } + + @Test("Draws are spread evenly across the range") + func belowUniform() { + var generator = SplitMix64(seed: 42) + var counts = [Int](repeating: 0, count: 6) + for _ in 0..<60_000 { counts[GroupResampling.below(6, using: &generator)] += 1 } + // Expected 10,000 each; the standard deviation is about 91, so 500 is more than five of them. + for count in counts { #expect(abs(count - 10_000) < 500) } + } + + @Test("Bootstrap weights are whole numbers that sum to the number of groups, and repeat for a seed") + func bootstrapWeights() { + var a = SplitMix64(seed: 5) + var b = SplitMix64(seed: 5) + var c = SplitMix64(seed: 6) + let first: [Double] = GroupResampling.bootstrapWeights(groups: 50, using: &a) + let second: [Double] = GroupResampling.bootstrapWeights(groups: 50, using: &b) + let other: [Double] = GroupResampling.bootstrapWeights(groups: 50, using: &c) + #expect(zip(first, second).allSatisfy { $0.isEqual(to: $1) }) + #expect(zip(first, other).contains { !$0.isEqual(to: $1) }) + #expect(first.count == 50) + #expect(first.reduce(0, +) == 50) + #expect(first.allSatisfy { $0 == $0.rounded() && $0 >= 0 }) + var empty = SplitMix64(seed: 5) + let none: [Double] = GroupResampling.bootstrapWeights(groups: 0, using: &empty) + #expect(none.isEmpty) + } + + @Test("Folds are balanced, every fold is used, and the assignment repeats for a seed") + func folds() { + var a = SplitMix64(seed: 9) + var b = SplitMix64(seed: 9) + var c = SplitMix64(seed: 10) + let first = GroupResampling.foldAssignment(groups: 23, folds: 5, using: &a) + #expect(first == GroupResampling.foldAssignment(groups: 23, folds: 5, using: &b)) + #expect(first != GroupResampling.foldAssignment(groups: 23, folds: 5, using: &c)) + var sizes = [Int](repeating: 0, count: 5) + for fold in first { sizes[fold] += 1 } + #expect(sizes.sorted() == [4, 4, 5, 5, 5]) + #expect(first.allSatisfy { $0 >= 0 && $0 < 5 }) + var d = SplitMix64(seed: 1) + #expect(GroupResampling.foldAssignment(groups: 0, folds: 3, using: &d).isEmpty) + #expect(GroupResampling.foldAssignment(groups: 3, folds: 0, using: &d).isEmpty) + // Fewer groups than folds: each group alone, some folds empty. + let few = GroupResampling.foldAssignment(groups: 2, folds: 5, using: &d) + #expect(few.count == 2) + #expect(Set(few).count == 2) + } + + @Test("Quantiles interpolate linearly and the tail of a level is half what it leaves out") + func quantiles() { + let sorted = [1.0, 2.0, 3.0, 4.0] + #expect(abs(GroupedCrossValidation.percentile(sorted, 0.5) - 2.5) < 1e-12) + #expect(GroupedCrossValidation.percentile(sorted, 0) == 1) + #expect(GroupedCrossValidation.percentile(sorted, 1) == 4) + #expect(abs(GroupedCrossValidation.percentile(sorted, 1.0 / 3.0) - 2) < 1e-12) + #expect(GroupedCrossValidation.percentile(sorted, -1) == 1) + #expect(GroupedCrossValidation.percentile(sorted, 2) == 4) + #expect(GroupedCrossValidation.percentile([7.0], 0.9) == 7) + #expect(GroupedCrossValidation.percentile([Double](), 0.9) == 0) + #expect(GroupedCrossValidation.percentile(sorted, Double.nan) == 1) + #expect(abs(GroupedCrossValidation.tailProbability(level: 0.9) - 0.05) < 1e-15) + #expect(GroupedCrossValidation.tailProbability(level: 1.5) == 0) + #expect(abs(GroupedCrossValidation.tailProbability(level: -1) - 0.5) < 1e-12) + } +} diff --git a/Tests/BusinessMathTests/Grouped Ranking Tests/GroupedCrossValidationTests.swift b/Tests/BusinessMathTests/Grouped Ranking Tests/GroupedCrossValidationTests.swift new file mode 100644 index 00000000..8518ddc6 --- /dev/null +++ b/Tests/BusinessMathTests/Grouped Ranking Tests/GroupedCrossValidationTests.swift @@ -0,0 +1,217 @@ +// +// GroupedCrossValidationTests.swift +// BusinessMath +// +// Held-out comparison, nested penalty choice and bootstrap intervals for grouped choices. +// + +import Testing +import Foundation +import Numerics +@testable import BusinessMath + +@Suite("Grouped choice: cross-validation") +struct GroupedCrossValidationTests { + + private typealias Group = GroupedChoiceSynthetic.Group + + private func model(_ groups: [Group], reference: [Double]) throws -> GroupedChoiceModel { + let data = try #require(GroupedChoiceData(groups: groups)) + return try #require(GroupedChoiceModel(data: data, reference: reference, likelihood: .subset)) + } + + private let grid: [PenaltyChoice] = [.reference, .penalty(10), .penalty(1), .penalty(0.1), .penalty(0.01)] + + // MARK: - Evidence + + @Test("Feature counts are worked by hand") + func featureCounts() throws { + let data = try #require(GroupedChoiceData(groups: [ + [(features: [1, 0], chosen: true), (features: [1, 1], chosen: false), (features: [0, 1], chosen: false)], + [(features: [0, 1], chosen: true), (features: [1, 0], chosen: true)], + [(features: [1, 1], chosen: true), (features: [0, 0], chosen: false)], + ])) + let model = try #require(GroupedChoiceModel(data: data, reference: [1, 1], likelihood: .subset)) + // Group 1 chose everything, so it is not informative and does not count. + // Group 0: feature 0 on candidates 0 (chosen) and 1; feature 1 on candidates 1 and 2. Group 2: both features on the chosen one. + let counts = try #require(GroupedCrossValidation.featureCounts(model: model, groupWeights: [1, 1, 1])) + #expect(counts.carrying == [3, 3]) + #expect(counts.chosenCarrying == [2, 1]) + let weighted = try #require(GroupedCrossValidation.featureCounts(model: model, groupWeights: [0, 1, 1])) + #expect(weighted.carrying == [1, 1]) + #expect(weighted.chosenCarrying == [1, 1]) + #expect(GroupedCrossValidation.featureCounts(model: model, groupWeights: [1]) == nil) + #expect(GroupedCrossValidation.thinFeatures(model: model, groupWeights: [1, 1, 1], minimumChosen: 2) == [1]) + } + + // MARK: - Choosing the penalty + + @Test("With a strong signal a weak penalty is chosen; with none, the strongest option") + func choosePenalty() throws { + let signal = GroupedChoiceSynthetic.make(seed: 41, groups: 400, candidates: 6, sizes: [2, 3], beta: [1.2, 0.8]) + // A reference that is wrong in scale and shape, so the refit has something to learn. + let wrong = try model(signal, reference: [0.1, 1.5]) + let weights = [Double](repeating: 1, count: 400) + let chosen = GroupedCrossValidation.choosePenalty(model: wrong, groupWeights: weights, penalties: grid, folds: 4, seed: 1) + #expect(chosen != .reference) + let noise = GroupedChoiceSynthetic.make(seed: 43, groups: 400, candidates: 6, sizes: [2, 3], beta: [0, 0]) + let flat = try model(noise, reference: [1, 1]) + let weak = GroupedCrossValidation.choosePenalty(model: flat, groupWeights: weights, penalties: grid, folds: 4, seed: 1) + #expect(weak == .reference || weak == .penalty(10)) + } + + @Test("With too few groups to cross-validate, the reference is kept") + func chooseFewGroups() throws { + let groups = GroupedChoiceSynthetic.make(seed: 47, groups: 7, candidates: 6, sizes: [2], beta: [1]) + let model = try model(groups, reference: [1]) + let choice = GroupedCrossValidation.choosePenalty( + model: model, groupWeights: [Double](repeating: 1, count: 7), penalties: grid, folds: 4, seed: 1) + #expect(choice == .reference) + #expect(GroupedCrossValidation.choosePenalty( + model: model, groupWeights: [Double](repeating: 1, count: 7), penalties: grid, folds: 1, seed: 1) == .reference) + } + + @Test("Exactly tied candidates go to the stronger penalty") + func tiesGoToTheStrongerPenalty() throws { + let groups = GroupedChoiceSynthetic.make(seed: 97, groups: 80, candidates: 6, sizes: [2, 3], beta: [0.5, 0.5]) + let model = try model(groups, reference: [1, 1]) + // Every feature frozen, so every penalty gives the same fit and the same held-out likelihood: an exact tie. + let chosen = GroupedCrossValidation.choosePenalty( + model: model, groupWeights: [Double](repeating: 1, count: 80), penalties: [.penalty(0.01), .penalty(10), .penalty(1)], + frozen: [0, 1], folds: 4, seed: 1) + #expect(chosen == .penalty(10)) + } + + @Test("Fewer than two groups per fold are not cross-validated, even when a refit would clearly win") + func fewGroupsEvenWithSignal() throws { + let groups = GroupedChoiceSynthetic.make(seed: 101, groups: 7, candidates: 6, sizes: [2], beta: [2.0, 0.0]) + let model = try model(groups, reference: [0.1, 2.0]) + let weights = [Double](repeating: 1, count: 7) + #expect(model.data.informativeGroups.count == 7) + let choice = GroupedCrossValidation.choosePenalty( + model: model, groupWeights: weights, penalties: [.penalty(0.001), .penalty(0.01)], folds: 4, seed: 1) + #expect(choice == .reference) + } + + // MARK: - Held-out comparison + + @Test("Comparing the reference with itself gives exactly zero and an interval that includes it") + func selfComparison() throws { + let groups = GroupedChoiceSynthetic.make(seed: 51, groups: 200, candidates: 6, sizes: [2, 3], beta: [0.8, 0.4]) + let model = try model(groups, reference: [1, 1]) + let result = try #require(GroupedCrossValidation.heldOutComparison( + model: model, penalties: [.reference], minimumChosen: 1, folds: 4, innerFolds: 3, resamples: 50, level: 0.9, seed: 7)) + #expect(result.difference == 0) + #expect(result.lower == 0 && result.upper == 0) + #expect(!result.refitBeatsReference) + #expect(!result.intervalExcludesZero) + #expect(result.referencePercentile == result.refitPercentile) + #expect(result.penalties.allSatisfy { $0 == .reference }) + #expect(result.resamples == 50) + #expect(abs(result.level - 0.9) < 1e-12) + } + + @Test("A refit that is truly better has an interval above zero; every informative group is held out once") + func betterRefit() throws { + let groups = GroupedChoiceSynthetic.make(seed: 53, groups: 320, candidates: 6, sizes: [2, 3], beta: [1.0, 0.0]) + // A reference that weighs the useless feature at twice the useful one. (The penalty is on the RELATIVE change, so a + // reference that is tiny for the useful feature could barely be moved: the design is chosen so the data can argue.) + let model = try model(groups, reference: [0.5, 1.0]) + let result = try #require(GroupedCrossValidation.heldOutComparison( + model: model, penalties: [.penalty(0.01), .penalty(0.001)], minimumChosen: 5, folds: 4, innerFolds: 3, resamples: 100, + level: 0.9, seed: 3)) + #expect(result.difference > 0.02) + #expect(result.refitBeatsReference) + #expect(result.intervalExcludesZero) + #expect(result.refitPercentile > result.referencePercentile) + #expect(result.foldSizes.reduce(0, +) == model.data.informativeGroups.count) + #expect(result.groups == model.data.informativeGroups.count) + #expect(result.difference > result.lower) + #expect(result.difference < result.upper) + #expect(result.spread > 0) + } + + @Test("With no signal the interval includes zero") + func nullComparison() throws { + let groups = GroupedChoiceSynthetic.make(seed: 59, groups: 300, candidates: 6, sizes: [2, 3], beta: [0, 0]) + let model = try model(groups, reference: [1, 1]) + let result = try #require(GroupedCrossValidation.heldOutComparison( + model: model, penalties: grid, minimumChosen: 5, folds: 4, innerFolds: 3, resamples: 100, level: 0.9, seed: 5)) + #expect(!result.refitBeatsReference) + } + + @Test("The same seed gives the same comparison, and a different seed a different one") + func comparisonDeterminism() throws { + let groups = GroupedChoiceSynthetic.make(seed: 61, groups: 200, candidates: 6, sizes: [2, 3], beta: [0.8, 0.4]) + let model = try model(groups, reference: [0.3, 1.2]) + func run(_ seed: UInt64) -> HeldOutComparison? { + GroupedCrossValidation.heldOutComparison( + model: model, penalties: [.penalty(0.1), .penalty(0.01)], minimumChosen: 5, folds: 4, innerFolds: 3, resamples: 60, + level: 0.9, seed: seed) + } + #expect(run(7) == run(7)) + #expect(run(7) != run(8)) + } + + @Test("Too few groups, or fewer than two folds, give no comparison") + func comparisonRefusals() throws { + let groups = GroupedChoiceSynthetic.make(seed: 67, groups: 7, candidates: 6, sizes: [2], beta: [1]) + let model = try model(groups, reference: [1]) + #expect(GroupedCrossValidation.heldOutComparison( + model: model, penalties: grid, minimumChosen: 1, folds: 4, innerFolds: 2, resamples: 10, level: 0.9, seed: 1) == nil) + #expect(GroupedCrossValidation.heldOutComparison( + model: model, penalties: grid, minimumChosen: 1, folds: 1, innerFolds: 2, resamples: 10, level: 0.9, seed: 1) == nil) + } + + @Test("The penalty chosen for a fold cannot depend on that fold's held-out groups") + func foldDiscipline() throws { + let groups = GroupedChoiceSynthetic.make(seed: 71, groups: 160, candidates: 6, sizes: [2, 3], beta: [1.0, 0.2]) + let base = try model(groups, reference: [0.4, 1.0]) + let slots = base.data.informativeGroups + var assigner = SplitMix64(seed: 5 &+ 3) + let assignment = GroupResampling.foldAssignment(groups: slots.count, folds: 4, using: &assigner) + let held = Set(slots.indices.filter { assignment[$0] == 0 }.map { slots[$0] }) + // The adversary: in fold 0's groups only, reverse which candidates were chosen (the counts stay the same). + var altered = groups + for index in held { altered[index] = zip(groups[index], groups[index].reversed()).map { (features: $0.0.features, chosen: $0.1.chosen) } } + let other = try model(altered, reference: [0.4, 1.0]) + #expect(other.data.informativeGroups == slots) + func run(_ model: GroupedChoiceModel) -> HeldOutComparison? { + GroupedCrossValidation.heldOutComparison( + model: model, penalties: grid, minimumChosen: 5, folds: 4, innerFolds: 3, resamples: 20, level: 0.9, seed: 5) + } + let a = try #require(run(base)) + let b = try #require(run(other)) + #expect(a.penalties[0] == b.penalties[0]) + #expect(a.foldSizes == b.foldSizes) + #expect(a.difference != b.difference) + } + + // MARK: - Bootstrap intervals + + @Test("Bootstrap intervals bracket the fit and the true weight, and can be refused") + func bootstrapIntervals() throws { + let beta = [0.9, 0.4] + let groups = GroupedChoiceSynthetic.make(seed: 73, groups: 400, candidates: 6, sizes: [2, 3], beta: beta) + let model = try model(groups, reference: [1, 1]) + let weights = [Double](repeating: 1, count: 400) + let full = try model.fit(groupWeights: weights, penalty: 1e-3) + let intervals = try #require(GroupedCrossValidation.bootstrapIntervals( + model: model, full: full, penalty: 1e-3, groupWeights: weights, resamples: 60, level: 0.9, seed: 9)) + #expect(intervals.resamples + intervals.skipped == 60) + #expect(abs(intervals.level - 0.9) < 1e-12) + for k in 0..<2 { + #expect(intervals.lower[k] <= intervals.upper[k]) + #expect(intervals.lower[k] <= full.multipliers[k] && full.multipliers[k] <= intervals.upper[k]) + let weight = full.scale + #expect(intervals.lower[k] * weight <= beta[k] && beta[k] <= intervals.upper[k] * weight) + } + let repeated = try #require(GroupedCrossValidation.bootstrapIntervals( + model: model, full: full, penalty: 1e-3, groupWeights: weights, resamples: 60, level: 0.9, seed: 9)) + #expect(repeated == intervals) + #expect(GroupedCrossValidation.bootstrapIntervals( + model: model, full: full, penalty: 1e-3, groupWeights: weights, resamples: 0, level: 0.9, seed: 9) == nil) + #expect(GroupedCrossValidation.bootstrapIntervals( + model: model, full: full, penalty: 1e-3, groupWeights: [1], resamples: 10, level: 0.9, seed: 9) == nil) + } +} From a7097fc9492fc5f01ddd82aa5e33dc911d8fd7a4 Mon Sep 17 00:00:00 2001 From: Justin Purnell Date: Sat, 21 Nov 2026 13:07:01 -0500 Subject: [PATCH 07/13] feat(grouped-ranking): Plackett-Luce ranking likelihood and ranked data (B5); CHANGELOG Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_017dtpLZ6XGCJVmSqc1u4qUt --- CHANGELOG.md | 11 + .../GroupedRanking/GroupRankingMetrics.swift | 2 +- .../GroupedRanking/GroupedChoiceData.swift | 76 +++++- .../GroupedRanking/GroupedChoiceFit.swift | 2 +- .../GroupedRanking/GroupedChoiceModel.swift | 59 +++++ .../PlackettLuceTests.swift | 235 ++++++++++++++++++ 6 files changed, 381 insertions(+), 4 deletions(-) create mode 100644 Tests/BusinessMathTests/Grouped Ranking Tests/PlackettLuceTests.swift diff --git a/CHANGELOG.md b/CHANGELOG.md index a119e4ed..762b7cce 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,17 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### [Unreleased] +**Grouped-ranking toolkit (`Statistics/GroupedRanking`), phases B1 to B5 of `project/plans/proposals/BusinessMathGroupedRanking.md`.** All additive; +no existing symbol changes. `GroupedChoiceData` (dense or sparse candidates grouped by chooser, with optional fixed per-candidate offsets, or ranked +groups), `GroupedChoiceModel` (the exact conditional-logit likelihood for an unordered chosen set, and the Plackett-Luce likelihood for ordered +top choices, with gradients), `fitScale` / `referenceFit` / `fit` (a penalty on the relative change of each multiplier toward a reference, +non-negativity by projection, a restart-guarded accelerated search, and a thrown `didNotConverge` rather than an unsettled result), +`GroupRankingMetrics` (per-group percentile, top-own and top-k, and the pooled `ClassifierEvaluation`), `GroupResampling` (an unbiased bounded draw, +bootstrap weights over groups, balanced fold assignment), and `GroupedCrossValidation` (nested penalty choice, group-bootstrap intervals, and +`HeldOutComparison`, which reports a fact about held-out groups and applies no adoption threshold). A softmax per chosen candidate is biased on the +same data (a recovery test shows a true weight of 1 fitted at about 0.64); the conditional likelihood recovers it. Not yet built: the penalised +`LogisticRegression.fit` (B6), the DocC article and ADR-011 (B7), and the MCP tools (phase D, in businessMathMCP). + ### [3.0.0-alpha.17] - 2026-11-14 **The Network module gains weighted graphs and the graph measures that lived in the ClassGraph package** (ADR-006 to ADR-010; plan diff --git a/Sources/BusinessMath/Statistics/GroupedRanking/GroupRankingMetrics.swift b/Sources/BusinessMath/Statistics/GroupedRanking/GroupRankingMetrics.swift index 39497d9f..0ff0dbf6 100644 --- a/Sources/BusinessMath/Statistics/GroupedRanking/GroupRankingMetrics.swift +++ b/Sources/BusinessMath/Statistics/GroupedRanking/GroupRankingMetrics.swift @@ -105,7 +105,7 @@ public enum GroupRankingMetrics { guard scores.count == data.rowCount else { return nil } var pooledScores: [T] = [] var outcomes: [Bool] = [] - for group in data.informativeGroups { + for group in data.comparableGroups { for row in data.rows(ofGroup: group) { pooledScores.append(scores[row]) outcomes.append(data.rowChosen[row]) diff --git a/Sources/BusinessMath/Statistics/GroupedRanking/GroupedChoiceData.swift b/Sources/BusinessMath/Statistics/GroupedRanking/GroupedChoiceData.swift index ad1718cd..8137661a 100644 --- a/Sources/BusinessMath/Statistics/GroupedRanking/GroupedChoiceData.swift +++ b/Sources/BusinessMath/Statistics/GroupedRanking/GroupedChoiceData.swift @@ -9,9 +9,18 @@ import Numerics /// Which of the likelihoods a grouped choice model uses. /// /// - ``subset``: the group chose an unordered set of its candidates (the *conditional logit*). +/// - ``ranking``: the group ranked its top candidates in order (the *Plackett-Luce* model). +/// +/// With exactly one chosen candidate per group the two are the same function (the multinomial logit). With more than one +/// they are **different likelihoods**: the subset form does not know an order, and Plackett-Luce taken over an arbitrary +/// order of an unordered set would make the answer depend on the order chosen. Build unordered data with +/// ``GroupedChoiceData/init(groups:offsets:)`` and ranked data with ``GroupedChoiceData/init(rankedGroups:offsets:)``; each +/// model refuses the other's data. public enum ChoiceLikelihood: Sendable, Equatable { /// The group chose an unordered set of items; how many it chose does not move the weights. case subset + /// The group ranked its top choices, best first; each next choice is made among the candidates not yet taken. + case ranking } /// Why a grouped choice model could not be built or fitted. @@ -60,6 +69,10 @@ public struct GroupedChoiceData: Senda let entryValue: [T] let rowChosen: [Bool] let rowOffset: [T] + let rowRank: [Int] + + /// Whether the data holds ordered rankings (built by ``init(rankedGroups:offsets:)``) and so belongs to ``ChoiceLikelihood/ranking``. + public let isRanked: Bool /// Creates data from dense feature rows. /// @@ -101,6 +114,13 @@ public struct GroupedChoiceData: Senda /// non-finite value, or offsets of the wrong shape. public init?( sparseGroups: [[(features: [(feature: Int, value: T)], chosen: Bool)]], featureCount: Int, offsets: [[T]]? = nil + ) { + self.init(sparseGroups: sparseGroups, featureCount: featureCount, offsets: offsets, ranks: nil) + } + + /// The shared constructor: `ranks`, when given, holds each candidate's position in its group's ranking (`-1` if unranked). + init?( + sparseGroups: [[(features: [(feature: Int, value: T)], chosen: Bool)]], featureCount: Int, offsets: [[T]]?, ranks: [[Int]]? ) { guard featureCount > 0, !sparseGroups.isEmpty else { return nil } if let offsets { @@ -115,6 +135,7 @@ public struct GroupedChoiceData: Senda var entryValue: [T] = [] var rowChosen: [Bool] = [] var rowOffset: [T] = [] + var rowRank: [Int] = [] for (groupIndex, group) in sparseGroups.enumerated() { for (position, candidate) in group.enumerated() { var seen = Set() @@ -128,6 +149,7 @@ public struct GroupedChoiceData: Senda rowEntryStart.append(entryFeature.count) rowChosen.append(candidate.chosen) rowOffset.append(offsets?[groupIndex][position] ?? T.zero) + rowRank.append(ranks?[groupIndex][position] ?? -1) } groupStart.append(rowChosen.count) } @@ -141,6 +163,49 @@ public struct GroupedChoiceData: Senda self.entryValue = entryValue self.rowChosen = rowChosen self.rowOffset = rowOffset + self.rowRank = rowRank + self.isRanked = ranks != nil + } + + /// Creates ranked data: each group's candidates and the order in which its top choices were made. + /// + /// - Parameters: + /// - rankedGroups: One entry per group: every candidate's dense feature row, and `ranking`, the candidate indices from the + /// best choice to the last one made. The ranking may cover only the top *m* of the candidates; the unranked remainder is + /// what each ranked choice was made against. + /// - offsets: As for ``init(groups:offsets:)``. + /// - Returns: `nil` for no candidates, rows of different widths or zero width, a non-finite value, a ranking index out of + /// range or repeated, or offsets of the wrong shape. + public init?(rankedGroups: [(candidates: [[T]], ranking: [Int])], offsets: [[T]]? = nil) { + guard let width = rankedGroups.lazy.compactMap({ $0.candidates.first?.count }).first, width > 0 else { return nil } + var sparse: [[(features: [(feature: Int, value: T)], chosen: Bool)]] = [] + var ranks: [[Int]] = [] + for group in rankedGroups { + var positions = [Int](repeating: -1, count: group.candidates.count) + for (position, candidate) in group.ranking.enumerated() { + guard candidate >= 0, candidate < group.candidates.count, positions[candidate] < 0 else { return nil } + positions[candidate] = position + } + var rows: [(features: [(feature: Int, value: T)], chosen: Bool)] = [] + for (index, row) in group.candidates.enumerated() { + guard row.count == width else { return nil } + var entries: [(feature: Int, value: T)] = [] + for (feature, value) in row.enumerated() where value != T.zero { entries.append((feature: feature, value: value)) } + rows.append((features: entries, chosen: positions[index] >= 0)) + } + sparse.append(rows) + ranks.append(positions) + } + self.init(sparseGroups: sparse, featureCount: width, offsets: offsets, ranks: ranks) + } + + /// How many choices a group's likelihood counts: for unordered data the number chosen (zero when nothing, or everything, was chosen), for ranked data the number ranked, + /// less the last step when the ranking covers every candidate (it has only one candidate left to take, which says nothing). + func stepCount(group: Int) -> Int { + let chosen = chosenCount(group: group) + let count = rows(ofGroup: group).count + guard isRanked else { return chosen > 0 && chosen < count ? chosen : 0 } + return Swift.min(chosen, count - 1) } /// The rows (flat candidate positions) belonging to `group`. @@ -162,10 +227,17 @@ public struct GroupedChoiceData: Senda rows(ofGroup: group).reduce(0) { rowChosen[$1] ? $0 + 1 : $0 } } - /// The groups that carry information: at least one chosen and at least one unchosen candidate. + /// The groups that carry information. /// - /// A group that chose nothing, or everything, says nothing about what distinguishes a chosen candidate. + /// For unordered data: at least one chosen and at least one unchosen candidate, since a group that chose nothing, or + /// everything, says nothing about what distinguishes a chosen candidate. For ranked data: at least two candidates and at + /// least one ranked (a full ranking still says which was taken before which). public var informativeGroups: [Int] { + (0.. 0 } + } + + /// The groups with both a chosen and an unchosen candidate: the ones a ranking metric can compare. + var comparableGroups: [Int] { (0.. 0 && chosen < rows(ofGroup: group).count diff --git a/Sources/BusinessMath/Statistics/GroupedRanking/GroupedChoiceFit.swift b/Sources/BusinessMath/Statistics/GroupedRanking/GroupedChoiceFit.swift index 6d8e992a..56b3f55f 100644 --- a/Sources/BusinessMath/Statistics/GroupedRanking/GroupedChoiceFit.swift +++ b/Sources/BusinessMath/Statistics/GroupedRanking/GroupedChoiceFit.swift @@ -172,7 +172,7 @@ extension GroupedChoiceModel { guard !free.isEmpty else { return GroupedChoiceFit(multipliers: ones, scale: scale, iterations: 0, converged: true) } var totalChosen: T = T.zero for group in data.informativeGroups { - let weighted: T = groupWeights[group] * T(data.chosenCount(group: group)) + let weighted: T = groupWeights[group] * T(data.stepCount(group: group)) totalChosen += weighted } guard totalChosen > T.zero else { throw GroupedChoiceError.noInformativeGroups } diff --git a/Sources/BusinessMath/Statistics/GroupedRanking/GroupedChoiceModel.swift b/Sources/BusinessMath/Statistics/GroupedRanking/GroupedChoiceModel.swift index f31360a3..a2ee2ffa 100644 --- a/Sources/BusinessMath/Statistics/GroupedRanking/GroupedChoiceModel.swift +++ b/Sources/BusinessMath/Statistics/GroupedRanking/GroupedChoiceModel.swift @@ -53,6 +53,7 @@ public struct GroupedChoiceModel: Send /// - likelihood: The likelihood to use. public init?(data: GroupedChoiceData, reference: [T], likelihood: ChoiceLikelihood) { guard reference.count == data.featureCount else { return nil } + guard data.isRanked == (likelihood == .ranking) else { return nil } guard reference.allSatisfy({ $0.isFinite && $0 >= T.zero }) else { return nil } self.data = data self.reference = reference @@ -160,6 +161,8 @@ public struct GroupedChoiceModel: Send switch likelihood { case .subset: return subsetGroup(group: group, scores: scores, work: &work, wantInclusion: wantInclusion) + case .ranking: + return rankingGroup(group: group, scores: scores, work: &work) } } @@ -202,6 +205,62 @@ public struct GroupedChoiceModel: Send return (logLikelihood, friends) } + /// One group's Plackett-Luce log-likelihood: the product, over the ranked choices in order, of the chosen candidate's + /// `exp(score)` over the sum of `exp(score)` across the candidates not yet taken. + /// + /// The denominator of step *j* is the sum over the unranked candidates plus the ranked candidates from *j* on, built from + /// the back by additions only, so nothing is subtracted and no precision is lost when early choices dominate. The same + /// pass gives each candidate's expected count (its weight times the sum of the reciprocal denominators of the steps at + /// which it was still available), which is what the gradient needs. + private func rankingGroup(group: Int, scores: [T], work: inout Work) -> (logLikelihood: T, steps: Int)? { + let rows = data.rows(ofGroup: group) + let count = rows.count + let steps = data.stepCount(group: group) + guard steps > 0 else { return nil } + var maximum: T = -T.infinity + for row in rows { maximum = Swift.max(maximum, scores[row]) } + guard maximum.isFinite else { return nil } + let rankedCount = rows.reduce(0) { data.rowRank[$1] >= 0 ? $0 + 1 : $0 } + var order = [Int](repeating: -1, count: rankedCount) + for (position, row) in rows.enumerated() where data.rowRank[row] >= 0 { order[data.rowRank[row]] = position } + if work.terms.count < count { + work.terms = [T](repeating: T.zero, count: count) + work.inclusion = work.terms + } + var unranked: T = T.zero + for (position, row) in rows.enumerated() { + let weight: T = T.exp(scores[row] - maximum) + work.terms[position] = weight + if data.rowRank[row] < 0 { unranked += weight } + } + let ranked = order.count + var denominators = [T](repeating: T.zero, count: ranked) + var running: T = unranked + var step = ranked - 1 + while step >= 0 { + running += work.terms[order[step]] + denominators[step] = running + step -= 1 + } + var logLikelihood: T = T.zero + var reciprocalSums = [T](repeating: T.zero, count: steps + 1) + for step in 0.. T.zero, denominator.isFinite else { return nil } + let shifted: T = scores[rows.lowerBound + order[step]] - maximum + logLikelihood += shifted - T.log(denominator) + reciprocalSums[step + 1] = reciprocalSums[step] + T(1) / denominator + } + work.taken = [Bool](repeating: false, count: count) + for (position, row) in rows.enumerated() { + let rank = data.rowRank[row] + let available = rank < 0 ? steps : Swift.min(rank + 1, steps) + work.inclusion[position] = work.terms[position] * reciprocalSums[available] + work.taken[position] = rank >= 0 && rank < steps + } + return (logLikelihood, steps) + } + /// The sum, over every set of `friends` of the first `count` terms, of the product of the set's terms. static func rollingSum(terms: [T], count: Int, friends: Int, work: inout [T]) -> T { let width = friends + 1 diff --git a/Tests/BusinessMathTests/Grouped Ranking Tests/PlackettLuceTests.swift b/Tests/BusinessMathTests/Grouped Ranking Tests/PlackettLuceTests.swift new file mode 100644 index 00000000..108516d3 --- /dev/null +++ b/Tests/BusinessMathTests/Grouped Ranking Tests/PlackettLuceTests.swift @@ -0,0 +1,235 @@ +// +// PlackettLuceTests.swift +// BusinessMath +// +// The ranking (Plackett-Luce) likelihood, and how it differs from the subset likelihood. +// +// The oracle is brute force again: the test sums the product of the Plackett-Luce step probabilities itself, over the +// ranked prefix, and the probability of a top-m list is also summed over every permutation of the remaining items to +// show the likelihood is a proper distribution. +// + +import Testing +import Foundation +import Numerics +@testable import BusinessMath + +@Suite("Grouped choice: Plackett-Luce") +struct PlackettLuceTests { + + /// The log-probability of `ranking` (best first) among items with `scores`, by the definition: each step is the chosen + /// item's weight over the weights of the items not yet taken. + private func definitionLogProbability(scores: [Double], ranking: [Int]) -> Double { + var remaining = Set(0.. [[Int]] { + guard items.count > 1 else { return [items] } + var result: [[Int]] = [] + for (index, item) in items.enumerated() { + var rest = items + rest.remove(at: index) + for tail in permutations(rest) { result.append([item] + tail) } + } + return result + } + + private func rankedModel( + candidates: [[Double]], ranking: [Int], reference: [Double], offsets: [[Double]]? = nil + ) throws -> GroupedChoiceModel { + let data = try #require(GroupedChoiceData(rankedGroups: [(candidates: candidates, ranking: ranking)], offsets: offsets)) + return try #require(GroupedChoiceModel(data: data, reference: reference, likelihood: .ranking)) + } + + @Test("Matches the definition for rankings of every length, partial and full") + func definition() throws { + let candidates: [[Double]] = [[1, 0.5], [0, 2], [3, 0], [0.5, 1], [2, 2]] + let reference = [0.4, 0.8] + let multipliers = [1.3, 0.7] + let scale = 0.9 + let scores = candidates.map { scale * (multipliers[0] * reference[0] * $0[0] + multipliers[1] * reference[1] * $0[1]) } + for ranking in [[2], [2, 0], [4, 1, 3], [4, 1, 3, 0], [4, 1, 3, 0, 2]] { + let model = try rankedModel(candidates: candidates, ranking: ranking, reference: reference) + let got = try #require(model.negativeLogLikelihood(multipliers: multipliers, scale: scale, groupWeights: [1])) + let want = -definitionLogProbability(scores: scores, ranking: ranking) + #expect(abs(got.total - want) < 1e-12) + #expect(abs(got.chosen - Double(Swift.min(ranking.count, candidates.count - 1))) < 1e-12) + } + } + + @Test("The probabilities of all top-m lists sum to one") + func properDistribution() { + let scores = [0.3, -0.2, 0.9, 0.1] + for length in 1...3 { + var total = 0.0 + for ranking in permutations([0, 1, 2, 3]).map({ Array($0.prefix(length)) }).reduce(into: Set<[Int]>(), { $0.insert($1) }) { + total += exp(definitionLogProbability(scores: scores, ranking: ranking)) + } + #expect(abs(total - 1) < 1e-12) + } + } + + @Test("With one chosen candidate per group the ranking and subset likelihoods are the same function") + func firstChoice() throws { + let candidates: [[Double]] = [[1, 0], [0, 1], [2, 1]] + let ranked = try rankedModel(candidates: candidates, ranking: [2], reference: [0.5, 1.5]) + let subsetData = try #require(GroupedChoiceData(groups: [ + zip(candidates, [false, false, true]).map { (features: $0, chosen: $1) }, + ])) + let subset = try #require(GroupedChoiceModel(data: subsetData, reference: [0.5, 1.5], likelihood: .subset)) + let a = try #require(ranked.negativeLogLikelihood(multipliers: [1.1, 0.9], scale: 0.8, groupWeights: [1])) + let b = try #require(subset.negativeLogLikelihood(multipliers: [1.1, 0.9], scale: 0.8, groupWeights: [1])) + #expect(abs(a.total - b.total) < 1e-12) + } + + @Test("With two chosen the ranking and subset likelihoods are different numbers") + func twoLikelihoodsDiffer() throws { + // Scores 1, 0, 0 (feature on the first candidate, scale 1). Chosen: candidates 0 and 1. + // Subset: P = e^(1+0) / (e^(1+0) + e^(1+0) + e^(0+0)) = e / (2e + 1). + // Ranking 0 then 1: P = e/(e+1+1) * 1/(1+1) = e / (2(e + 2)). + let candidates: [[Double]] = [[1], [0], [0]] + let ranked = try rankedModel(candidates: candidates, ranking: [0, 1], reference: [1]) + let subsetData = try #require(GroupedChoiceData(groups: [ + zip(candidates, [true, true, false]).map { (features: $0, chosen: $1) }, + ])) + let subset = try #require(GroupedChoiceModel(data: subsetData, reference: [1], likelihood: .subset)) + let e = exp(1.0) + let rankingHand = -log(e / (2 * (e + 2))) + let subsetHand = -log(e / (2 * e + 1)) + let a = try #require(ranked.negativeLogLikelihood(multipliers: [1], scale: 1, groupWeights: [1])) + let b = try #require(subset.negativeLogLikelihood(multipliers: [1], scale: 1, groupWeights: [1])) + #expect(abs(a.total - rankingHand) < 1e-12) + #expect(abs(b.total - subsetHand) < 1e-12) + #expect(abs(a.total - b.total) > 0.1) + // Reversing the order changes the ranking likelihood of an ASYMMETRIC pair, and cannot change the subset's. + let reversed = try rankedModel(candidates: candidates, ranking: [1, 0], reference: [1]) + let c = try #require(reversed.negativeLogLikelihood(multipliers: [1], scale: 1, groupWeights: [1])) + #expect(abs(c.total - a.total) > 0.1) + } + + @Test("A model refuses the other kind of data") + func refusesMismatch() throws { + let ranked = try #require(GroupedChoiceData(rankedGroups: [(candidates: [[1], [0]], ranking: [0])])) + let unordered = try #require(GroupedChoiceData(groups: [[(features: [1], chosen: true), (features: [0], chosen: false)]])) + #expect(ranked.isRanked && !unordered.isRanked) + #expect(GroupedChoiceModel(data: ranked, reference: [1], likelihood: .subset) == nil) + #expect(GroupedChoiceModel(data: unordered, reference: [1], likelihood: .ranking) == nil) + _ = try #require(GroupedChoiceModel(data: ranked, reference: [1], likelihood: .ranking)) + } + + @Test("Ranked data that cannot be built is refused") + func rankedRefusals() { + typealias Entry = (candidates: [[Double]], ranking: [Int]) + #expect(GroupedChoiceData(rankedGroups: []) == nil) + let outOfRange: [Entry] = [(candidates: [[1], [0]], ranking: [2])] + #expect(GroupedChoiceData(rankedGroups: outOfRange) == nil) + let negative: [Entry] = [(candidates: [[1], [0]], ranking: [-1])] + #expect(GroupedChoiceData(rankedGroups: negative) == nil) + let repeated: [Entry] = [(candidates: [[1], [0]], ranking: [0, 0])] + #expect(GroupedChoiceData(rankedGroups: repeated) == nil) + let ragged: [Entry] = [(candidates: [[1, 2], [0]], ranking: [0])] + #expect(GroupedChoiceData(rankedGroups: ragged) == nil) + let nan: [Entry] = [(candidates: [[Double.nan], [0]], ranking: [0])] + #expect(GroupedChoiceData(rankedGroups: nan) == nil) + let offsets: [Entry] = [(candidates: [[1], [0]], ranking: [0])] + #expect(GroupedChoiceData(rankedGroups: offsets, offsets: [[0]]) == nil) + } + + @Test("Which groups are informative: ranked data needs two candidates and one ranked; a full ranking still counts") + func informativeRanked() throws { + let data = try #require(GroupedChoiceData(rankedGroups: [ + (candidates: [[1]], ranking: [0]), // one candidate: nothing to choose among + (candidates: [[1], [0]], ranking: []), // nothing ranked + (candidates: [[1], [0]], ranking: [0]), // one of two + (candidates: [[1], [0], [2]], ranking: [2, 0, 1]), // a full ranking: two informative steps + ])) + #expect(data.informativeGroups == [2, 3]) + #expect(data.stepCount(group: 3) == 2) + #expect(data.stepCount(group: 2) == 1) + #expect(data.comparableGroups == [2]) + } + + @Test("Pooled evaluation of ranked data leaves out a group that ranked every candidate (it has no unchosen one)") + func pooledRanked() throws { + let data = try #require(GroupedChoiceData(rankedGroups: [ + (candidates: [[1], [0], [2]], ranking: [2]), // comparable: one ranked of three + (candidates: [[1], [0], [2]], ranking: [2, 0, 1]), // everyone ranked: nothing unchosen to compare against + ])) + let scores: [Double] = [1, 0, 2, 9, 9, 9] + let pooled = try #require(GroupRankingMetrics.pooledEvaluation(scores: scores, data: data)) + #expect(pooled.positiveCount == 1) + #expect(pooled.negativeCount == 2) + #expect(abs(pooled.auc - 1) < 1e-12) + } + + @Test("The analytic gradient matches a central finite difference, offsets and group weights included") + func gradient() throws { + let data = try #require(GroupedChoiceData(rankedGroups: [ + (candidates: [[1, 0.5, 0], [0, 2, 1], [3, 0, 0.5], [0.5, 1, 0]], ranking: [2, 0]), + (candidates: [[0, 1, 1], [2, 0, 0], [1, 1, 1]], ranking: [1, 2, 0]), + (candidates: [[1, 1, 0], [0, 0, 1], [1, 0, 1], [0, 1, 0], [2, 0, 0]], ranking: [4, 3, 0]), + ], offsets: [[0, 0.1, -0.2, 0], [0, 0, 0.3], [0, 0.1, 0, 0, -0.1]])) + let model = try #require(GroupedChoiceModel(data: data, reference: [2, 0.5, 1.5], likelihood: .ranking)) + let multipliers = [1.2, 0.8, 1.1] + let scale = 0.7 + let weights = [1.0, 2.0, 0.5] + let analytic = try #require(model.evaluate(multipliers: multipliers, scale: scale, groupWeights: weights, gradient: true)).gradient + let step = 1e-6 + for k in 0..<3 { + var up = multipliers, down = multipliers + up[k] += step + down[k] -= step + let high = try #require(model.negativeLogLikelihood(multipliers: up, scale: scale, groupWeights: weights)).total + let low = try #require(model.negativeLogLikelihood(multipliers: down, scale: scale, groupWeights: weights)).total + #expect(abs(analytic[k] - (high - low) / (2 * step)) < 1e-7) + } + } + + @Test("Scores far apart stay finite, with early choices dominating the later denominators") + func stability() throws { + let model = try rankedModel(candidates: [[1], [0.5], [0]], ranking: [0, 1], reference: [1]) + let result = try #require(model.negativeLogLikelihood(multipliers: [1], scale: 800, groupWeights: [1])) + #expect(result.total.isFinite) + #expect(abs(result.total) < 1e-12) + } + + @Test("Recovers known weights from rankings drawn by sequential choice") + func recovery() throws { + var generator = SplitMix64(seed: 77) + let beta = [0.9, 0.4] + var groups: [(candidates: [[Double]], ranking: [Int])] = [] + for index in 0..<1200 { + let candidates: [[Double]] = (0..<7).map { _ in + [Double.random(in: 0..<1, using: &generator) < 0.4 ? 1 : 0, Double.random(in: 0..<2, using: &generator)] + } + var remaining = Array(0..<7) + var ranking: [Int] = [] + let depth = 1 + index % 4 + for _ in 0..= target { picked = position; break } + } + ranking.append(remaining[picked]) + remaining.remove(at: picked) + } + groups.append((candidates: candidates, ranking: ranking)) + } + let data = try #require(GroupedChoiceData(rankedGroups: groups)) + let model = try #require(GroupedChoiceModel(data: data, reference: [1, 1], likelihood: .ranking)) + let fit = try model.fit(groupWeights: [Double](repeating: 1, count: 1200), penalty: 1e-6) + for k in 0..<2 { #expect(abs(fit.scale * fit.multipliers[k] - beta[k]) < RecoveryTolerance.weight) } + } +} From 7527f0493a0f8612b8849cce2a0d71f0eda05739 Mon Sep 17 00:00:00 2001 From: Justin Purnell Date: Sat, 21 Nov 2026 16:23:43 -0500 Subject: [PATCH 08/13] fix(regression): damp a singular Newton step when every fitted probability is saturated; close mutation gaps Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_017dtpLZ6XGCJVmSqc1u4qUt --- .../LogisticRegression+Penalty.swift | 36 +++++++++++-- .../PenalisedLogisticRegressionTests.swift | 52 ++++++++++++++++++- 2 files changed, 82 insertions(+), 6 deletions(-) diff --git a/Sources/BusinessMath/Statistics/Regression/LogisticRegression+Penalty.swift b/Sources/BusinessMath/Statistics/Regression/LogisticRegression+Penalty.swift index 01715533..0e0ffd89 100644 --- a/Sources/BusinessMath/Statistics/Regression/LogisticRegression+Penalty.swift +++ b/Sources/BusinessMath/Statistics/Regression/LogisticRegression+Penalty.swift @@ -198,10 +198,9 @@ extension LogisticRegression { information[column][column] += lambda } - guard let delta = Self.solveSymmetric(information, score) else { - // Unreachable for lambda > 0: the information plus lambda on the slopes is - // positive definite. A singular result here is a numerical failure, reported as - // one rather than as a fit. + guard let delta = Self.dampedSolve(information, score) else { + // The system stayed unsolvable under heavy damping: the information overflowed or + // holds a NaN. That is a numerical failure and is reported as one, not as a fit. throw LogisticRegressionError.didNotConverge(iterations: step, gradientNorm: Double.infinity) } var largest: T = T.zero @@ -228,7 +227,8 @@ extension LogisticRegression { for index in 0..= objective - slack { break } + // A NaN or -infinity objective fails this comparison, so it needs no separate finiteness test. + if nextObjective >= objective - slack { break } scale /= T(2) halvings += 1 } @@ -256,6 +256,32 @@ extension LogisticRegression { penalty: LogisticPenalty(lambda: lambda, centre: centre)) } + /// Solves the Newton system, adding damping when it is singular. + /// + /// The penalised information is positive definite on the slopes, but the *intercept* + /// entry is the sum of the fitted weights `p(1 − p)`, which is zero to working precision + /// when every fitted probability is saturated (a start far from the optimum, or very large + /// predictors). The exact system is then singular though the objective is not. Levenberg + /// damping, adding `μ` to the diagonal with `μ` growing by a factor of one hundred, gives a + /// step that still ascends; the caller's step-halving keeps it honest. + /// + /// - Returns: The step, or `nil` if even a heavily damped system cannot be solved. + static func dampedSolve(_ matrix: [[T]], _ rhs: [T]) -> [T]? { + if let exact = solveSymmetric(matrix, rhs), exact.allSatisfy({ $0.isFinite }) { return exact } + var largestDiagonal: T = T(1) + for index in 0.. largestDiagonal { + largestDiagonal = matrix[index][index] + } + var damping: T = T(1) / T(100_000_000) * largestDiagonal + for _ in 0..<12 { + var damped = matrix + for index in 0.. Date: Sat, 21 Nov 2026 16:38:50 -0500 Subject: [PATCH 09/13] refactor(regression): drop a finiteness guard that dampedSolve already makes unreachable Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_017dtpLZ6XGCJVmSqc1u4qUt --- .../Statistics/Regression/LogisticRegression+Penalty.swift | 3 --- 1 file changed, 3 deletions(-) diff --git a/Sources/BusinessMath/Statistics/Regression/LogisticRegression+Penalty.swift b/Sources/BusinessMath/Statistics/Regression/LogisticRegression+Penalty.swift index 0e0ffd89..5e1f42b4 100644 --- a/Sources/BusinessMath/Statistics/Regression/LogisticRegression+Penalty.swift +++ b/Sources/BusinessMath/Statistics/Regression/LogisticRegression+Penalty.swift @@ -208,9 +208,6 @@ extension LogisticRegression { let size: T = delta[index] < T.zero ? -delta[index] : delta[index] if size > largest { largest = size } } - guard largest.isFinite else { - throw LogisticRegressionError.didNotConverge(iterations: step, gradientNorm: Double.infinity) - } // Halve the step until the objective does not fall. A full Newton step is accepted // whenever it improves, so the quadratic convergence near the optimum is kept. From 7ab2cd57cd3db4f9193a2418183625790796a972 Mon Sep 17 00:00:00 2001 From: Justin Purnell Date: Sat, 21 Nov 2026 16:57:48 -0500 Subject: [PATCH 10/13] docs(changelog): penalised LogisticRegression.fit(penalty:) (B6) Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_017dtpLZ6XGCJVmSqc1u4qUt --- CHANGELOG.md | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index a119e4ed..1f5ed137 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,19 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### [Unreleased] +**Added: a penalised `LogisticRegression.fit(penalty:)` (phase B6 of `project/plans/proposals/BusinessMathGroupedRanking.md`).** +Additive; the existing `fit(maxIterations:tolerance:)`, its errors and its tests are unchanged, and `validatedDesign` gains a defaulted +parameter that leaves the unpenalised path as it was. A ridge-type penalty `(lambda / 2) * sum (beta_k - c_k)^2` over the slopes, centred on +a supplied vector (zero by default), with the intercept unpenalised. With `lambda > 0` the objective is strictly concave, so data that the +unpenalised fit refuses as separated or rank-deficient, and designs with more predictors than observations, are fitted. It still refuses a +constant outcome when an intercept is fitted (the intercept is not penalised), a penalty that is not positive and finite, a centre of the +wrong width, malformed data, and an exhausted iteration budget. New public types: `LogisticPenalty`, `PenalisedLogisticFit` (no classical +standard errors: they are not valid under a penalty; use a bootstrap). The coefficient-space form is deliberate: `LogisticRegression` has no +reference weights, so the relative-change form planned for the grouped models does not apply here. It is not Firth's penalty. Newton steps +are halved until the penalised objective does not fall, and a singular system (every fitted probability saturated, so the intercept's +information is zero) is solved with Levenberg damping. Tests were checked against an independent BFGS run and against the penalised score +equations, and a mutation audit killed 22 of 27 mutants (the survivors are recorded in the build report). + ### [3.0.0-alpha.17] - 2026-11-14 **The Network module gains weighted graphs and the graph measures that lived in the ClassGraph package** (ADR-006 to ADR-010; plan From 31a1307178cad107cf9829d494dc327092dfcf2a Mon Sep 17 00:00:00 2001 From: Justin Purnell Date: Sat, 21 Nov 2026 16:59:01 -0500 Subject: [PATCH 11/13] docs(changelog): correct the mutation count for B6 Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_017dtpLZ6XGCJVmSqc1u4qUt --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1f5ed137..7e84e52a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -22,7 +22,7 @@ standard errors: they are not valid under a penalty; use a bootstrap). The coeff reference weights, so the relative-change form planned for the grouped models does not apply here. It is not Firth's penalty. Newton steps are halved until the penalised objective does not fall, and a singular system (every fitted probability saturated, so the intercept's information is zero) is solved with Levenberg damping. Tests were checked against an independent BFGS run and against the penalised score -equations, and a mutation audit killed 22 of 27 mutants (the survivors are recorded in the build report). +equations, and a mutation audit killed 22 of 25 applicable mutants; the three survivors (the start point, which does not change a strictly concave optimum, and two finiteness checks on the damped solve that no input reached) are recorded in the build report. ### [3.0.0-alpha.17] - 2026-11-14 From a7864fabe7a72b09f61cf87d7797df467aecc113 Mon Sep 17 00:00:00 2001 From: Justin Purnell Date: Sat, 21 Nov 2026 17:56:52 -0500 Subject: [PATCH 12/13] docs(grouped-ranking): DocC article 2.8, ADR-011 accepted, CHANGELOG, master plan and proposal reconciled (B7) The article's examples are run by GroupedRankingDocumentationTests. The softmax test now pins the direction of its bias (understates: measured 0.636 for a true weight of 1). Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_017dtpLZ6XGCJVmSqc1u4qUt --- CHANGELOG.md | 6 +- .../BusinessMath.docc/2.8-GroupedRanking.md | 177 ++++++++++++++++++ .../BusinessMath.docc/Part2-Analysis.md | 3 + .../GroupedChoiceFitTests.swift | 2 + .../GroupedRankingDocumentationTests.swift | 101 ++++++++++ project/decisions/architecture_decisions.md | 98 ++++++++++ project/master_plan.md | 13 +- .../proposals/BusinessMathGroupedRanking.md | 20 +- 8 files changed, 407 insertions(+), 13 deletions(-) create mode 100644 Sources/BusinessMath/BusinessMath.docc/2.8-GroupedRanking.md create mode 100644 Tests/BusinessMathTests/Grouped Ranking Tests/GroupedRankingDocumentationTests.swift diff --git a/CHANGELOG.md b/CHANGELOG.md index 26cf0542..bd9dea06 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,8 +19,10 @@ non-negativity by projection, a restart-guarded accelerated search, and a thrown `GroupRankingMetrics` (per-group percentile, top-own and top-k, and the pooled `ClassifierEvaluation`), `GroupResampling` (an unbiased bounded draw, bootstrap weights over groups, balanced fold assignment), and `GroupedCrossValidation` (nested penalty choice, group-bootstrap intervals, and `HeldOutComparison`, which reports a fact about held-out groups and applies no adoption threshold). A softmax per chosen candidate is biased on the -same data (a recovery test shows a true weight of 1 fitted at about 0.64); the conditional likelihood recovers it. Not yet built: the penalised -`LogisticRegression.fit` (B6), the DocC article and ADR-011 (B7), and the MCP tools (phase D, in businessMathMCP). +same data (a recovery test shows a true weight of 1 fitted at about 0.64, so it understates the weight); the conditional likelihood recovers it. The +penalised `LogisticRegression.fit` is the next entry (B6). Documentation (B7): the DocC article `2.8-GroupedRanking` (its examples are run by +`GroupedRankingDocumentationTests`) and ADR-011, which records the deviations from the proposal. Not yet built: the MCP tools (phase D, in +businessMathMCP). **Added: a penalised `LogisticRegression.fit(penalty:)` (phase B6 of `project/plans/proposals/BusinessMathGroupedRanking.md`).** Additive; the existing `fit(maxIterations:tolerance:)`, its errors and its tests are unchanged, and `validatedDesign` gains a defaulted diff --git a/Sources/BusinessMath/BusinessMath.docc/2.8-GroupedRanking.md b/Sources/BusinessMath/BusinessMath.docc/2.8-GroupedRanking.md new file mode 100644 index 00000000..2a4daf37 --- /dev/null +++ b/Sources/BusinessMath/BusinessMath.docc/2.8-GroupedRanking.md @@ -0,0 +1,177 @@ +# Grouped Ranking: What Predicts a Choice + +Fit what predicts which candidates get chosen *within* each chooser's own set, test whether a refit beats the weights you already have, and keep the verdict honest. + +## Overview + +Some data has the shape "within each group, some candidates were chosen": a person and the colleagues they named, a shopper and the products they clicked, a query and the results someone opened. The question is what about a candidate predicts being chosen. A pooled regression answers a different question. It credits any feature that merely correlates with choosers who choose a lot, because a chooser who names fifteen people contributes fifteen positives and one who names two contributes two. + +The grouped-ranking toolkit compares each group only with itself, so how much a group chooses drops out. It is in `Statistics/GroupedRanking`, generic over `T: Real & Sendable & BinaryFloatingPoint`, and additive: no existing symbol changed. + +- ``GroupedChoiceData`` holds the groups, candidates with numeric features, and which were chosen (or in what order). +- ``GroupedChoiceModel`` pairs the data with **reference weights** and a ``ChoiceLikelihood``. ``GroupedChoiceModel/fit(groupWeights:penalty:frozen:start:maxIterations:)`` refits the weights, pulled toward the reference by a penalty. +- ``GroupRankingMetrics`` scores a set of candidate scores group by group. +- ``GroupedCrossValidation`` chooses the penalty, bootstraps over groups, and runs ``GroupedCrossValidation/heldOutComparison(model:penalties:minimumChosen:folds:innerFolds:resamples:level:seed:)``, which returns a ``HeldOutComparison``. +- ``LogisticRegression/fit(penalty:maxIterations:tolerance:)`` is a separate, penalised logistic fit. + +Everything fitted here **ranks**. A candidate nobody chose is *unknown*, not rejected, so the weights say which candidates a chooser is more likely to choose, not by how much they are chosen. + +## The data + +A group is one chooser's candidates. Each candidate is a row of features and a flag. + +```swift +let small = GroupedChoiceData(groups: [ + [(features: [1, 0], chosen: true), (features: [0, 1], chosen: false), (features: [0, 0], chosen: false)], + [(features: [1, 1], chosen: true), (features: [0, 0], chosen: false)], +]) +// small?.groupCount == 2, small?.featureCount == 2, small?.informativeGroups == [0, 1] +``` + +Initialisers return `nil` for malformed data. Features are stored sparsely (only the non-zero entries), so a wide, mostly-zero feature matrix costs memory in proportion to what is present. An optional fixed offset per candidate carries a term the model must not fit, such as a deduction you apply by rule. + +A *group with no chosen candidate, or with every candidate chosen, has nothing to compare*; it is not an error, and it adds nothing to the fit (``GroupedChoiceData/informativeGroups`` lists the groups that do). + +## Two likelihoods, not one + +``ChoiceLikelihood`` has two cases, and they are different functions. + +- ``ChoiceLikelihood/subset``: the group chose an *unordered* set of candidates, the **conditional logit**. How many a group chose does not move the weights. +- ``ChoiceLikelihood/ranking``: the group ranked its top candidates *in order*, the **Plackett-Luce** model. Each next choice is made among the candidates not yet taken. + +With exactly one chosen candidate per group they coincide. With more than one they do not, and Plackett-Luce taken over an arbitrary order of an unordered set would make the answer depend on the order chosen. So each model refuses the other's data: + +```swift +let ranked = GroupedChoiceData(rankedGroups: [ + (candidates: [[1, 0], [0, 1], [0, 0]], ranking: [0, 1]), // candidate 0 first, then 1 + (candidates: [[1, 1], [0, 0], [1, 0]], ranking: [0, 2]), + (candidates: [[0, 1], [1, 0], [0, 0]], ranking: [1]), +]) +// GroupedChoiceModel(data: ranked, reference: [1, 1], likelihood: .ranking) is a model; +// the same data with .subset is nil, and unordered data with .ranking is nil. +``` + +## Fitting around a reference + +Most uses start from weights somebody already believes in. The model fits two things: one **scale** that turns the reference weights into log-odds, then a **multiplier** on each weight (at least zero), with a penalty on how far a multiplier moves from 1. A large penalty returns your weights; a small one approaches the unpenalised optimum. The data has to argue for any change. + +The example below builds 60 choosers with six candidates each. Feature 0 genuinely drives the choice; feature 1 does not. The reference weights say both matter equally. + +```swift +var generator = SplitMix64(seed: 11) +let groups: [[(features: [Double], chosen: Bool)]] = (0..<60).map { _ in + let candidates: [[Double]] = (0..<6).map { _ in + [Double.random(in: 0..<1, using: &generator) < 0.4 ? 1 : 0, + Double.random(in: 0..<1, using: &generator) < 0.4 ? 1 : 0] + } + let appeal: [Double] = candidates.map { exp(1.5 * $0[0]) } + var pick = Double.random(in: 0..<1, using: &generator) * appeal.reduce(0, +) + var chosenIndex = appeal.count - 1 + for (index, share) in appeal.enumerated() { + if pick < share { chosenIndex = index; break } + pick -= share + } + return candidates.enumerated().map { (features: $0.element, chosen: $0.offset == chosenIndex) } +} + +guard let data = GroupedChoiceData(groups: groups), + let model = GroupedChoiceModel(data: data, reference: [1, 1], likelihood: .subset) else { + fatalError("the example's data is well-formed") +} +let weights = [Double](repeating: 1, count: data.groupCount) // every group counts once +let fit = try model.fit(groupWeights: weights, penalty: 0.05) +// fit.multipliers ≈ [1.69, 0.27] (the real feature is raised, the other lowered) +// fit.scale ≈ 0.785 (effective weights ≈ 1.32 and 0.21, against a true 1.5 and 0) +// fit.converged true +``` + +`fit` **throws** ``GroupedChoiceError/didNotConverge(iterations:gradientNorm:)`` if the search does not settle. It never returns an unsettled estimate as though it had settled. + +The penalty acts on each multiplier's *relative* change. A feature whose reference is `0` cannot move, because its multiplier is not identified. ``GroupedChoiceModel/referenceFit(groupWeights:)`` keeps every multiplier at 1 and fits only the scale: the reference weights, calibrated. + +## Ranking metrics, group by group + +``GroupRankingMetrics/perGroup(scores:data:k:)`` takes one score per candidate row and returns, for each group, where its chosen candidates fell. + +```swift +if let scores = model.scores(for: fit), + let perGroup = GroupRankingMetrics.perGroup(scores: scores, data: data, k: 3) { + let summary = GroupRankingMetrics.summary(perGroup) + // summary.groups 60 + // summary.meanPercentile ≈ 0.65 (0.5 is chance) + // summary.topOwnShare ≈ 0.33 (the share of a group's chosen candidates inside its top *n*, *n* being how many it chose) +} +``` + +``GroupRankingMetrics/pooledEvaluation(scores:data:)`` pools the comparable groups and hands the result to ``ClassifierEvaluation``, so the ROC area and the confusion matrix are the library's own. + +A metric is `nil` where it is not defined: scores that are not one per row, a group with nothing to compare, a score that is not finite. + +## Does a refit beat what you had? + +Fitting on the data you score flatters the refit. ``GroupedCrossValidation/heldOutComparison(model:penalties:minimumChosen:folds:innerFolds:resamples:level:seed:)`` holds each group out of the fit exactly once, picks the penalty on the training groups only (nested folds), and compares the refit with the reference weights on the groups it never saw. + +```swift +let comparison = GroupedCrossValidation.heldOutComparison( + model: model, penalties: [.reference, .penalty(0.05), .penalty(0.5)], minimumChosen: 10, + folds: 5, innerFolds: 3, resamples: 200, level: 0.9, seed: 1) +// comparison?.referencePercentile ≈ 0.63 +// comparison?.refitPercentile ≈ 0.65 +// comparison?.difference ≈ 0.023 +// comparison?.lower, comparison?.upper ≈ 0.003, 0.045 (90% bootstrap interval over groups) +// comparison?.refitBeatsReference true +``` + +``HeldOutComparison`` states a **fact**: the two mean percentiles, their paired difference, and a bootstrap interval for the difference over *groups* (never rows). It does not say whether to adopt anything. ``HeldOutComparison/refitBeatsReference`` is true when the interval's lower end is above zero; ``HeldOutComparison/intervalExcludesZero`` is true on either side. How big a move counts, and how many chosen candidates a feature needs before it is refitted (`minimumChosen`, which keeps a thin feature at its reference value), belong to your own policy and sit on top of these figures. + +Seeds are `UInt64` values. The fold assignment, each inner assignment and the bootstrap use derived seeds from `SplitMix64`, so a run repeats exactly. + +## A penalised logistic regression + +``LogisticRegression/fit(maxIterations:tolerance:)`` refuses data a feature separates perfectly, because the coefficient would run to infinity. A small ridge penalty fixes that: + +```swift +let regression = LogisticRegression(predictors: [[0], [1], [2], [3]], + outcomes: [false, false, true, true]) +// regression.fit() throws LogisticRegressionError.separation +let logisticFit = try regression.fit(penalty: LogisticPenalty(lambda: 0.1)) +// logisticFit.coefficients ≈ [-3.98, 2.65] (intercept, then slope) +// logisticFit.probability([1.5]) ≈ 0.5 +``` + +``LogisticPenalty`` is `(lambda / 2) × Σ (β − centre)²`, with the intercept left unpenalised and a centre of zero by default. The result is a ``PenalisedLogisticFit``, not a `LogisticFit`: it has **no classical standard errors**, because they are not valid under a penalty. Use a bootstrap. The existing unpenalised `fit` and its errors are unchanged. + +A constant outcome is still refused when an intercept is fitted, since the unpenalised intercept would diverge. + +## What it does not do + +- It estimates **rankings, not probabilities**. A candidate nobody chose is unknown; the fitted weights say who is more likely to be chosen, not how likely. +- It does **not** decide whether to adopt a refit. ``HeldOutComparison`` reports; you decide. +- The penalty on the grouped models acts on the *relative* change of each reference weight. ``LogisticRegression`` has no reference weights, so its penalty is a coefficient-space ridge. +- The MCP tools for this toolkit are a later phase, in businessMathMCP. + +## Topics + +### Data and models + +- ``GroupedChoiceData`` +- ``GroupedChoiceModel`` +- ``ChoiceLikelihood`` +- ``GroupedChoiceFit`` +- ``GroupedChoiceError`` + +### Evaluation + +- ``GroupRankingMetrics`` +- ``GroupRanking`` +- ``GroupRankingSummary`` +- ``GroupedCrossValidation`` +- ``HeldOutComparison`` +- ``PenaltyChoice`` +- ``BootstrapIntervals`` +- ``GroupResampling`` + +### Penalised logistic regression + +- ``LogisticPenalty`` +- ``PenalisedLogisticFit`` diff --git a/Sources/BusinessMath/BusinessMath.docc/Part2-Analysis.md b/Sources/BusinessMath/BusinessMath.docc/Part2-Analysis.md index 40d4b33e..edc72e0e 100644 --- a/Sources/BusinessMath/BusinessMath.docc/Part2-Analysis.md +++ b/Sources/BusinessMath/BusinessMath.docc/Part2-Analysis.md @@ -41,6 +41,9 @@ This section bridges the gap between calculation and insight. Whether you're eva - - +### Choice Models and Rankings +- + ## Prerequisites Before diving into Part II, you should be comfortable with time series operations, basic financial calculations, and the fluent API patterns from Part I. If you skipped Part I, at minimum review chapters 1.1-1.3 before proceeding. diff --git a/Tests/BusinessMathTests/Grouped Ranking Tests/GroupedChoiceFitTests.swift b/Tests/BusinessMathTests/Grouped Ranking Tests/GroupedChoiceFitTests.swift index 391048ba..2358de29 100644 --- a/Tests/BusinessMathTests/Grouped Ranking Tests/GroupedChoiceFitTests.swift +++ b/Tests/BusinessMathTests/Grouped Ranking Tests/GroupedChoiceFitTests.swift @@ -66,6 +66,8 @@ struct GroupedChoiceFitTests { let softmax = (low + high) / 2 #expect(abs(conditional - 1.0) < 0.1) #expect(abs(softmax - 1.0) > 0.25) + // The direction: the softmax UNDERSTATES the weight (measured at about 0.64 for a true weight of 1), it does not overstate it. + #expect(softmax < 0.75) } @Test("With no signal the effective weights are close to zero") diff --git a/Tests/BusinessMathTests/Grouped Ranking Tests/GroupedRankingDocumentationTests.swift b/Tests/BusinessMathTests/Grouped Ranking Tests/GroupedRankingDocumentationTests.swift new file mode 100644 index 00000000..11909279 --- /dev/null +++ b/Tests/BusinessMathTests/Grouped Ranking Tests/GroupedRankingDocumentationTests.swift @@ -0,0 +1,101 @@ +// +// GroupedRankingDocumentationTests.swift +// BusinessMath +// +// The examples in `2.8-GroupedRanking.md`, run. Each test is the article's code with its stated results asserted, so +// an example that stops compiling or stops giving the figure the article quotes fails here. +// + +import Testing +import Foundation +import Numerics +@testable import BusinessMath + +@Suite("Grouped ranking: documentation examples") +struct GroupedRankingDocumentationTests { + + /// The article's synthetic class: 60 choosers, 6 candidates each, feature 0 really matters and feature 1 does not. + private func articleGroups() -> [[(features: [Double], chosen: Bool)]] { + var generator = SplitMix64(seed: 11) + return (0..<60).map { _ in + let candidates: [[Double]] = (0..<6).map { _ in + [Double.random(in: 0..<1, using: &generator) < 0.4 ? 1 : 0, + Double.random(in: 0..<1, using: &generator) < 0.4 ? 1 : 0] + } + let weights: [Double] = candidates.map { exp(1.5 * $0[0]) } + var pick = Double.random(in: 0..<1, using: &generator) * weights.reduce(0, +) + var chosenIndex = weights.count - 1 + for (index, weight) in weights.enumerated() { + if pick < weight { chosenIndex = index; break } + pick -= weight + } + return candidates.enumerated().map { (features: $0.element, chosen: $0.offset == chosenIndex) } + } + } + + @Test("Fitting: the data type, the model and a penalised fit") + func fitting() throws { + let data = try #require(GroupedChoiceData(groups: articleGroups())) + let model = try #require(GroupedChoiceModel(data: data, reference: [1, 1], likelihood: .subset)) + let weights = [Double](repeating: 1, count: data.groupCount) + let fit = try model.fit(groupWeights: weights, penalty: 0.05) + // The article: multipliers about [1.69, 0.27], scale about 0.785. + #expect(abs(fit.multipliers[0] - 1.69) < 0.02) + #expect(abs(fit.multipliers[1] - 0.27) < 0.02) + #expect(abs(fit.scale - 0.785) < 0.01) + #expect(data.groupCount == 60) + #expect(fit.converged) + } + + @Test("Ranking metrics and the held-out comparison") + func ranking() throws { + let data = try #require(GroupedChoiceData(groups: articleGroups())) + let model = try #require(GroupedChoiceModel(data: data, reference: [1, 1], likelihood: .subset)) + let weights = [Double](repeating: 1, count: data.groupCount) + let fit = try model.fit(groupWeights: weights, penalty: 0.05) + let scores = try #require(model.scores(for: fit)) + let perGroup = try #require(GroupRankingMetrics.perGroup(scores: scores, data: data, k: 3)) + let summary = GroupRankingMetrics.summary(perGroup) + // The article: mean percentile about 0.65, top-own share about 0.33. + let percentile = try #require(summary.meanPercentile) + let topOwn = try #require(summary.topOwnShare) + #expect(abs(percentile - 0.65) < 0.01) + #expect(abs(topOwn - 0.33) < 0.01) + let comparison = try #require(GroupedCrossValidation.heldOutComparison( + model: model, penalties: [.reference, .penalty(0.05), .penalty(0.5)], minimumChosen: 10, + folds: 5, innerFolds: 3, resamples: 200, level: 0.9, seed: 1)) + // The article: held out, 0.63 against 0.65, a difference of about 0.023 with a 90% interval of about 0.003 to 0.045. + #expect(abs(comparison.referencePercentile - 0.63) < 0.01) + #expect(abs(comparison.refitPercentile - 0.65) < 0.01) + #expect(abs(comparison.difference - 0.023) < 0.005) + #expect(abs(comparison.lower - 0.003) < 0.005) + #expect(abs(comparison.upper - 0.045) < 0.005) + #expect(comparison.refitBeatsReference) + #expect(summary.groups == 60) + } + + @Test("Plackett-Luce: ranked groups, and each model refuses the other's data") + func plackettLuce() throws { + let ranked = try #require(GroupedChoiceData(rankedGroups: [ + (candidates: [[1, 0], [0, 1], [0, 0]], ranking: [0, 1]), + (candidates: [[1, 1], [0, 0], [1, 0]], ranking: [0, 2]), + (candidates: [[0, 1], [1, 0], [0, 0]], ranking: [1]), + ])) + #expect(GroupedChoiceModel(data: ranked, reference: [1, 1], likelihood: .ranking) != nil) + #expect(GroupedChoiceModel(data: ranked, reference: [1, 1], likelihood: .subset) == nil) + } + + @Test("Penalised logistic regression on separated data") + func penalisedLogistic() throws { + let regression = LogisticRegression(predictors: [[0], [1], [2], [3]], outcomes: [false, false, true, true]) + var refused = false + do { _ = try regression.fit() } catch LogisticRegressionError.separation { refused = true } + #expect(refused) + let fit = try regression.fit(penalty: LogisticPenalty(lambda: 0.1)) + // The article: coefficients about [-3.98, 2.65] (intercept, then slope), and a probability of about 0.5 at 1.5. + #expect(abs(fit.coefficients[0] + 3.98) < 0.02) + #expect(abs(fit.coefficients[1] - 2.65) < 0.02) + #expect(abs(fit.probability([1.5]) - 0.5) < 0.01) + #expect(fit.coefficients.count == 2) + } +} diff --git a/project/decisions/architecture_decisions.md b/project/decisions/architecture_decisions.md index 2a90f9fc..40f1daa8 100644 --- a/project/decisions/architecture_decisions.md +++ b/project/decisions/architecture_decisions.md @@ -611,3 +611,101 @@ supersedes: null amends: ADR-009 superseded_by: null ``` + +--- + +```yaml +id: ADR-011 +date: 2026-11-21 +status: accepted +category: api +title: Grouped ranking is a Statistics toolkit (conditional logit, Plackett-Luce, prior-centred penalty, held-out comparison), and LogisticRegression gains a separate penalised fit +context: | + ClassGraph's weight backtest (about 2,100 lines in ClassGraph Sources/ClassGraphCore/Backtest at main c81c833) holds generic + statistics written by hand: an exact conditional-logit fitter, per-group ranking metrics, a bootstrap over groups, nested + grouped k-fold, and a copy of SplitMix64. ClassGraph's rule is that generic machinery lives here (its ADR-014). The need is the + general one of fitting what predicts a choice within each chooser's own candidates, where a pooled regression credits any feature + that merely correlates with choosers who choose a lot. The existing LogisticRegression is unpenalised and refuses data a feature + separates, so it cannot fit the sparse features such a model meets. The owner approved upstreaming, with ClassGraph keeping its + own protocol (label definitions, the weight mapping, the candidate file, the rescale-to-density step, privacy, and the adoption + thresholds as policy) (2026-11-21). Design: project/plans/proposals/BusinessMathGroupedRanking.md. Built as phases B1 to B6; + this record and the DocC article 2.8-GroupedRanking are B7. +decision: | + A domain-free toolkit in Statistics/GroupedRanking, generic over T: Real & Sendable & BinaryFloatingPoint, additive to the public API: + - GroupedChoiceData: candidates grouped by chooser, dense or sparse (only non-zero entries stored), optional fixed per-candidate + offsets, or ranked groups. GroupedChoiceModel pairs it with reference weights and a ChoiceLikelihood, .subset (the exact + conditional logit for an unordered chosen set) or .ranking (Plackett-Luce). Each model refuses the other's data (init? is nil): + with more than one chosen candidate the two are different likelihoods, and "first-choice conditional logit is a special case of + Plackett-Luce" holds only for one chosen candidate per group. + - fitScale / referenceFit / fit: the scale is fitted first, then the multipliers around the reference, with a penalty on each + multiplier's relative change (m - 1), non-negativity by projection, a restart-guarded accelerated search, and a thrown + GroupedChoiceError.didNotConverge rather than an unsettled result. + - GroupRankingMetrics (per-group percentile, top-own and top-k, a summary, and a pooled evaluation by ClassifierEvaluation, not + reimplemented), GroupResampling (an unbiased bounded draw, bootstrap weights over groups, balanced fold assignment), and + GroupedCrossValidation (nested penalty choice, group-bootstrap intervals, heldOutComparison). + - HeldOutComparison states a fact about held-out groups (the two mean percentiles, their paired difference, a bootstrap interval) + and applies no adoption threshold: how big a move counts and how many chosen candidates a feature needs stay a caller's policy. + - LogisticRegression.fit(penalty: LogisticPenalty) in LogisticRegression+Penalty.swift: a coefficient-space ridge, (lambda / 2) times the + sum of squared distances from a centre (zero by default), intercept unpenalised, returning PenalisedLogisticFit. The existing + fit(maxIterations:tolerance:), its errors and its tests are unchanged. + Deviations from the proposal, as built (each was a choice made during the build, not a decision the owner reserved): + 1. Offsets. GroupedChoiceData takes an optional fixed per-candidate offset, so a caller can carry a deduction the model must not + fit (ClassGraph's orientation deduction). The proposal had none. + 2. fit signature and failure. fit gains maxIterations and start, and throws didNotConverge. ClassGraph's private fitter accepted + unsettled fits, so the phase C parity run may expose cases where it never settled. + 3. Seeds, not generators. heldOutComparison, choosePenalty and bootstrapIntervals take a UInt64 seed and use SplitMix64 + internally (SwiftDeterminism is the ground truth); only GroupResampling takes a generator. + 4. Optional metrics. GroupRankingMetrics.perGroup returns nil when the scores are not one per row or k is below 1, and an + element is nil for a group with nothing to compare; the summary's means are optional. + 5. Two interval checks. HeldOutComparison has intervalExcludesZero (either side of zero) and refitBeatsReference (lower end above + zero); the proposal named one. + 6. The bounded draw is unbiased and differs from ClassGraph's modulo draw, so ClassGraph's real-archive figures shift slightly when + it moves over (phase C records both runs). + 7. The softmax bias runs the other way from ClassGraph's record. A softmax per chosen candidate UNDERSTATES a true weight: the + recovery test fits a true weight of 1 at about 0.64, a bias of about 36 percent (ClassGraph's ADR-022 says about 40 percent and + "overstates"; the size agrees and the direction there is wrong). The softmax is not shipped; the test keeps it as the deliberately + wrong comparison. + 8. The penalised logistic fit returns PenalisedLogisticFit, not LogisticFit, because LogisticFit.standardErrors is non-optional and + classical errors are not valid under a penalty; use a bootstrap. + 9. Constant outcome. With an intercept fitted the penalised fit still refuses a constant outcome, as separation(variables: []), + because the unpenalised intercept diverges. The proposal said the penalised path never throws separation. Without an intercept + it is fitted. A design with fewer rows than predictors is accepted (a defaulted requireIdentifiable parameter on validatedDesign). + 10. Newton steps are halved until the penalised objective does not fall, and a singular system (every fitted probability saturated, + so the intercept's information is zero) is solved with Levenberg damping; the mutation tests exposed that failure. + The penalty form on LogisticRegression is coefficient-space ridge, and the grouped models' is on the relative change; the owner's + "relative change only, for now" applies to the grouped models, which have a reference scale, and LogisticRegression has none. + The MCP tools are phase D, pending, in businessMathMCP (a separate repository) under its own proposal. Nothing here exposes them. +rationale: | + - The within-group comparison removes how much each chooser chooses; the toolkit's recovery and talkative-group tests pin it. + - Reference-centred shrinkage makes the data argue for any change from supplied weights; a large penalty returns the reference. + - Reporting a held-out fact and leaving the threshold to the caller keeps the policy where the stakes are known. + - Generic over T and seeded through SwiftDeterminism follow the repository's own conventions, and keep ClassGraph's migration a deletion. +consequences: | + Every fit that did not settle is an error, not a result. The public API is generic with no @_specialize; its speed for Double callers + across the module boundary is unmeasured (ClassGraph's baseline for the backtest on a 532-person class was 229 seconds). Linux + (Swift 6.2.1) type-checking has not been run until CI does. Mutation audits killed 71 of 78 mutants for B1 to B5 (the survivors + equivalent, optimiser-path only, or in non-convergence handling a test could not reach) and 22 of 25 applicable for B6 (the start + point is equivalent, and two finiteness checks inside the damped solve were not reached). ClassGraph's ADR-022 states the softmax + bias in the wrong direction and needs the correction made in that repository. A release tag, and the exact version, are the owner's. +alternatives_rejected: + - "Leave it in ClassGraph: the status quo; the next analysis of the same shape rewrites the likelihood, and the softmax mistake is made again." + - "A shared Statistics/Ranking folder holding this and Comparison Statistics: those functions test whether judges agree on rank matrices (WineTaster uses them), this models what predicts a choice from features; a shared parent would force moving existing code." + - "Group-indicator dummies in LogisticRegression: separation and rank deficiency with hundreds of groups." + - "A softmax per chosen candidate: biased, as measured." +affected_files: + - Sources/BusinessMath/Statistics/GroupedRanking/GroupedChoiceData.swift + - Sources/BusinessMath/Statistics/GroupedRanking/GroupedChoiceModel.swift + - Sources/BusinessMath/Statistics/GroupedRanking/GroupedChoiceFit.swift + - Sources/BusinessMath/Statistics/GroupedRanking/GroupRankingMetrics.swift + - Sources/BusinessMath/Statistics/GroupedRanking/GroupResampling.swift + - Sources/BusinessMath/Statistics/GroupedRanking/GroupedCrossValidation.swift + - Sources/BusinessMath/Statistics/GroupedRanking/HeldOutComparison.swift + - Sources/BusinessMath/Statistics/Regression/LogisticRegression+Penalty.swift + - Sources/BusinessMath/Statistics/Regression/LogisticRegression.swift + - Sources/BusinessMath/BusinessMath.docc/2.8-GroupedRanking.md + - Tests/BusinessMathTests/Grouped Ranking Tests/ + - Tests/BusinessMathTests/Regression Tests/PenalisedLogisticRegressionTests.swift +supersedes: null +amends: null +superseded_by: null +``` diff --git a/project/master_plan.md b/project/master_plan.md index 8e2242f6..36095796 100644 --- a/project/master_plan.md +++ b/project/master_plan.md @@ -38,6 +38,17 @@ suite depends on it. ## Current Status +**Unreleased (2026-11-21) — `Statistics/GroupedRanking` and a penalised `LogisticRegression.fit`**, built and merged to `main` +as phases B1 to B6 of `project/plans/proposals/BusinessMathGroupedRanking.md` (ADR-011), documented in B7 (the DocC article +`2.8-GroupedRanking`). A generic toolkit for fitting what predicts a choice **within** each group: the conditional-logit +(subset) and Plackett-Luce (ranking) likelihoods over `GroupedChoiceData` (dense or sparse, optional fixed offsets), a +prior-centred penalty on each weight's relative change with non-negativity, per-group ranking metrics, a bootstrap over groups, +grouped and nested k-fold, and `HeldOutComparison`; and `LogisticRegression.fit(penalty:)`, a ridge-type fit that returns a +result where the unpenalised fit refuses separated data. Additive; no existing symbol changes. No release tag yet (the owner +decides). Pending: the MCP tools (phase D, in businessMathMCP) and ClassGraph's migration onto this toolkit (phase C, in +ClassGraph). This section's own older entries stop at alpha.11 and have not been reconciled with alpha.12 to alpha.17; that +drift is recorded, not repaired here. + **3.0.0-alpha.11 shipped 2026-10-04** — twenty-two divisions a wider `fp-division-unguarded` reads (a divisor followed back through `let d = Double(n)`, and a `Double` parameter as a divisor in its own right). Eighteen were already safe and now carry the bound where the division is. @@ -817,7 +828,7 @@ The earlier table was about *scope*; this one is about *what is being measured*. --- -**Last Updated:** 2026-11-14 — tagged v3.0.0-alpha.17: the CHANGELOG's `[Unreleased]` block (weighted graphs and the graph measures in the Network module, steps 0 to 4 of `project/plans/upcoming/NetworkWeightedGraph.md`, ADR-006 to ADR-010, plus the by-component eigenvector) became the release; the README notice and install line name it. Two existing functions change their answers (`Graph.eigenvectorCentrality`, `Graph.louvainCommunities`); the new API is additive. Network is now shipped, so the plan is complete apart from the follow-ups recorded in ADR-010. +**Last Updated:** 2026-11-21 — reconciled the grouped-ranking toolkit and the penalised `LogisticRegression.fit` (phases B1 to B7, ADR-011) into Current Status; no release tag. Previous note: 2026-11-14, tagged v3.0.0-alpha.17 (weighted graphs and the graph measures in the Network module, ADR-006 to ADR-010). **Previously, 2026-11-13 — reconciled for step 4 of `project/plans/upcoming/NetworkWeightedGraph.md` (ADR-009): the weighted-graph plan's Status now reads steps 0 to 4 done, and its section 6 no longer says the silent behaviours close in step 5. Nothing in Current Status advanced (the weighted graph is on its feature branch, not released). diff --git a/project/plans/proposals/BusinessMathGroupedRanking.md b/project/plans/proposals/BusinessMathGroupedRanking.md index ffa10c0f..3f46f18d 100644 --- a/project/plans/proposals/BusinessMathGroupedRanking.md +++ b/project/plans/proposals/BusinessMathGroupedRanking.md @@ -1,6 +1,6 @@ # Design Proposal: `Statistics/GroupedRanking` — conditional logit, Plackett-Luce, a prior-centred penalty (also on `LogisticRegression`), per-group ranking metrics, group bootstrap, grouped cross-validation and a held-out comparison -**Status:** Proposed 2026-11-21. Owner decisions of 2026-11-21 are built in (section 16a). Nothing is built in BusinessMath; no BusinessMath file other than this one was touched. This is the BusinessMath-side proposal derived from ClassGraph's draft of the same name (ClassGraph branch `bm-grouped-ranking-proposal`, commit `8c01683`, which stays there as history). +**Status:** BUILT 2026-11-21 (phases B1 to B7); ADR-011 accepted. Phases C (ClassGraph migration) and D (MCP tools, in businessMathMCP) are pending. No release tag: the owner decides. Owner decisions of 2026-11-21 are built in (section 16a); the deviations from this proposal that the build made are recorded in ADR-011. This is the BusinessMath-side proposal derived from ClassGraph's draft of the same name (ClassGraph branch `bm-grouped-ranking-proposal`, commit `8c01683`, which stays there as history). **Master Plan Reference:** `project/master_plan.md` (Statistics area); the portfolio principle that generic machinery lives here and what is specific to a consumer stays there (ClassGraph ADR-014 moved its generic graph metrics here, ADR-010 here took the eigenvector-by-component measure); new **ADR-011** (ADR-010 is the last in `project/decisions/architecture_decisions.md`, checked 2026-11-21). **Source:** ClassGraph `Sources/ClassGraphCore/Backtest/` at `main` c81c833 (7 files, about 2,100 lines: a conditional-logit fitter, a per-group ranking evaluator, a group bootstrap and a nested grouped 5-fold, and `BacktestRandom`, a copy of SplitMix64), its ADR-022 and `YearbookMentionGraph.md` Amendment A. Read only; nothing is copied until phase B1. **Upstream check (done 2026-11-21):** BusinessMath is at `v3.0.0-alpha.17` (`main`, release commit `99de37f5`). ClassGraph pins revision `ae06466`, which is 4 commits behind; those commits touch only `Sources/BusinessMath/Network` (4 files, +416 lines). Nothing in `Statistics` changed, so none of what follows exists upstream. WineTaster 4 pins `3.0.0-alpha.16` exactly and is unaffected until it chooses to move. @@ -32,7 +32,7 @@ Seven pieces, each separately useful and separately gated: **Why it belongs here.** - It is domain-neutral, which this library already values: `ClassifierEvaluation` documents that it lives in `Statistics/` and not under marketing because a response model, a credit scorecard and a churn model are the same object. A choice model over groups is likewise the same object in discrete-choice demand, search and recommendation ranking, offer selection, and any "which of these did they pick" data. - The consumer's own rule (its `Package.swift`, `shared_packages.md`) is that generic machinery is not hand-rolled in a consumer. The backtest breaks it twice: the statistics, and `BacktestRandom`, a copy of the SplitMix64 that SwiftDeterminism provides and this library re-exports. -- **It is easy to get subtly wrong, and the first version was.** The first likelihood was a softmax per chosen item; ClassGraph's build agent measured a scale bias of about 40 percent on a synthetic class generated from the intended model (a measurement from that build, not re-measured for this proposal) and replaced it with the exact conditional likelihood. A library with a recovery test that fails the softmax is where that lesson should live. +- **It is easy to get subtly wrong, and the first version was.** The first likelihood was a softmax per chosen item; ClassGraph's build agent measured a scale bias of about 40 percent on a synthetic class generated from the intended model (ClassGraph's record says the softmax *overstates* the weight; **that direction was wrong**: the B2 recovery test fits a true weight of 1 at about 0.64, so the softmax *understates* it, a bias of about 36 percent. The size agrees; the direction is corrected here and in ADR-011) and replaced it with the exact conditional likelihood. A library with a recovery test that fails the softmax is where that lesson should live. - It closes a gap this library's own documentation states. `LogisticRegression` says the remedy for separation is Firth's penalised likelihood, "not implemented here". A penalised fit is the natural next step (section 3.9). ## 3. Proposed Architecture @@ -306,13 +306,13 @@ Split agreed; held-out comparison result type upstream, thresholds stay in Class | 0 | This proposal and ADR-011 (proposed) | BusinessMath | **owner approval**, section 17 | | M0a | Replace the hand-written pooled ROC area and the score-band table with `ClassifierEvaluation`; add `BusinessMath` as a `ClassGraphCore` dependency (ADR-022 note). **Built** on ClassGraph branch `backtest-businessmath` at `84f988b` (per its build report; I did not inspect the branch); calibration and gains were not swapped because their buckets do not match the score bands. Awaiting merge | ClassGraph | its gate passed 51/51 | | M0b | Replace `BacktestRandom` with SwiftDeterminism's `SplitMix64`; parity run and record both figures. **Not built.** Can wait for C | ClassGraph | gate 0/0; real-archive re-run, counts only | -| B1 | `GroupedChoiceData` (dense, and sparse per Q4) and the **subset** likelihood with gradient, unpenalised evaluation only; brute-force and finite-difference tests | BusinessMath | repo gate 0/0; mutation audit | -| B2 | The prior-centred penalty, non-negativity, scale step, `fit`; recovery (fails the softmax), null, talkative-group, penalty tests | BusinessMath | gate; mutation audit | -| B3 | Per-group metrics and the pooled helper | BusinessMath | gate; mutation audit | -| B4 | Group bootstrap, grouped and nested k-fold, `HeldOutComparison` | BusinessMath | gate; mutation audit; determinism across processes | -| B5 | Plackett-Luce (`likelihood: .ranking`), tests including "the two likelihoods differ" | BusinessMath | gate; mutation audit | -| B6 | Penalised `LogisticRegression.fit(penalty:)`; separation and rank-deficiency tests; the existing `fit` unchanged | BusinessMath | gate; mutation audit; existing tests untouched | -| B7 | DocC article, CHANGELOG, ADR-011 accepted, `master_plan.md`; a release tag only on the owner's decision (Open Question 5) | BusinessMath | gate 0/0 | +| B1 | `GroupedChoiceData` (dense, and sparse per Q4) and the **subset** likelihood with gradient, unpenalised evaluation only; brute-force and finite-difference tests | BusinessMath | repo gate 0/0; mutation audit **Built** `6a828ae4`; mutation 21 of 22. | +| B2 | The prior-centred penalty, non-negativity, scale step, `fit`; recovery (fails the softmax), null, talkative-group, penalty tests | BusinessMath | gate; mutation audit **Built** `78ce5d88`; mutation 10 of 15 (the rest equivalent, optimiser-path or unreached). | +| B3 | Per-group metrics and the pooled helper | BusinessMath | gate; mutation audit **Built** `f4d7895b`; mutation 11 of 11. | +| B4 | Group bootstrap, grouped and nested k-fold, `HeldOutComparison` | BusinessMath | gate; mutation audit; determinism across processes **Built** `05abf47b`; mutation 18 of 19. | +| B5 | Plackett-Luce (`likelihood: .ranking`), tests including "the two likelihoods differ" | BusinessMath | gate; mutation audit **Built** `a7097fc9`; mutation 11 of 11. | +| B6 | Penalised `LogisticRegression.fit(penalty:)`; separation and rank-deficiency tests; the existing `fit` unchanged | BusinessMath | gate; mutation audit; existing tests untouched **Built** `ca9ff4ea`, `7527f049`, `c1b1cc0d`, merged as `274c72a8`; mutation 22 of 25 applicable. | +| B7 | DocC article, CHANGELOG, ADR-011 accepted, `master_plan.md`; a release tag only on the owner's decision (Open Question 5) | BusinessMath | gate 0/0 **Built** (branch `feature/grouped-ranking-docs`): DocC article 2.8, ADR-011 accepted, CHANGELOG and master plan reconciled, no tag. | | C | Bump ClassGraph's pin; parity test (new toolkit versus the private code on a fixed-seed class); delete `BacktestFitter`, the metrics, `BacktestRandom`, the bootstrap and fold code; ADR-022 amendment | ClassGraph | gate 0/0; real-archive re-run reproduces the recorded figures within the stated tolerance | | D | The MCP tools (section 5), after B7, in `businessMathMCP` under its own proposal and process, pinning this library | businessMathMCP | that repository's gate | @@ -363,7 +363,7 @@ Process: merges only on the owner's explicit approval after `git branch --show-c ### Honest limits of this proposal - No BusinessMath code was written or run; the API in section 4 is a sketch, and names are proposals. - ClassGraph's M0a branch (`backtest-businessmath`, `84f988b`) is described from its build report, not inspected; M0b's generator swap is not built. -- The "about 40 percent" softmax scale bias is the ClassGraph build agent's measurement on a synthetic class, recorded in its ADR-022; it was not re-measured here. +- The "about 40 percent" softmax scale bias is the ClassGraph build agent's measurement on a synthetic class, recorded in its ADR-022. The B2 recovery test re-measured it in this repository: a true weight of 1 fitted at about 0.64, so the softmax **understates** (ClassGraph's ADR-022 says "overstates" and needs the same correction there). - Whether ClassGraph's `BacktestRandom` is bit-identical to SwiftDeterminism's `SplitMix64` was not checked. - That the penalised `LogisticRegression` path can skip the separation and rank-deficiency checks safely was reasoned from the objective's convexity, not by reading every line of `fit`; B6's first tests settle it. - WineTaster was read at its README, `Package.swift` and `BusinessMathBridge.swift` only. From a04eecbbb85a627920ec02ead5380ab45e94e81a Mon Sep 17 00:00:00 2001 From: Justin Purnell Date: Sat, 21 Nov 2026 18:00:34 -0500 Subject: [PATCH 13/13] release: 3.0.0-alpha.18 The grouped-ranking toolkit (Statistics/GroupedRanking) and a penalised LogisticRegression.fit. Additive, source-compatible. CHANGELOG moved from Unreleased; README notice and install line, and master plan Current Status (alpha.12 to alpha.18) reconciled. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_017dtpLZ6XGCJVmSqc1u4qUt --- CHANGELOG.md | 10 +++++ README.md | 11 ++--- .../GroupedRankingDocumentationTests.swift | 4 +- project/master_plan.md | 41 ++++++++++++++----- 4 files changed, 49 insertions(+), 17 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index bd9dea06..a1921168 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,16 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### [Unreleased] +### [3.0.0-alpha.18] - 2026-11-21 + +Additive: no existing API changes. (`LogisticRegression.validatedDesign` gains a defaulted parameter that leaves the unpenalised path as it was.) + +**A grouped-ranking toolkit and a penalised `LogisticRegression.fit`.** New in `Statistics/GroupedRanking`: the conditional-logit (subset) and +Plackett-Luce (ranking) likelihoods over grouped candidates, a prior-centred penalty with non-negativity, per-group ranking metrics, a bootstrap +over groups, grouped and nested k-fold, and `HeldOutComparison`; and `LogisticRegression.fit(penalty:)`, which fits data the unpenalised fit refuses +as separated. Source-compatible for everyone on alpha.17. Documented in the DocC article `2.8-GroupedRanking` and ADR-011. The entries below say +exactly what each part does. + **Grouped-ranking toolkit (`Statistics/GroupedRanking`), phases B1 to B5 of `project/plans/proposals/BusinessMathGroupedRanking.md`.** All additive; no existing symbol changes. `GroupedChoiceData` (dense or sparse candidates grouped by chooser, with optional fixed per-candidate offsets, or ranked groups), `GroupedChoiceModel` (the exact conditional-logit likelihood for an unordered chosen set, and the Plackett-Luce likelihood for ordered diff --git a/README.md b/README.md index d94fb796..ef9c2ce0 100644 --- a/README.md +++ b/README.md @@ -11,12 +11,12 @@ Build DCF models, optimize portfolios, run Monte Carlo simulations, and value se --- -## Pre-release: 3.0.0-alpha.17 +## Pre-release: 3.0.0-alpha.18 **The breaking set shipped first, in alpha.1 and alpha.2** — the items that had been waiting for a major since August. Everything since has been correctness work and one protocol requirement. **alpha.8 is source-breaking again**, in a handful of signatures listed below; -alpha.9 through alpha.17 are source-compatible; alpha.11 changes four *answers*, alpha.12 +alpha.9 through alpha.18 are source-compatible; alpha.11 changes four *answers*, alpha.12 adds a validating form of one optimiser and bounds its table, alpha.13 adds `ConcordanceResult.friedmanCorrected` and changes what an all-tied panel answers (`nan`, as in SciPy and R, where it was a χ² of 0 and p = 1), and alpha.14 adds exact, tie-aware rank-sum @@ -26,7 +26,8 @@ tie-aware Spearman critical values and p-values (`spearmanDistribution`, `spearm `spearmanTest`), and alpha.17 adds weighted graphs and graph measures to the Network module (`WeightedGraph`, weighted centrality, community and brokerage measures, diffusion, seed selection, siting, a metric registry) and changes the answers of two existing functions, `Graph.eigenvectorCentrality` (correct on bipartite graphs; `nil` when not converged within `maxIterations`) and -`Graph.louvainCommunities` (now contracts communities). +`Graph.louvainCommunities` (now contracts communities), and alpha.18 adds a grouped-ranking toolkit (`Statistics/GroupedRanking`: conditional-logit and Plackett-Luce likelihoods, a prior-centred +penalty, per-group ranking metrics, a group bootstrap, grouped and nested k-fold, `HeldOutComparison`) and a penalised `LogisticRegression.fit(penalty:)`. This notice said until 2026-10-09 that alpha.8 through alpha.11 "add no API at all" and that what breaks "has not moved since alpha.7". Neither was true of alpha.8, and a consumer pinned @@ -36,7 +37,7 @@ at alpha.7 found out by failing to compile: see *What alpha.8 breaks* below. `from: "2.7.0"` you stay on 2.18.0 and nothing changes. To try the alpha, ask for it by name: ```swift -.package(url: "https://github.com/jpurnell/BusinessMath.git", exact: "3.0.0-alpha.17") +.package(url: "https://github.com/jpurnell/BusinessMath.git", exact: "3.0.0-alpha.18") ``` What breaks: @@ -81,7 +82,7 @@ zero, and `EOQModel` overflowed to a non-finite order quantity with no error. It `ModifiedZScoreAnomalyDetector` and `IQRAnomalyDetector`, and a `seed:` on `runFinancialSimulation`. -**alpha.8 is source-breaking; alpha.9 through alpha.17 are not.** alpha.8 closes the +**alpha.8 is source-breaking; alpha.9 through alpha.18 are not.** alpha.8 closes the contaminated-input campaign: ~1,200 sites read, ~215 real defects and 6 hard crashes, in 32 commits, against one class — *a guard that is correct while the value it returns is a claim landing at the favourable end of a scale the caller reads.* The principle it produced: diff --git a/Tests/BusinessMathTests/Grouped Ranking Tests/GroupedRankingDocumentationTests.swift b/Tests/BusinessMathTests/Grouped Ranking Tests/GroupedRankingDocumentationTests.swift index 11909279..1175dc6e 100644 --- a/Tests/BusinessMathTests/Grouped Ranking Tests/GroupedRankingDocumentationTests.swift +++ b/Tests/BusinessMathTests/Grouped Ranking Tests/GroupedRankingDocumentationTests.swift @@ -81,7 +81,9 @@ struct GroupedRankingDocumentationTests { (candidates: [[1, 1], [0, 0], [1, 0]], ranking: [0, 2]), (candidates: [[0, 1], [1, 0], [0, 0]], ranking: [1]), ])) - #expect(GroupedChoiceModel(data: ranked, reference: [1, 1], likelihood: .ranking) != nil) + let rankingModel = try #require(GroupedChoiceModel(data: ranked, reference: [1, 1], likelihood: .ranking)) + #expect(rankingModel.likelihood == .ranking) + #expect(rankingModel.reference == [1, 1]) #expect(GroupedChoiceModel(data: ranked, reference: [1, 1], likelihood: .subset) == nil) } diff --git a/project/master_plan.md b/project/master_plan.md index 36095796..4c20620e 100644 --- a/project/master_plan.md +++ b/project/master_plan.md @@ -38,16 +38,35 @@ suite depends on it. ## Current Status -**Unreleased (2026-11-21) — `Statistics/GroupedRanking` and a penalised `LogisticRegression.fit`**, built and merged to `main` -as phases B1 to B6 of `project/plans/proposals/BusinessMathGroupedRanking.md` (ADR-011), documented in B7 (the DocC article -`2.8-GroupedRanking`). A generic toolkit for fitting what predicts a choice **within** each group: the conditional-logit -(subset) and Plackett-Luce (ranking) likelihoods over `GroupedChoiceData` (dense or sparse, optional fixed offsets), a -prior-centred penalty on each weight's relative change with non-negativity, per-group ranking metrics, a bootstrap over groups, -grouped and nested k-fold, and `HeldOutComparison`; and `LogisticRegression.fit(penalty:)`, a ridge-type fit that returns a -result where the unpenalised fit refuses separated data. Additive; no existing symbol changes. No release tag yet (the owner -decides). Pending: the MCP tools (phase D, in businessMathMCP) and ClassGraph's migration onto this toolkit (phase C, in -ClassGraph). This section's own older entries stop at alpha.11 and have not been reconciled with alpha.12 to alpha.17; that -drift is recorded, not repaired here. +**3.0.0-alpha.18 (2026-11-21; tag pending the owner after the release PR merges) — `Statistics/GroupedRanking` and a penalised +`LogisticRegression.fit`**, built as phases B1 to B7 of `project/plans/proposals/BusinessMathGroupedRanking.md` (ADR-011), documented in the DocC +article `2.8-GroupedRanking`. A generic toolkit for fitting what predicts a choice **within** each group: the conditional-logit (subset) and +Plackett-Luce (ranking) likelihoods over `GroupedChoiceData` (dense or sparse, optional fixed offsets), a prior-centred penalty on each +weight's relative change with non-negativity, per-group ranking metrics, a bootstrap over groups, grouped and nested k-fold, and +`HeldOutComparison`; and `LogisticRegression.fit(penalty:)`, a ridge-type fit that returns a result where the unpenalised fit refuses separated +data. Additive; no existing symbol changes. Pending: the MCP tools (phase D, in businessMathMCP) and ClassGraph's migration onto this toolkit +(phase C, in ClassGraph). + +**3.0.0-alpha.17 shipped 2026-11-14** — the Network module gains weighted graphs and the graph measures that lived in the ClassGraph package +(`WeightedGraph`, weighted centrality, community and brokerage measures, diffusion, seed selection, p-median siting, a metric registry with a +stored-record envelope; ADR-006 to ADR-010, plan `project/plans/upcoming/NetworkWeightedGraph.md`). Two existing functions change their answers: +`Graph.eigenvectorCentrality` is correct on bipartite graphs and returns `nil` when not converged within `maxIterations`, and +`Graph.louvainCommunities` contracts communities between passes. Signatures unchanged. + +**3.0.0-alpha.16 shipped 2026-11-13** — exact, tie-aware Spearman's rho: `spearmanDistribution`, `spearmanCriticalValues`, `spearmanTest`, checked +against brute force, an independent exact programme, R, SciPy, Monte Carlo and Zar's table. Additive. + +**3.0.0-alpha.15 shipped 2026-11-12** — `wilsonInterval`, `medianAbsoluteDeviation` and `poissonSurvival` for the Diagnostics Hub's analysis +slice, checked against R and SciPy, plus an assessment of the library's anomaly detectors against the hub's spike rule. Additive. + +**3.0.0-alpha.14 shipped 2026-11-12** — exact, tie-aware rank-sum distribution and critical values (`rankSumDistribution`, +`rankSumCriticalValues`), checked against brute force, exact Python integers, NumPy, R and Monte Carlo. Additive. + +**3.0.0-alpha.13 shipped 2026-11-11** — tie-corrected concordance checked against SciPy and R, `ConcordanceResult.friedmanCorrected`; an all-tied +panel now answers `nan`; SABR ATM and `SimulatedAnnealing` guards. + +**3.0.0-alpha.12 shipped 2026-10-10** — a security fix: `CapitalAllocationOptimizer.optimizeIntegerProjects` sized a table from caller-supplied +numbers and could end the process; the validating form `optimizeIntegerProjects(validating:budget:)` bounds it (see the CHANGELOG entry). **3.0.0-alpha.11 shipped 2026-10-04** — twenty-two divisions a wider `fp-division-unguarded` reads (a divisor followed back through `let d = Double(n)`, and a `Double` parameter as a divisor @@ -828,7 +847,7 @@ The earlier table was about *scope*; this one is about *what is being measured*. --- -**Last Updated:** 2026-11-21 — reconciled the grouped-ranking toolkit and the penalised `LogisticRegression.fit` (phases B1 to B7, ADR-011) into Current Status; no release tag. Previous note: 2026-11-14, tagged v3.0.0-alpha.17 (weighted graphs and the graph measures in the Network module, ADR-006 to ADR-010). +**Last Updated:** 2026-11-21 — prepared release 3.0.0-alpha.18 (tag pending): the grouped-ranking toolkit and the penalised `LogisticRegression.fit` (phases B1 to B7, ADR-011) moved from Unreleased in the CHANGELOG; Current Status now carries alpha.12 to alpha.18, reconciled against the CHANGELOG headlines (they had stopped at alpha.11; that drift is repaired here); the Roadmap and Priorities tables list no item that these releases shipped, so none moved; README notice and install line name alpha.18. Previous note: 2026-11-14, tagged v3.0.0-alpha.17 (weighted graphs and the graph measures in the Network module, ADR-006 to ADR-010). **Previously, 2026-11-13 — reconciled for step 4 of `project/plans/upcoming/NetworkWeightedGraph.md` (ADR-009): the weighted-graph plan's Status now reads steps 0 to 4 done, and its section 6 no longer says the silent behaviours close in step 5. Nothing in Current Status advanced (the weighted graph is on its feature branch, not released).