@mailwoman/entity-resolution 0.0.0-stage → 11.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +114 -2
- package/lib/address-key.ts +46 -0
- package/lib/geocode-handler.ts +37 -0
- package/lib/geojson.ts +72 -0
- package/lib/index.ts +23 -0
- package/lib/ingest.ts +349 -0
- package/lib/learned-scorer.ts +134 -0
- package/lib/map-html.ts +287 -0
- package/lib/models/crosssource-gbt-en-us.ts +43 -0
- package/lib/models/dedup-gbt-en-us.ts +47 -0
- package/lib/models/org-crosssource-gbt-en-us.ts +43 -0
- package/lib/reconcile.ts +239 -0
- package/lib/resolve.ts +569 -0
- package/lib/types.ts +110 -0
- package/out/address-key.d.ts +34 -0
- package/out/address-key.d.ts.map +1 -0
- package/out/address-key.js +41 -0
- package/out/address-key.js.map +1 -0
- package/out/geocode-handler.d.ts +20 -0
- package/out/geocode-handler.d.ts.map +1 -0
- package/out/geocode-handler.js +29 -0
- package/out/geocode-handler.js.map +1 -0
- package/out/geojson.d.ts +28 -0
- package/out/geojson.d.ts.map +1 -0
- package/out/geojson.js +62 -0
- package/out/geojson.js.map +1 -0
- package/out/index.d.ts +23 -0
- package/out/index.d.ts.map +1 -0
- package/out/index.js +23 -0
- package/out/index.js.map +1 -0
- package/out/ingest.d.ts +173 -0
- package/out/ingest.d.ts.map +1 -0
- package/out/ingest.js +185 -0
- package/out/ingest.js.map +1 -0
- package/out/learned-scorer.d.ts +61 -0
- package/out/learned-scorer.d.ts.map +1 -0
- package/out/learned-scorer.js +91 -0
- package/out/learned-scorer.js.map +1 -0
- package/out/map-html.d.ts +39 -0
- package/out/map-html.d.ts.map +1 -0
- package/out/map-html.js +220 -0
- package/out/map-html.js.map +1 -0
- package/out/models/crosssource-gbt-en-us.d.ts +45 -0
- package/out/models/crosssource-gbt-en-us.d.ts.map +1 -0
- package/out/models/crosssource-gbt-en-us.js +40 -0
- package/out/models/crosssource-gbt-en-us.js.map +1 -0
- package/out/models/dedup-gbt-en-us.d.ts +44 -0
- package/out/models/dedup-gbt-en-us.d.ts.map +1 -0
- package/out/models/dedup-gbt-en-us.js +44 -0
- package/out/models/dedup-gbt-en-us.js.map +1 -0
- package/out/models/org-crosssource-gbt-en-us.d.ts +45 -0
- package/out/models/org-crosssource-gbt-en-us.d.ts.map +1 -0
- package/out/models/org-crosssource-gbt-en-us.js +40 -0
- package/out/models/org-crosssource-gbt-en-us.js.map +1 -0
- package/out/reconcile.d.ts +96 -0
- package/out/reconcile.d.ts.map +1 -0
- package/out/reconcile.js +127 -0
- package/out/reconcile.js.map +1 -0
- package/out/resolve.d.ts +264 -0
- package/out/resolve.d.ts.map +1 -0
- package/out/resolve.js +282 -0
- package/out/resolve.js.map +1 -0
- package/out/tools/coverage-reconciliation.d.ts +67 -0
- package/out/tools/coverage-reconciliation.d.ts.map +1 -0
- package/out/tools/coverage-reconciliation.js +113 -0
- package/out/tools/coverage-reconciliation.js.map +1 -0
- package/out/tools/cross/dataset-correlation.d.ts +61 -0
- package/out/tools/cross/dataset-correlation.d.ts.map +1 -0
- package/out/tools/cross/dataset-correlation.js +244 -0
- package/out/tools/cross/dataset-correlation.js.map +1 -0
- package/out/tools/cross/source-threshold-sweep.d.ts +60 -0
- package/out/tools/cross/source-threshold-sweep.d.ts.map +1 -0
- package/out/tools/cross/source-threshold-sweep.js +264 -0
- package/out/tools/cross/source-threshold-sweep.js.map +1 -0
- package/out/tools/dedup-ceiling.d.ts +62 -0
- package/out/tools/dedup-ceiling.d.ts.map +1 -0
- package/out/tools/dedup-ceiling.js +171 -0
- package/out/tools/dedup-ceiling.js.map +1 -0
- package/out/tools/eval-geocoder.d.ts +68 -0
- package/out/tools/eval-geocoder.d.ts.map +1 -0
- package/out/tools/eval-geocoder.js +13 -0
- package/out/tools/eval-geocoder.js.map +1 -0
- package/out/tools/geocoder/namesake-probe.d.ts +33 -0
- package/out/tools/geocoder/namesake-probe.d.ts.map +1 -0
- package/out/tools/geocoder/namesake-probe.js +60 -0
- package/out/tools/geocoder/namesake-probe.js.map +1 -0
- package/out/tools/geocoder/vs-provided-coords.d.ts +53 -0
- package/out/tools/geocoder/vs-provided-coords.d.ts.map +1 -0
- package/out/tools/geocoder/vs-provided-coords.js +161 -0
- package/out/tools/geocoder/vs-provided-coords.js.map +1 -0
- package/out/tools/gold-set-sample.d.ts +67 -0
- package/out/tools/gold-set-sample.d.ts.map +1 -0
- package/out/tools/gold-set-sample.js +81 -0
- package/out/tools/gold-set-sample.js.map +1 -0
- package/out/tools/learned/scorer/clustering-eval.d.ts +77 -0
- package/out/tools/learned/scorer/clustering-eval.d.ts.map +1 -0
- package/out/tools/learned/scorer/clustering-eval.js +207 -0
- package/out/tools/learned/scorer/clustering-eval.js.map +1 -0
- package/out/tools/learned/scorer/crossstate-eval.d.ts +65 -0
- package/out/tools/learned/scorer/crossstate-eval.d.ts.map +1 -0
- package/out/tools/learned/scorer/crossstate-eval.js +168 -0
- package/out/tools/learned/scorer/crossstate-eval.js.map +1 -0
- package/out/tools/learned/scorer/eval.d.ts +64 -0
- package/out/tools/learned/scorer/eval.d.ts.map +1 -0
- package/out/tools/learned/scorer/eval.js +275 -0
- package/out/tools/learned/scorer/eval.js.map +1 -0
- package/out/tools/matcher-scale.d.ts +40 -0
- package/out/tools/matcher-scale.d.ts.map +1 -0
- package/out/tools/matcher-scale.js +111 -0
- package/out/tools/matcher-scale.js.map +1 -0
- package/out/tools/nppes/dedup-benchmark.d.ts +82 -0
- package/out/tools/nppes/dedup-benchmark.d.ts.map +1 -0
- package/out/tools/nppes/dedup-benchmark.js +226 -0
- package/out/tools/nppes/dedup-benchmark.js.map +1 -0
- package/out/tools/nppes/org-name.d.ts +15 -0
- package/out/tools/nppes/org-name.d.ts.map +1 -0
- package/out/tools/nppes/org-name.js +6 -0
- package/out/tools/nppes/org-name.js.map +1 -0
- package/out/tools/nppes/overmerge-packet.d.ts +43 -0
- package/out/tools/nppes/overmerge-packet.d.ts.map +1 -0
- package/out/tools/nppes/overmerge-packet.js +54 -0
- package/out/tools/nppes/overmerge-packet.js.map +1 -0
- package/out/tools/nppes/report.d.ts +97 -0
- package/out/tools/nppes/report.d.ts.map +1 -0
- package/out/tools/nppes/report.js +178 -0
- package/out/tools/nppes/report.js.map +1 -0
- package/out/tools/nppes/sample.d.ts +101 -0
- package/out/tools/nppes/sample.d.ts.map +1 -0
- package/out/tools/nppes/sample.js +127 -0
- package/out/tools/nppes/sample.js.map +1 -0
- package/out/tools/nppes/scoring.d.ts +37 -0
- package/out/tools/nppes/scoring.d.ts.map +1 -0
- package/out/tools/nppes/scoring.js +81 -0
- package/out/tools/nppes/scoring.js.map +1 -0
- package/out/tools/nppes/settings.d.ts +41 -0
- package/out/tools/nppes/settings.d.ts.map +1 -0
- package/out/tools/nppes/settings.js +79 -0
- package/out/tools/nppes/settings.js.map +1 -0
- package/out/tools/nppes/truth-grains.d.ts +63 -0
- package/out/tools/nppes/truth-grains.d.ts.map +1 -0
- package/out/tools/nppes/truth-grains.js +142 -0
- package/out/tools/nppes/truth-grains.js.map +1 -0
- package/out/tools/shared.d.ts +325 -0
- package/out/tools/shared.d.ts.map +1 -0
- package/out/tools/shared.js +453 -0
- package/out/tools/shared.js.map +1 -0
- package/out/tools/train/cross-gbt.d.ts +89 -0
- package/out/tools/train/cross-gbt.d.ts.map +1 -0
- package/out/tools/train/cross-gbt.js +132 -0
- package/out/tools/train/cross-gbt.js.map +1 -0
- package/out/tools/train/gbt.d.ts +85 -0
- package/out/tools/train/gbt.d.ts.map +1 -0
- package/out/tools/train/gbt.js +155 -0
- package/out/tools/train/gbt.js.map +1 -0
- package/out/tools/train/org-cross-gbt.d.ts +85 -0
- package/out/tools/train/org-cross-gbt.d.ts.map +1 -0
- package/out/tools/train/org-cross-gbt.js +122 -0
- package/out/tools/train/org-cross-gbt.js.map +1 -0
- package/out/tools/txhhsc-to-oarow.d.ts +42 -0
- package/out/tools/txhhsc-to-oarow.d.ts.map +1 -0
- package/out/tools/txhhsc-to-oarow.js +78 -0
- package/out/tools/txhhsc-to-oarow.js.map +1 -0
- package/out/tools/viz/browser.d.ts +31 -0
- package/out/tools/viz/browser.d.ts.map +1 -0
- package/out/tools/viz/browser.js +26 -0
- package/out/tools/viz/browser.js.map +1 -0
- package/out/tools/viz/cross-dataset-map.d.ts +39 -0
- package/out/tools/viz/cross-dataset-map.d.ts.map +1 -0
- package/out/tools/viz/cross-dataset-map.js +84 -0
- package/out/tools/viz/cross-dataset-map.js.map +1 -0
- package/out/tools/viz/geocode-first-surface.d.ts +36 -0
- package/out/tools/viz/geocode-first-surface.d.ts.map +1 -0
- package/out/tools/viz/geocode-first-surface.js +234 -0
- package/out/tools/viz/geocode-first-surface.js.map +1 -0
- package/out/tools/viz/render/map.d.ts +42 -0
- package/out/tools/viz/render/map.d.ts.map +1 -0
- package/out/tools/viz/render/map.js +40 -0
- package/out/tools/viz/render/map.js.map +1 -0
- package/out/tools/viz/render.d.ts +46 -0
- package/out/tools/viz/render.d.ts.map +1 -0
- package/out/tools/viz/render.js +49 -0
- package/out/tools/viz/render.js.map +1 -0
- package/out/tools/viz/source-provenance-map.d.ts +57 -0
- package/out/tools/viz/source-provenance-map.d.ts.map +1 -0
- package/out/tools/viz/source-provenance-map.js +82 -0
- package/out/tools/viz/source-provenance-map.js.map +1 -0
- package/out/tools/viz/yardstick-figure.d.ts +22 -0
- package/out/tools/viz/yardstick-figure.d.ts.map +1 -0
- package/out/tools/viz/yardstick-figure.js +106 -0
- package/out/tools/viz/yardstick-figure.js.map +1 -0
- package/out/types.d.ts +108 -0
- package/out/types.d.ts.map +1 -0
- package/out/types.js +11 -0
- package/out/types.js.map +1 -0
- package/package.json +113 -3
- package/tools/coverage-reconciliation.ts +192 -0
- package/tools/cross/dataset-correlation.ts +380 -0
- package/tools/cross/source-threshold-sweep.ts +416 -0
- package/tools/dedup-ceiling.ts +225 -0
- package/tools/eval-geocoder.ts +77 -0
- package/tools/geocoder/namesake-probe.ts +91 -0
- package/tools/geocoder/vs-provided-coords.ts +232 -0
- package/tools/gold-set-sample.ts +147 -0
- package/tools/learned/scorer/clustering-eval.ts +349 -0
- package/tools/learned/scorer/crossstate-eval.ts +280 -0
- package/tools/learned/scorer/eval.ts +429 -0
- package/tools/matcher-scale.ts +185 -0
- package/tools/nppes/dedup-benchmark.ts +364 -0
- package/tools/nppes/org-name.ts +15 -0
- package/tools/nppes/overmerge-packet.ts +98 -0
- package/tools/nppes/report.ts +380 -0
- package/tools/nppes/sample.ts +250 -0
- package/tools/nppes/scoring.ts +115 -0
- package/tools/nppes/settings.ts +102 -0
- package/tools/nppes/truth-grains.ts +185 -0
- package/tools/shared.ts +743 -0
- package/tools/train/cross-gbt.ts +214 -0
- package/tools/train/gbt.ts +261 -0
- package/tools/train/org-cross-gbt.ts +189 -0
- package/tools/txhhsc-to-oarow.ts +118 -0
- package/tools/viz/browser.ts +41 -0
- package/tools/viz/cross-dataset-map.ts +133 -0
- package/tools/viz/geocode-first-surface.ts +305 -0
- package/tools/viz/render/map.ts +61 -0
- package/tools/viz/render.ts +103 -0
- package/tools/viz/source-provenance-map.ts +154 -0
- package/tools/viz/yardstick-figure.ts +197 -0
package/tools/shared.ts
ADDED
|
@@ -0,0 +1,743 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @copyright Sister Software
|
|
3
|
+
* @license AGPL-3.0
|
|
4
|
+
* @author Teffen Ellis, et al.
|
|
5
|
+
*
|
|
6
|
+
* Shared helpers used by two or more probes in the `registry/tools` probe battery.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import { makeDirectories, writeLocalFile } from "@mailwoman/core/fs/writers"
|
|
10
|
+
import { stringifyJSON } from "@mailwoman/core/json"
|
|
11
|
+
import { isPresent } from "@mailwoman/core/objects"
|
|
12
|
+
import { makeLcg } from "@mailwoman/core/random"
|
|
13
|
+
import { block, gbtScore, trainGBT, type GBTOpts, type TermFrequencyTable } from "@mailwoman/match"
|
|
14
|
+
import { dirname } from "path-ts"
|
|
15
|
+
|
|
16
|
+
import {
|
|
17
|
+
addressFrequencyKey,
|
|
18
|
+
buildDefaultModel,
|
|
19
|
+
createMatchFeaturizer,
|
|
20
|
+
defaultBlockingKeys,
|
|
21
|
+
ingestRows,
|
|
22
|
+
normalizePhoneStrict,
|
|
23
|
+
streamRows,
|
|
24
|
+
type ColumnMapping,
|
|
25
|
+
type SourceRecord,
|
|
26
|
+
} from "#index"
|
|
27
|
+
import type { EvalGeocoderFactory } from "#tools/eval-geocoder"
|
|
28
|
+
import type { Score } from "#tools/nppes/scoring"
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* One source a cross-source probe ingests.
|
|
32
|
+
*
|
|
33
|
+
* Its spec gives the path and column mapping.
|
|
34
|
+
* The spec also provides an in-state filter.
|
|
35
|
+
*/
|
|
36
|
+
export interface SourceSpec {
|
|
37
|
+
source: string
|
|
38
|
+
path: string
|
|
39
|
+
mapping: ColumnMapping
|
|
40
|
+
/**
|
|
41
|
+
* Keep only rows in-state (reads the row's state column).
|
|
42
|
+
*/
|
|
43
|
+
inState: (row: Record<string, string>) => boolean
|
|
44
|
+
/**
|
|
45
|
+
* Optional: a row carrying ≥1 addressable entity yields each as its own row.
|
|
46
|
+
*
|
|
47
|
+
* @defaultValue identity.
|
|
48
|
+
*/
|
|
49
|
+
explode?: (row: Record<string, string>) => Record<string, string>[]
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Trim, treating `null` or `undefined` as empty — the shape every probe's raw CSV columns arrive in.
|
|
54
|
+
*/
|
|
55
|
+
export const norm = (s: string | null | undefined): string => (s ?? "").trim()
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Corporate-form suffixes and function words that add no identity — dropped from an organization name
|
|
59
|
+
* before its tokens are compared, so the domain words include the distinguishing signal.
|
|
60
|
+
*/
|
|
61
|
+
const ORGANIZATION_STOP_WORDS = new Set([
|
|
62
|
+
"llc",
|
|
63
|
+
"inc",
|
|
64
|
+
"incorporated",
|
|
65
|
+
"corp",
|
|
66
|
+
"corporation",
|
|
67
|
+
"co",
|
|
68
|
+
"ltd",
|
|
69
|
+
"pllc",
|
|
70
|
+
"pc",
|
|
71
|
+
"pa",
|
|
72
|
+
"lp",
|
|
73
|
+
"llp",
|
|
74
|
+
"the",
|
|
75
|
+
"of",
|
|
76
|
+
"and",
|
|
77
|
+
])
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* The token set of an organization name for the probes' cheap Jaccard overlap,
|
|
81
|
+
* never blocking or display — not a canonical form.
|
|
82
|
+
*/
|
|
83
|
+
export function orgTokens(s: string): Set<string> {
|
|
84
|
+
return new Set(
|
|
85
|
+
s
|
|
86
|
+
.toLowerCase()
|
|
87
|
+
.replaceAll(/[^a-z0-9 ]/g, " ")
|
|
88
|
+
.split(/\s+/)
|
|
89
|
+
.filter((t) => t && !ORGANIZATION_STOP_WORDS.has(t))
|
|
90
|
+
)
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* Join the four US address columns into one line, dropping blanks.
|
|
95
|
+
*/
|
|
96
|
+
export const addr = (line: string, city: string, st: string, zip: string): string =>
|
|
97
|
+
[norm(line), norm(city), norm(st), norm(zip)].filter(isPresent).join(", ")
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* Population standard deviation; `0` on an empty sample, because these feed
|
|
101
|
+
* report tables that print a number per row.
|
|
102
|
+
*/
|
|
103
|
+
export const std = (xs: readonly number[]): number => {
|
|
104
|
+
const m = xs.reduce((a, b) => a + b, 0) / Math.max(1, xs.length)
|
|
105
|
+
|
|
106
|
+
return Math.sqrt(xs.map((x) => (x - m) ** 2).reduce((a, b) => a + b, 0) / Math.max(1, xs.length))
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* Takes a fraction and omits the percent sign, unlike core `formatPercent`'s
|
|
111
|
+
* numerator/denominator interface.
|
|
112
|
+
* Call sites append their own `%`.
|
|
113
|
+
*/
|
|
114
|
+
export const pct = (x: number): string => (100 * x).toFixed(1)
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* Sign prefix for a signed delta: `"+"` for a non-negative value, since a negative one includes its sign.
|
|
118
|
+
*/
|
|
119
|
+
export const sgn = (x: number): string => (x >= 0 ? "+" : "")
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* Logistic function with the input clamped to ±30, past which `Math.exp` underflows to 0
|
|
123
|
+
* and the gradient step silently becomes a no-op.
|
|
124
|
+
*/
|
|
125
|
+
export const sigmoid = (z: number): number => 1 / (1 + Math.exp(-Math.max(-30, Math.min(30, z))))
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* The probes' shared `--state` option: upper-cased, defaulting to TX (the benchmark corpus state).
|
|
129
|
+
*/
|
|
130
|
+
export const stateOption = (options: { state?: string }): string => (options.state || "TX").toUpperCase()
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* Texas bounding box (generous) — the shared wrong-region test.
|
|
134
|
+
*/
|
|
135
|
+
export const TX_BBOX = { latMin: 25.8, latMax: 36.6, lonMin: -106.7, lonMax: -93.4 }
|
|
136
|
+
|
|
137
|
+
/**
|
|
138
|
+
* Whether a coordinate falls inside {@link TX_BBOX}.
|
|
139
|
+
*/
|
|
140
|
+
export const inTXBBOX = (lat: number, lon: number): boolean =>
|
|
141
|
+
lat >= TX_BBOX.latMin && lat <= TX_BBOX.latMax && lon >= TX_BBOX.lonMin && lon <= TX_BBOX.lonMax
|
|
142
|
+
|
|
143
|
+
/**
|
|
144
|
+
* NPPES registry column headers, by the short name the probes read them under. no code
|
|
145
|
+
* enumerates this object, so adding a column cannot change a probe's behavior.
|
|
146
|
+
*/
|
|
147
|
+
export const NPPES_COLUMNS = {
|
|
148
|
+
npi: "NPI",
|
|
149
|
+
entityType: "Entity Type Code",
|
|
150
|
+
orgLegal: "Provider Organization Name (Legal Business Name)",
|
|
151
|
+
last: "Provider Last Name (Legal Name)",
|
|
152
|
+
first: "Provider First Name",
|
|
153
|
+
pAddr: "Provider First Line Business Practice Location Address",
|
|
154
|
+
pCity: "Provider Business Practice Location Address City Name",
|
|
155
|
+
pState: "Provider Business Practice Location Address State Name",
|
|
156
|
+
pZip: "Provider Business Practice Location Address Postcode",
|
|
157
|
+
pPhone: "Provider Business Practice Location Address Telephone Number",
|
|
158
|
+
mAddr: "Provider First Line Business Mailing Address",
|
|
159
|
+
mCity: "Provider Business Mailing Address City Name",
|
|
160
|
+
mState: "Provider Business Mailing Address State Name",
|
|
161
|
+
mZip: "Provider Business Mailing Address Postcode",
|
|
162
|
+
otherOrg: "Provider Other Organization Name",
|
|
163
|
+
authLast: "Authorized Official Last Name",
|
|
164
|
+
authFirst: "Authorized Official First Name",
|
|
165
|
+
isSubpart: "Is Organization Subpart",
|
|
166
|
+
parentLBN: "Parent Organization LBN",
|
|
167
|
+
parentTIN: "Parent Organization TIN",
|
|
168
|
+
// The 15 taxonomy slots.
|
|
169
|
+
// Any shared code counts as agreement.
|
|
170
|
+
taxonomy: Array.from({ length: 15 }, (_, i) => `Healthcare Provider Taxonomy Code_${i + 1}`),
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/**
|
|
174
|
+
* Groups below this size are too small for a held-out split to mean anything.
|
|
175
|
+
*/
|
|
176
|
+
export const MIN_GROUP_SIZE = 5
|
|
177
|
+
|
|
178
|
+
/**
|
|
179
|
+
* Gradient-descent epochs for {@link trainLogisticRegression}, fixed
|
|
180
|
+
* rather than early-stopped so seeds stay comparable.
|
|
181
|
+
*/
|
|
182
|
+
export const TRAINING_EPOCHS = 400
|
|
183
|
+
|
|
184
|
+
/**
|
|
185
|
+
* Smallest mean F1 gap counted as a real difference between models rather than seed
|
|
186
|
+
* noise. verdicts inside ±this are reported as a tie.
|
|
187
|
+
*/
|
|
188
|
+
export const MIN_MEANINGFUL_F1_DELTA = 0.02
|
|
189
|
+
|
|
190
|
+
/**
|
|
191
|
+
* Batch-gradient-descent learning rate for {@link trainLogisticRegression}.
|
|
192
|
+
*/
|
|
193
|
+
export const LR_LEARNING_RATE = 0.1
|
|
194
|
+
|
|
195
|
+
/**
|
|
196
|
+
* L2 regularization strength for {@link trainLogisticRegression}.
|
|
197
|
+
*/
|
|
198
|
+
export const LR_L2 = 1e-3
|
|
199
|
+
|
|
200
|
+
/**
|
|
201
|
+
* L2-regularized logistic regression by batch gradient descent over {@link TRAINING_EPOCHS}
|
|
202
|
+
* epochs, where `w` stores per-sample class weights, returning the logit rather than
|
|
203
|
+
* the probability so it is threshold-comparable across a fixed feature layout.
|
|
204
|
+
*/
|
|
205
|
+
export function trainLogisticRegression(
|
|
206
|
+
X: readonly (readonly number[])[],
|
|
207
|
+
y: readonly number[],
|
|
208
|
+
w: readonly number[],
|
|
209
|
+
dim: number
|
|
210
|
+
): (x: readonly number[]) => number {
|
|
211
|
+
const weights = new Array<number>(dim).fill(0)
|
|
212
|
+
let bias = 0
|
|
213
|
+
|
|
214
|
+
for (let epoch = 0; epoch < TRAINING_EPOCHS; epoch++) {
|
|
215
|
+
const gw = new Array<number>(dim).fill(0)
|
|
216
|
+
let gb = 0
|
|
217
|
+
|
|
218
|
+
for (let i = 0; i < X.length; i++) {
|
|
219
|
+
let z = bias
|
|
220
|
+
|
|
221
|
+
for (let j = 0; j < dim; j++) {
|
|
222
|
+
z += weights[j]! * X[i]![j]!
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
const err = (sigmoid(z) - y[i]!) * w[i]!
|
|
226
|
+
|
|
227
|
+
for (let j = 0; j < dim; j++) {
|
|
228
|
+
gw[j]! += err * X[i]![j]!
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
gb += err
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
for (let j = 0; j < dim; j++) {
|
|
235
|
+
weights[j]! -= LR_LEARNING_RATE * (gw[j]! / X.length + LR_L2 * weights[j]!)
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
bias -= LR_LEARNING_RATE * (gb / X.length)
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
return (x) => {
|
|
242
|
+
let z = bias
|
|
243
|
+
|
|
244
|
+
for (let j = 0; j < x.length; j++) {
|
|
245
|
+
z += weights[j]! * x[j]!
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
return z
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
/**
|
|
253
|
+
* `n + 1` evenly-spaced order statistics of an already-sorted sample, de-duplicated,
|
|
254
|
+
* that a GBT node considers as candidate splits.
|
|
255
|
+
*
|
|
256
|
+
* An empty sample yields `[0]` so a degenerate feature still yields one threshold
|
|
257
|
+
* rather than an empty split set.
|
|
258
|
+
*/
|
|
259
|
+
export function uniqueQuantiles(sorted: readonly number[], n: number): number[] {
|
|
260
|
+
if (!sorted.length) return [0]
|
|
261
|
+
const ts = new Set<number>()
|
|
262
|
+
|
|
263
|
+
for (let k = 0; k <= n; k++) {
|
|
264
|
+
ts.add(sorted[Math.floor((k / n) * (sorted.length - 1))]!)
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
return [...ts]
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
const THRESHOLD_QUANTILE_POINTS = 32
|
|
271
|
+
|
|
272
|
+
/**
|
|
273
|
+
* Link-threshold candidates for a learned scorer: de-duplicated quantiles of the
|
|
274
|
+
* scorer's own eval-pair score distribution across the 0.2–0.999 band.
|
|
275
|
+
*/
|
|
276
|
+
export const quantileThresholds = (scores: readonly number[]): number[] => {
|
|
277
|
+
const sorted = [...scores].toSorted((p, q) => p - q)
|
|
278
|
+
const ts = new Set<number>()
|
|
279
|
+
|
|
280
|
+
for (let k = 0; k <= THRESHOLD_QUANTILE_POINTS; k++) {
|
|
281
|
+
ts.add(sorted[Math.floor((0.2 + (0.999 - 0.2) * (k / THRESHOLD_QUANTILE_POINTS)) * (sorted.length - 1))]!)
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
return [...ts]
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
/**
|
|
288
|
+
* One clustering arm's operating point, as the eval tables print it.
|
|
289
|
+
*/
|
|
290
|
+
export interface ArmScore {
|
|
291
|
+
precision: number
|
|
292
|
+
recall: number
|
|
293
|
+
f1: number
|
|
294
|
+
overMerged: number
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
/**
|
|
298
|
+
* Project a full {@link Score} onto the arm shape the eval tables print.
|
|
299
|
+
*/
|
|
300
|
+
export const toArmScore = (s: Score): ArmScore => ({
|
|
301
|
+
precision: s.precision,
|
|
302
|
+
recall: s.recall,
|
|
303
|
+
f1: s.f1,
|
|
304
|
+
overMerged: s.overMergedClusters,
|
|
305
|
+
})
|
|
306
|
+
|
|
307
|
+
/**
|
|
308
|
+
* The best-F1 operating point over a threshold sweep.
|
|
309
|
+
*/
|
|
310
|
+
export function bestOver(thresholds: readonly number[], scoreAt: (threshold: number) => ArmScore): ArmScore {
|
|
311
|
+
let best: ArmScore = { precision: 0, recall: 0, f1: -1, overMerged: 0 }
|
|
312
|
+
|
|
313
|
+
for (const t of thresholds) {
|
|
314
|
+
const s = scoreAt(t)
|
|
315
|
+
|
|
316
|
+
if (s.f1 > best.f1) {
|
|
317
|
+
best = s
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
return best
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
/**
|
|
325
|
+
* One organization provider at its practice address, as the geocode-free co-location probes read it.
|
|
326
|
+
*/
|
|
327
|
+
export interface ColocatedProvider {
|
|
328
|
+
npi: string
|
|
329
|
+
org: string
|
|
330
|
+
tokens: Set<string>
|
|
331
|
+
/**
|
|
332
|
+
* The composed practice address ({@link addr}).
|
|
333
|
+
*/
|
|
334
|
+
address: string
|
|
335
|
+
/**
|
|
336
|
+
* Strict last-10-digit phone key; `""` when the column contains fewer than 10 digits.
|
|
337
|
+
*/
|
|
338
|
+
phone: string
|
|
339
|
+
/**
|
|
340
|
+
* Authorized official, `"last first"`, lowercased.
|
|
341
|
+
*/
|
|
342
|
+
auth: string
|
|
343
|
+
/**
|
|
344
|
+
* Primary taxonomy (specialty) code.
|
|
345
|
+
*/
|
|
346
|
+
taxonomy: string
|
|
347
|
+
subpart: boolean
|
|
348
|
+
/**
|
|
349
|
+
* `parentLBN|parentTIN`, lowercased; `"|"` when both are blank.
|
|
350
|
+
*/
|
|
351
|
+
parent: string
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
/**
|
|
355
|
+
* What {@link scanColocatedProviders} collects.
|
|
356
|
+
*/
|
|
357
|
+
export interface ColocatedScan {
|
|
358
|
+
/**
|
|
359
|
+
* Providers grouped by their normalized practice-address key.
|
|
360
|
+
*/
|
|
361
|
+
byAddr: Map<string, ColocatedProvider[]>
|
|
362
|
+
kept: number
|
|
363
|
+
scanned: number
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
/**
|
|
367
|
+
* Stream in-state type-2 (organization) providers from the registry,
|
|
368
|
+
* one record per row at its practice address, grouped by `addressFrequencyKey`;
|
|
369
|
+
* geocode-free on purpose so it runs at large caps in seconds.
|
|
370
|
+
*/
|
|
371
|
+
export async function scanColocatedProviders(options: {
|
|
372
|
+
registryPath: string
|
|
373
|
+
state: string
|
|
374
|
+
cap: number
|
|
375
|
+
}): Promise<ColocatedScan> {
|
|
376
|
+
const { registryPath, state, cap } = options
|
|
377
|
+
const C = NPPES_COLUMNS
|
|
378
|
+
const byAddr = new Map<string, ColocatedProvider[]>()
|
|
379
|
+
let kept = 0
|
|
380
|
+
let scanned = 0
|
|
381
|
+
|
|
382
|
+
for await (const r of streamRows(registryPath)) {
|
|
383
|
+
scanned++
|
|
384
|
+
|
|
385
|
+
if (norm(r[C.entityType]) !== "2") continue
|
|
386
|
+
|
|
387
|
+
if (norm(r[C.pState]).toUpperCase() !== state) continue
|
|
388
|
+
const org = norm(r[C.orgLegal])
|
|
389
|
+
const line1 = norm(r[C.pAddr])
|
|
390
|
+
|
|
391
|
+
if (!org || !line1) continue
|
|
392
|
+
const address = addr(line1, r[C.pCity]!, state, r[C.pZip]!)
|
|
393
|
+
const addrKey = addressFrequencyKey(address)
|
|
394
|
+
|
|
395
|
+
if (!addrKey) continue
|
|
396
|
+
|
|
397
|
+
const provider: ColocatedProvider = {
|
|
398
|
+
npi: norm(r[C.npi]),
|
|
399
|
+
org,
|
|
400
|
+
tokens: orgTokens(org),
|
|
401
|
+
address,
|
|
402
|
+
phone: normalizePhoneStrict(r[C.pPhone]),
|
|
403
|
+
auth: `${norm(r[C.authLast])} ${norm(r[C.authFirst])}`.toLowerCase().trim(),
|
|
404
|
+
taxonomy: norm(r[C.taxonomy[0]!]),
|
|
405
|
+
subpart: norm(r[C.isSubpart]).toUpperCase() === "Y",
|
|
406
|
+
parent: `${norm(r[C.parentLBN])}|${norm(r[C.parentTIN])}`.toLowerCase(),
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
if (!byAddr.has(addrKey)) {
|
|
410
|
+
byAddr.set(addrKey, [])
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
byAddr.get(addrKey)!.push(provider)
|
|
414
|
+
|
|
415
|
+
kept++
|
|
416
|
+
|
|
417
|
+
if (kept >= cap) break
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
return { byAddr, kept, scanned }
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
/**
|
|
424
|
+
* One co-located distinct-NPI pair, with the address group it came from.
|
|
425
|
+
*/
|
|
426
|
+
export interface ColocatedPair {
|
|
427
|
+
a: ColocatedProvider
|
|
428
|
+
b: ColocatedProvider
|
|
429
|
+
/**
|
|
430
|
+
* The distinct-NPI providers at the shared address, length ≥ 2, one array reference
|
|
431
|
+
* per group so a consumer can detect the group boundary by identity.
|
|
432
|
+
*/
|
|
433
|
+
group: readonly ColocatedProvider[]
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
/**
|
|
437
|
+
* Every unordered pair of distinct NPIs sharing a practice-address key, de-duplicated
|
|
438
|
+
* per address by NPI (first record wins) so single-NPI addresses yield no pair.
|
|
439
|
+
*/
|
|
440
|
+
export function* colocatedDistinctPairs(
|
|
441
|
+
byAddr: ReadonlyMap<string, readonly ColocatedProvider[]>
|
|
442
|
+
): Generator<ColocatedPair> {
|
|
443
|
+
for (const providers of byAddr.values()) {
|
|
444
|
+
const distinct = new Map<string, ColocatedProvider>()
|
|
445
|
+
|
|
446
|
+
for (const p of providers)
|
|
447
|
+
if (!distinct.has(p.npi)) {
|
|
448
|
+
distinct.set(p.npi, p)
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
const group = [...distinct.values()]
|
|
452
|
+
|
|
453
|
+
if (group.length < 2) continue
|
|
454
|
+
|
|
455
|
+
for (let i = 0; i < group.length; i++) {
|
|
456
|
+
for (let j = i + 1; j < group.length; j++) {
|
|
457
|
+
yield { a: group[i]!, b: group[j]!, group }
|
|
458
|
+
}
|
|
459
|
+
}
|
|
460
|
+
}
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
/**
|
|
464
|
+
* The TX facility source specs the cross-source probes share.
|
|
465
|
+
*/
|
|
466
|
+
export const buildSpecs = (S: string, STATE: string): SourceSpec[] => [
|
|
467
|
+
{
|
|
468
|
+
source: "txhhsc-nursing",
|
|
469
|
+
path: `${S}/txhhsc_nursing-facilities_20260611.tsv`,
|
|
470
|
+
mapping: {
|
|
471
|
+
id: "Facility ID",
|
|
472
|
+
organization: "Facility Name",
|
|
473
|
+
address: ["Physical Address", "Physical Address CITY", "Physical Address State", "Physical Address Zipcode"],
|
|
474
|
+
phone: "Facility Phone Number",
|
|
475
|
+
source: "txhhsc-nursing",
|
|
476
|
+
},
|
|
477
|
+
inState: (r) => norm(r["Physical Address State"]).toUpperCase() === STATE,
|
|
478
|
+
},
|
|
479
|
+
{
|
|
480
|
+
source: "fcc-rhc",
|
|
481
|
+
path: `${S}/fcc-rhc_posted-services_form461-465_20260615.tsv`,
|
|
482
|
+
mapping: {
|
|
483
|
+
id: "HCP Number",
|
|
484
|
+
organization: "HCP Name",
|
|
485
|
+
address: ["Site Address Line 1", "Site City", "Site State", "Site ZIP Code"],
|
|
486
|
+
phone: "Contact Phone",
|
|
487
|
+
email: "Contact E-mail",
|
|
488
|
+
source: "fcc-rhc",
|
|
489
|
+
},
|
|
490
|
+
inState: (r) => norm(r["Site State"]).toUpperCase() === STATE,
|
|
491
|
+
},
|
|
492
|
+
{
|
|
493
|
+
source: "nppes",
|
|
494
|
+
path: `${S}/nppes_npi-registry_20260607.tsv`,
|
|
495
|
+
mapping: {
|
|
496
|
+
id: NPPES_COLUMNS.npi,
|
|
497
|
+
organization: NPPES_COLUMNS.orgLegal,
|
|
498
|
+
address: [NPPES_COLUMNS.pAddr, NPPES_COLUMNS.pCity, NPPES_COLUMNS.pState, NPPES_COLUMNS.pZip],
|
|
499
|
+
phone: NPPES_COLUMNS.pPhone,
|
|
500
|
+
source: "nppes",
|
|
501
|
+
},
|
|
502
|
+
inState: (r) =>
|
|
503
|
+
norm(r[NPPES_COLUMNS.pState]).toUpperCase() === STATE &&
|
|
504
|
+
norm(r[NPPES_COLUMNS.entityType]) === "2" &&
|
|
505
|
+
!!norm(r[NPPES_COLUMNS.orgLegal]),
|
|
506
|
+
},
|
|
507
|
+
]
|
|
508
|
+
|
|
509
|
+
const CROSS_SOURCE_HYPERPARAMS: GBTOpts = { rounds: 120, depth: 3, lr: 0.3, minLeaf: 20 }
|
|
510
|
+
|
|
511
|
+
const FIT_SPLIT_FRACTION = 0.8
|
|
512
|
+
|
|
513
|
+
/**
|
|
514
|
+
* One assembled input row for a cross-source trainer.
|
|
515
|
+
*
|
|
516
|
+
* Its `npi` field contains the cross-system join key (an NPI or a CCN).
|
|
517
|
+
* The trainer copies that key into `record.id` as the held-out label.
|
|
518
|
+
*/
|
|
519
|
+
export interface CrossSourceRow extends Record<string, string> {
|
|
520
|
+
npi: string
|
|
521
|
+
name: string
|
|
522
|
+
org: string
|
|
523
|
+
address: string
|
|
524
|
+
source: string
|
|
525
|
+
}
|
|
526
|
+
|
|
527
|
+
/**
|
|
528
|
+
* Every figure passed to {@link TrainCrossSourceModelOptions.meta}.
|
|
529
|
+
*/
|
|
530
|
+
export interface CrossSourceTrainingFigures {
|
|
531
|
+
records: number
|
|
532
|
+
pairs: number
|
|
533
|
+
posRate: number
|
|
534
|
+
barRecall: number
|
|
535
|
+
f1Max: number
|
|
536
|
+
recommendedThreshold: number
|
|
537
|
+
features: number
|
|
538
|
+
hyperparams: GBTOpts
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
/**
|
|
542
|
+
* Options for {@linkcode trainCrossSourceModel}.
|
|
543
|
+
*/
|
|
544
|
+
export interface TrainCrossSourceModelOptions {
|
|
545
|
+
/**
|
|
546
|
+
* The injected geocoder factory (the command wires `mailwoman/geocode-core`; see `./eval-geocoder.ts`).
|
|
547
|
+
*/
|
|
548
|
+
createGeocoder: EvalGeocoderFactory
|
|
549
|
+
/**
|
|
550
|
+
* The assembled two-source rows.
|
|
551
|
+
* The caller owns source loading.
|
|
552
|
+
*/
|
|
553
|
+
rows: readonly CrossSourceRow[]
|
|
554
|
+
/**
|
|
555
|
+
* The join keys present in both sources.
|
|
556
|
+
*/
|
|
557
|
+
joined: ReadonlySet<string>
|
|
558
|
+
addressFrequency: TermFrequencyTable
|
|
559
|
+
/**
|
|
560
|
+
* The two provenance labels, in ingest order.
|
|
561
|
+
*/
|
|
562
|
+
sources: readonly [string, string]
|
|
563
|
+
/**
|
|
564
|
+
* Max cross-source recall subject to this held-out pairwise precision.
|
|
565
|
+
*/
|
|
566
|
+
precisionBar: number
|
|
567
|
+
/**
|
|
568
|
+
* Output TS module path.
|
|
569
|
+
*/
|
|
570
|
+
out: string
|
|
571
|
+
/**
|
|
572
|
+
* The emitted module's docstring prose — the ` * `-prefixed lines between the author block and the closer.
|
|
573
|
+
*/
|
|
574
|
+
moduleDoc: string
|
|
575
|
+
/**
|
|
576
|
+
* Emitted export prefix — the module exports `<prefix>_META` + `<prefix>_MODEL`.
|
|
577
|
+
*/
|
|
578
|
+
exportPrefix: string
|
|
579
|
+
/**
|
|
580
|
+
* Assemble the emitted `<prefix>_META` object.
|
|
581
|
+
*
|
|
582
|
+
* The caller owns field names and order so a retrain's diff against its committed
|
|
583
|
+
* module shows only the changed values.
|
|
584
|
+
*/
|
|
585
|
+
meta: (figures: CrossSourceTrainingFigures) => Record<string, unknown>
|
|
586
|
+
report?: (line: string) => void
|
|
587
|
+
}
|
|
588
|
+
|
|
589
|
+
/**
|
|
590
|
+
* Geocode and ingest each source under its own provenance label, block the union,
|
|
591
|
+
* keep only cross-source candidate pairs, featurize with `createMatchFeaturizer` so train
|
|
592
|
+
* and inference agree, calibrate the threshold on a held-out split of the join keys,
|
|
593
|
+
* then train and emit the shipped model as a committed TS module.
|
|
594
|
+
*/
|
|
595
|
+
export async function trainCrossSourceModel(
|
|
596
|
+
options: TrainCrossSourceModelOptions
|
|
597
|
+
): Promise<{ out: string; pairs: number; recommendedThreshold: number }> {
|
|
598
|
+
const { rows, joined, addressFrequency, sources, precisionBar, out, report } = options
|
|
599
|
+
|
|
600
|
+
report?.("[C] geocoding…")
|
|
601
|
+
const geocoder = await options.createGeocoder()
|
|
602
|
+
|
|
603
|
+
// Ingest each source separately to retain its literal provenance label on every record.
|
|
604
|
+
// The cross-source filter uses that label.
|
|
605
|
+
const mappingFor = (source: string): ColumnMapping => ({
|
|
606
|
+
id: "npi",
|
|
607
|
+
name: "name",
|
|
608
|
+
organization: "org",
|
|
609
|
+
address: "address",
|
|
610
|
+
source,
|
|
611
|
+
})
|
|
612
|
+
|
|
613
|
+
const records: SourceRecord[] = []
|
|
614
|
+
|
|
615
|
+
for (const source of sources) {
|
|
616
|
+
records.push(
|
|
617
|
+
...(await ingestRows(
|
|
618
|
+
rows.filter((r) => r.source === source),
|
|
619
|
+
mappingFor(source),
|
|
620
|
+
{ geocodeAddress: geocoder.geocodeAddress }
|
|
621
|
+
))
|
|
622
|
+
)
|
|
623
|
+
}
|
|
624
|
+
|
|
625
|
+
geocoder[Symbol.dispose]()
|
|
626
|
+
report?.(` ${records.length} records, ${records.filter((r) => r.address?.geocode).length} geocoded`)
|
|
627
|
+
|
|
628
|
+
report?.("[D] blocking + featurizing (cross-source pairs only)…")
|
|
629
|
+
const comparisons = buildDefaultModel({ collapseSpatial: true, addressFrequency }).comparisons
|
|
630
|
+
const featurize = createMatchFeaturizer({ comparisons, addressFrequency })
|
|
631
|
+
const { pairs: allPairs } = block(records, defaultBlockingKeys())
|
|
632
|
+
const pairs = allPairs.filter(([a, b]) => a.source !== b.source)
|
|
633
|
+
const X = pairs.map(([a, b]) => featurize(a, b))
|
|
634
|
+
const Y: number[] = pairs.map(([a, b]) => (a.id === b.id ? 1 : 0))
|
|
635
|
+
const posRate = Y.reduce((s, y) => s + y, 0) / Math.max(1, Y.length)
|
|
636
|
+
const W = Y.map((y) => (y === 1 ? 1 - posRate : posRate))
|
|
637
|
+
|
|
638
|
+
report?.(
|
|
639
|
+
` ${allPairs.length} blocked pairs → ${pairs.length} cross-source (${(100 * posRate).toFixed(1)}% positive)`
|
|
640
|
+
)
|
|
641
|
+
|
|
642
|
+
report?.("[E] held-out calibration…")
|
|
643
|
+
const rnd = makeLcg(655)
|
|
644
|
+
const split = new Map<string, "fit" | "holdout">()
|
|
645
|
+
|
|
646
|
+
for (const key of joined) {
|
|
647
|
+
split.set(key, rnd() < FIT_SPLIT_FRACTION ? "fit" : "holdout")
|
|
648
|
+
}
|
|
649
|
+
|
|
650
|
+
const fitIdx = pairs
|
|
651
|
+
.map((_, i) => i)
|
|
652
|
+
.filter((i) => split.get(pairs[i]![0].id) === "fit" && split.get(pairs[i]![1].id) === "fit")
|
|
653
|
+
|
|
654
|
+
const holdIdx = pairs
|
|
655
|
+
.map((_, i) => i)
|
|
656
|
+
.filter((i) => split.get(pairs[i]![0].id) === "holdout" && split.get(pairs[i]![1].id) === "holdout")
|
|
657
|
+
|
|
658
|
+
const calib = trainGBT(
|
|
659
|
+
fitIdx.map((i) => X[i]!),
|
|
660
|
+
fitIdx.map((i) => Y[i]!),
|
|
661
|
+
fitIdx.map((i) => W[i]!),
|
|
662
|
+
CROSS_SOURCE_HYPERPARAMS
|
|
663
|
+
)
|
|
664
|
+
|
|
665
|
+
const holdScores = holdIdx.map((i) => ({ s: gbtScore(calib, X[i]!), y: Y[i]! }))
|
|
666
|
+
const sorted = holdScores.map((h) => h.s).toSorted((a, b) => a - b)
|
|
667
|
+
const totalPos = holdScores.reduce((s, h) => s + h.y, 0)
|
|
668
|
+
let recommendedThreshold = Number.POSITIVE_INFINITY
|
|
669
|
+
let barRecall = 0
|
|
670
|
+
let f1MaxThreshold = 0
|
|
671
|
+
let bestF1 = -1
|
|
672
|
+
|
|
673
|
+
for (const t of uniqueQuantiles(sorted, 60)) {
|
|
674
|
+
let tp = 0
|
|
675
|
+
let fp = 0
|
|
676
|
+
|
|
677
|
+
for (const h of holdScores) {
|
|
678
|
+
if (h.s < t) continue
|
|
679
|
+
|
|
680
|
+
if (h.y) {
|
|
681
|
+
tp++
|
|
682
|
+
} else {
|
|
683
|
+
fp++
|
|
684
|
+
}
|
|
685
|
+
}
|
|
686
|
+
|
|
687
|
+
const precision = tp + fp > 0 ? tp / (tp + fp) : 1
|
|
688
|
+
const recall = totalPos > 0 ? tp / totalPos : 0
|
|
689
|
+
const f1 = precision + recall > 0 ? (2 * precision * recall) / (precision + recall) : 0
|
|
690
|
+
|
|
691
|
+
// The lowest threshold whose precision clears the bar, maximizing recall under it.
|
|
692
|
+
if (precision >= precisionBar && recall > barRecall) {
|
|
693
|
+
barRecall = recall
|
|
694
|
+
recommendedThreshold = t
|
|
695
|
+
}
|
|
696
|
+
|
|
697
|
+
if (f1 > bestF1) {
|
|
698
|
+
bestF1 = f1
|
|
699
|
+
f1MaxThreshold = t
|
|
700
|
+
}
|
|
701
|
+
}
|
|
702
|
+
|
|
703
|
+
if (!Number.isFinite(recommendedThreshold)) {
|
|
704
|
+
recommendedThreshold = f1MaxThreshold
|
|
705
|
+
}
|
|
706
|
+
|
|
707
|
+
report?.(
|
|
708
|
+
` held-out (${holdIdx.length} pairs, ${totalPos} pos): precision-bar ${precisionBar} → threshold ${recommendedThreshold.toFixed(3)} (recall ${(100 * barRecall).toFixed(1)}%); F1-max ${(100 * bestF1).toFixed(1)}% @ ${f1MaxThreshold.toFixed(3)}`
|
|
709
|
+
)
|
|
710
|
+
|
|
711
|
+
report?.("[F] training the shipped model on all pairs…")
|
|
712
|
+
const model = trainGBT(X, Y, W, CROSS_SOURCE_HYPERPARAMS)
|
|
713
|
+
|
|
714
|
+
const meta = options.meta({
|
|
715
|
+
records: records.length,
|
|
716
|
+
pairs: pairs.length,
|
|
717
|
+
posRate: Number(posRate.toFixed(4)),
|
|
718
|
+
barRecall: Number(barRecall.toFixed(4)),
|
|
719
|
+
f1Max: Number(bestF1.toFixed(4)),
|
|
720
|
+
recommendedThreshold: Number(recommendedThreshold.toFixed(4)),
|
|
721
|
+
features: X[0]?.length ?? 0,
|
|
722
|
+
hyperparams: CROSS_SOURCE_HYPERPARAMS,
|
|
723
|
+
})
|
|
724
|
+
|
|
725
|
+
const moduleSource =
|
|
726
|
+
`/**\n` +
|
|
727
|
+
` * @copyright Sister Software\n` +
|
|
728
|
+
` * @license AGPL-3.0\n` +
|
|
729
|
+
` * @author Teffen Ellis, et al.\n` +
|
|
730
|
+
` *\n` +
|
|
731
|
+
options.moduleDoc +
|
|
732
|
+
` */\n\n` +
|
|
733
|
+
`import type { GBT } from "@mailwoman/match"\n\n` +
|
|
734
|
+
`export const ${options.exportPrefix}_META = ${stringifyJSON(meta)} as const\n\n` +
|
|
735
|
+
`// prettier-ignore\n` +
|
|
736
|
+
`export const ${options.exportPrefix}_MODEL: GBT = ${stringifyJSON(model)}\n`
|
|
737
|
+
|
|
738
|
+
await makeDirectories(dirname(out))
|
|
739
|
+
await writeLocalFile(moduleSource, out)
|
|
740
|
+
report?.(` ${model.trees.length} trees, ${X[0]?.length ?? 0} features -> ${out}`)
|
|
741
|
+
|
|
742
|
+
return { out, pairs: pairs.length, recommendedThreshold }
|
|
743
|
+
}
|