pangloss-learn 0.1.0__py3-none-any.whl

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.
@@ -0,0 +1,30 @@
1
+ """Fitting a weighted model from people's decisions, with no database and nothing of Pangloss in it (`maths.py` is
2
+ the whole of it): `fit` (a logistic regression), `Model` (plain data, to and from JSON, `Model.score`), `compare`
3
+ (is a fitted model better than a score set by hand, on decisions it was not fitted on), `compare_calls` (the same of
4
+ a model that says yes or no of a whole decision, against always answering the commoner or a score set by hand;
5
+ `CallsCompared`, its answer with how many calls differ, and a check that allows for chance).
6
+ implementation_docs/similarity-build-plan.md, phase 11; implementation_docs/learn.md"""
7
+
8
+ lazy from pangloss_learn.maths import (
9
+ CallsCompared,
10
+ Compared,
11
+ Example,
12
+ Model,
13
+ Unfittable,
14
+ compare,
15
+ compare_calls,
16
+ fit,
17
+ folds_of,
18
+ )
19
+
20
+ __all__ = [
21
+ "CallsCompared",
22
+ "Compared",
23
+ "Example",
24
+ "Model",
25
+ "Unfittable",
26
+ "compare",
27
+ "compare_calls",
28
+ "fit",
29
+ "folds_of",
30
+ ]
@@ -0,0 +1,357 @@
1
+ """The whole of the learning, with no database in it (step 11.1 of implementation_docs/similarity-build-plan.md).
2
+
3
+ An **example** is one thing that was offered when a person decided: its features (numbers, by name), whether it was
4
+ the one taken (`yes`), and the decision it belongs to (`group`: the others offered with it are of the same group).
5
+
6
+ `fit` makes a **model**: a logistic regression, the likelihood of "yes" as `1 / (1 + exp(-(w·x + c)))`, fitted by
7
+ Newton's steps with a ridge (a pull of every weight but the constant towards 0, so that examples a feature divides
8
+ cleanly do not send its weight off without end). The examples are put in one order first, so the same examples,
9
+ given in any order, make the same model to the last bit.
10
+
11
+ `compare` says whether a model is worth using: the decisions are dealt into folds by a seed; for each fold a model
12
+ is fitted on the others, and in each decision of the fold the example it scores highest is looked at, and the one a
13
+ baseline (a score set by hand) scores highest. How often each was the one taken is the answer. A decision in which
14
+ nothing offered was taken can be right for neither, and is not counted.
15
+
16
+ `compare_calls` is the same question of a model that says yes or no of a whole decision ("none of those offered is
17
+ the one"): each example is a decision by itself, the model's call is "yes" at a likelihood of a half or more, and
18
+ what it is compared with is always answering whichever of the two was the commoner among the examples it was fitted
19
+ on, or, given a `baseline` (a likelihood set by hand, of an example's features), that likelihood's call at a half.
20
+ Two options, each off unless asked for: `stratified` deals the "yes" and the "no" into the folds apart, evenly, so that
21
+ every part a model is fitted on has both answers wherever there are two of each or more; `count_differences` also
22
+ counts the held-out examples the model and the baseline call differently (`CallsCompared.differ`), for a check that
23
+ allows for chance (`CallsCompared.within`).
24
+
25
+ Features are not rescaled: they are expected to be of the size of a cosine or a small count's logarithm."""
26
+
27
+ import dataclasses
28
+ import json
29
+ import math
30
+ import random
31
+ from collections.abc import Callable, Iterable, Mapping, Sequence
32
+ from typing import Any
33
+
34
+ import numpy as np
35
+
36
+ STEPS = 100
37
+ """The most of Newton's steps (a fit that has a ridge settles in under ten)"""
38
+
39
+
40
+ class Unfittable(ValueError):
41
+ """The examples given cannot make a model: the message says why"""
42
+
43
+
44
+ @dataclasses.dataclass(frozen=True)
45
+ class Example:
46
+ features: Mapping[str, float]
47
+ yes: bool
48
+ group: str = ""
49
+
50
+
51
+ @dataclasses.dataclass(frozen=True)
52
+ class Model:
53
+ """What `fit` found: plain data. `examples` and `yes` are how many it was fitted on and how many of them were
54
+ taken; `fitted_at` is what the caller said (the maths knows no clock)"""
55
+
56
+ features: tuple[str, ...]
57
+ weights: tuple[float, ...]
58
+ constant: float
59
+ examples: int = 0
60
+ yes: int = 0
61
+ ridge: float = 1.0
62
+ fitted_at: str | None = None
63
+
64
+ def __post_init__(self) -> None:
65
+ if len(self.features) != len(self.weights):
66
+ raise ValueError(
67
+ f"A model has a weight for each feature, not {len(self.weights)} for {len(self.features)}"
68
+ )
69
+
70
+ def score(self, features: Mapping[str, float]) -> float:
71
+ """The likelihood, from 0 to 1, that what has these features is the one"""
72
+ return float(_likelihood(np.array([self._sum(features)]))[0])
73
+
74
+ def _sum(self, features: Mapping[str, float]) -> float:
75
+ missing = [name for name in self.features if name not in features]
76
+ if missing:
77
+ raise KeyError(
78
+ f"The model weighs {', '.join(missing)}, which the features given do not have "
79
+ f"(they have {', '.join(sorted(features)) or 'none'})"
80
+ )
81
+ return self.constant + sum(
82
+ weight * float(features[name])
83
+ for name, weight in zip(self.features, self.weights, strict=True)
84
+ )
85
+
86
+ def to_json(self) -> str:
87
+ return json.dumps(dataclasses.asdict(self), sort_keys=True)
88
+
89
+ @classmethod
90
+ def from_json(cls, text: str) -> Model:
91
+ data: dict[str, Any] = json.loads(text)
92
+ return cls(
93
+ features=tuple(data["features"]),
94
+ weights=tuple(float(weight) for weight in data["weights"]),
95
+ constant=float(data["constant"]),
96
+ examples=int(data.get("examples", 0)),
97
+ yes=int(data.get("yes", 0)),
98
+ ridge=float(data.get("ridge", 1.0)),
99
+ fitted_at=data.get("fitted_at"),
100
+ )
101
+
102
+
103
+ @dataclasses.dataclass(frozen=True)
104
+ class Compared:
105
+ """Of `decisions` decisions (those in which something offered was taken), in how many the one taken was first
106
+ by a model fitted on the other folds (`model`) and by the baseline (`baseline`)"""
107
+
108
+ decisions: int
109
+ model: int
110
+ baseline: int
111
+
112
+ @property
113
+ def no_worse(self) -> bool:
114
+ return self.model >= self.baseline
115
+
116
+
117
+ @dataclasses.dataclass(frozen=True)
118
+ class CallsCompared(Compared):
119
+ """(`compare_calls(count_differences=True)`) the same, and of the examples held out, how many the model and the
120
+ baseline call differently (`differ`): only there can one be right where the other is not"""
121
+
122
+ differ: int = 0
123
+
124
+ def within(self, margin: float) -> bool:
125
+ """No worse than the baseline by more than chance: the baseline right more often than the model by no more
126
+ than `margin` times the square root of `differ` (the spread of the difference were each of those calls a coin
127
+ toss). A margin of 0 is `no_worse`"""
128
+ if margin < 0:
129
+ raise ValueError(f"A margin is a number of 0 or more, not {margin!r}")
130
+ return self.baseline - self.model <= margin * math.sqrt(self.differ)
131
+
132
+
133
+ def _likelihood(sums: np.ndarray) -> np.ndarray:
134
+ # (cut where `exp` would overflow: a likelihood of 0 or 1 to every digit kept)
135
+ return 1.0 / (1.0 + np.exp(-np.clip(sums, -700.0, 700.0)))
136
+
137
+
138
+ def _rows(
139
+ examples: Sequence[Example], features: Sequence[str]
140
+ ) -> tuple[np.ndarray, np.ndarray]:
141
+ for example in examples:
142
+ missing = [name for name in features if name not in example.features]
143
+ if missing:
144
+ raise Unfittable(
145
+ f"An example has no {', '.join(missing)} (it has "
146
+ f"{', '.join(sorted(example.features)) or 'no features'}): every example needs every feature fitted"
147
+ )
148
+ rows = sorted(
149
+ (*(float(e.features[name]) for name in features), 1.0 if e.yes else 0.0)
150
+ for e in examples
151
+ )
152
+ table = np.array(rows, dtype=float).reshape(len(rows), len(features) + 1)
153
+ if not np.isfinite(table).all():
154
+ raise Unfittable("An example has a feature that is not a number (nan or inf)")
155
+ return table[:, :-1], table[:, -1]
156
+
157
+
158
+ def fit(
159
+ examples: Iterable[Example],
160
+ features: Sequence[str],
161
+ *,
162
+ ridge: float = 1.0,
163
+ fitted_at: str | None = None,
164
+ ) -> Model:
165
+ """The model of these examples over these features. Refused (`Unfittable`): no features, a ridge that is not
166
+ above 0, fewer examples than features and one, examples that are all "yes" or all "no", an example without one
167
+ of the features"""
168
+ examples = list(examples)
169
+ features = tuple(features)
170
+ if not features:
171
+ raise Unfittable("A model is fitted over one feature or more: none was named")
172
+ if len(set(features)) != len(features):
173
+ raise Unfittable(f"A feature is named twice: {', '.join(features)}")
174
+ if not ridge > 0:
175
+ raise Unfittable(f"The ridge is a number above 0, not {ridge!r}")
176
+ if len(examples) < len(features) + 2:
177
+ raise Unfittable(
178
+ f"{len(examples)} examples are too few to fit {len(features)} features: "
179
+ f"at least {len(features) + 2} are needed"
180
+ )
181
+ x, y = _rows(examples, features)
182
+ taken = int(y.sum())
183
+ if taken in (0, len(y)):
184
+ raise Unfittable(
185
+ f"All {len(y)} examples are {'yes' if taken else 'no'}: a model needs some of each"
186
+ )
187
+ x = np.hstack([x, np.ones((len(x), 1))])
188
+ pull = np.eye(x.shape[1]) * ridge
189
+ pull[-1, -1] = 0.0
190
+ w = np.zeros(x.shape[1])
191
+ settled = False
192
+ for _ in range(STEPS):
193
+ p = _likelihood(x @ w)
194
+ slope = x.T @ (p - y) + pull @ w
195
+ curve = (x * (p * (1.0 - p))[:, None]).T @ x + pull
196
+ # (the constant has no pull: a grain on the diagonal keeps the step defined when every likelihood is 0 or 1)
197
+ step = np.linalg.solve(curve + 1e-9 * np.eye(len(w)), slope)
198
+ w = w - step
199
+ if not np.isfinite(w).all():
200
+ break
201
+ if float(np.abs(step).max()) < 1e-10:
202
+ settled = True
203
+ break
204
+ if not settled:
205
+ raise Unfittable(
206
+ f"The fit did not settle in {STEPS} steps: the examples are too few or too alike to fit {len(features)} "
207
+ "features"
208
+ )
209
+ return Model(
210
+ features=features,
211
+ weights=tuple(float(v) for v in w[:-1]),
212
+ constant=float(w[-1]),
213
+ examples=len(y),
214
+ yes=taken,
215
+ ridge=float(ridge),
216
+ fitted_at=fitted_at,
217
+ )
218
+
219
+
220
+ def _first(scores: Sequence[float]) -> int:
221
+ """Where the highest score is; of several alike, the first as they were given"""
222
+ return max(range(len(scores)), key=lambda n: (scores[n], -n))
223
+
224
+
225
+ def compare(
226
+ examples: Iterable[Example],
227
+ features: Sequence[str],
228
+ baseline: Callable[[Mapping[str, float]], float],
229
+ *,
230
+ folds: int = 5,
231
+ seed: int = 0,
232
+ ridge: float = 1.0,
233
+ ) -> Compared:
234
+ """How often the one taken is first by a model fitted on the other folds, and by `baseline`, over the decisions
235
+ (the groups) in which something offered was taken. Refused (`Unfittable`): fewer decisions than folds, fewer
236
+ than two folds, or a fold whose others cannot be fitted"""
237
+ if folds < 2:
238
+ raise Unfittable(f"A comparison is over two folds or more, not {folds}")
239
+ groups: dict[str, list[Example]] = {}
240
+ for example in examples:
241
+ groups.setdefault(example.group, []).append(example)
242
+ names = sorted(groups)
243
+ if len(names) < folds:
244
+ raise Unfittable(
245
+ f"{len(names)} decisions are too few to compare over {folds} folds"
246
+ )
247
+ random.Random(seed).shuffle(names)
248
+ decisions = by_model = by_baseline = 0
249
+ for fold in range(folds):
250
+ held = names[fold::folds]
251
+ kept = set(names) - set(held)
252
+ model = fit(
253
+ (e for name in sorted(kept) for e in groups[name]), features, ridge=ridge
254
+ )
255
+ for name in held:
256
+ rows = groups[name]
257
+ if not any(e.yes for e in rows):
258
+ continue
259
+ decisions += 1
260
+ sums = [model._sum(e.features) for e in rows]
261
+ given = [baseline(e.features) for e in rows]
262
+ by_model += rows[_first(sums)].yes
263
+ by_baseline += rows[_first(given)].yes
264
+ return Compared(decisions=decisions, model=by_model, baseline=by_baseline)
265
+
266
+
267
+ def _in_order(examples: Sequence[Example], features: Sequence[str]) -> list[Example]:
268
+ return sorted(
269
+ examples,
270
+ key=lambda e: (e.group, *(float(e.features[name]) for name in features), e.yes),
271
+ )
272
+
273
+
274
+ def _dealt(
275
+ ordered: Sequence[Example], folds: int, seed: int, stratified: bool
276
+ ) -> list[int]:
277
+ """The places of the examples in the order they are dealt round the folds (fold `k` holds `places[k::folds]`)"""
278
+ if stratified:
279
+ shuffle = random.Random(seed).shuffle
280
+ yes = [n for n, e in enumerate(ordered) if e.yes]
281
+ no = [n for n, e in enumerate(ordered) if not e.yes]
282
+ shuffle(yes)
283
+ shuffle(no)
284
+ return yes + no
285
+ places = list(range(len(ordered)))
286
+ random.Random(seed).shuffle(places)
287
+ return places
288
+
289
+
290
+ def folds_of(
291
+ examples: Iterable[Example],
292
+ features: Sequence[str],
293
+ *,
294
+ folds: int = 5,
295
+ seed: int = 0,
296
+ stratified: bool = False,
297
+ ) -> list[list[Example]]:
298
+ """The examples each fold of `compare_calls` holds out, as it deals them (to see how they are dealt)"""
299
+ ordered = _in_order(list(examples), tuple(features))
300
+ places = _dealt(ordered, folds, seed, stratified)
301
+ return [[ordered[n] for n in sorted(places[fold::folds])] for fold in range(folds)]
302
+
303
+
304
+ def compare_calls(
305
+ examples: Iterable[Example],
306
+ features: Sequence[str],
307
+ *,
308
+ folds: int = 5,
309
+ seed: int = 0,
310
+ ridge: float = 1.0,
311
+ baseline: Callable[[Mapping[str, float]], float] | None = None,
312
+ stratified: bool = False,
313
+ count_differences: bool = False,
314
+ ) -> Compared:
315
+ """For examples that are each a decision by itself (yes or no of the whole of it): how often a model fitted on
316
+ the other folds calls it rightly ("yes" at a likelihood of a half or more), and how often always answering the
317
+ commoner of the two among those other folds does ("yes" when they are as many), or, with `baseline`, how often
318
+ its likelihood does ("yes" at a half or more), on the same held-out examples. The examples are put in one
319
+ order first (by `group`, then by what they are), so the same examples in any order give the same answer.
320
+ `stratified`: the "yes" and the "no" are dealt into the folds apart (each shuffled by the seed, the "yes" first,
321
+ round the folds in turn), so each fold has as many of each as another, give or take one, and every part fitted on
322
+ has both answers where there are two of each or more. `count_differences`: a `CallsCompared`, with how many of
323
+ the held-out examples the two call differently. Refused (`Unfittable`): fewer examples than folds, fewer than
324
+ two folds, or a fold whose others cannot be fitted"""
325
+ if folds < 2:
326
+ raise Unfittable(f"A comparison is over two folds or more, not {folds}")
327
+ features = tuple(features)
328
+ for example in (examples := list(examples)):
329
+ missing = [name for name in features if name not in example.features]
330
+ if missing:
331
+ raise Unfittable(
332
+ f"An example has no {', '.join(missing)}: every example needs every feature fitted"
333
+ )
334
+ ordered = _in_order(examples, features)
335
+ if len(ordered) < folds:
336
+ raise Unfittable(
337
+ f"{len(ordered)} decisions are too few to compare over {folds} folds"
338
+ )
339
+ places = _dealt(ordered, folds, seed, stratified)
340
+ by_model = by_baseline = differ = 0
341
+ for fold in range(folds):
342
+ held = set(places[fold::folds])
343
+ others = [ordered[n] for n in range(len(ordered)) if n not in held]
344
+ model = fit(others, features, ridge=ridge)
345
+ commoner = 2 * sum(e.yes for e in others) >= len(others)
346
+ for n in sorted(held):
347
+ example = ordered[n]
348
+ fitted = model._sum(example.features) >= 0.0
349
+ called = commoner if baseline is None else baseline(example.features) >= 0.5
350
+ by_model += fitted == example.yes
351
+ by_baseline += called == example.yes
352
+ differ += fitted != called
353
+ if count_differences:
354
+ return CallsCompared(
355
+ decisions=len(ordered), model=by_model, baseline=by_baseline, differ=differ
356
+ )
357
+ return Compared(decisions=len(ordered), model=by_model, baseline=by_baseline)
File without changes
@@ -0,0 +1,20 @@
1
+ Metadata-Version: 2.4
2
+ Name: pangloss-learn
3
+ Version: 0.1.0
4
+ Summary: Fitting a weighted model from people's decisions for Pangloss: a logistic regression in numpy, with no database in it
5
+ Author: Richard Hadden
6
+ Author-email: Richard Hadden <richard.hadden@oeaw.ac.at>
7
+ License-Expression: MIT
8
+ License-File: LICENCE.txt
9
+ Requires-Dist: numpy>=2.2
10
+ Requires-Python: >=3.15
11
+ Project-URL: Repository, https://github.com/richardhadden/pangloss-monorepo
12
+ Description-Content-Type: text/markdown
13
+
14
+ # pangloss-learn
15
+
16
+ Fitting a weighted model from people's decisions: `fit` (a logistic regression, in numpy), `Model` (plain data, to
17
+ and from JSON), and `compare` (is the fitted model better than what was set by hand, on decisions it was not fitted
18
+ on). No database and nothing of Pangloss in it; `pangloss-reconcile` uses it.
19
+
20
+ See `implementation_docs/learn.md`.
@@ -0,0 +1,7 @@
1
+ pangloss_learn/__init__.py,sha256=VRPk3HLmFoV1mlGViKgxjuPZk5L8eKHERstkpCUKWmw,970
2
+ pangloss_learn/maths.py,sha256=Ov5iX6dl6A-7GwFMrg8DjDpDcaaoP6vacmRLBQ8TE14,15235
3
+ pangloss_learn/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
4
+ pangloss_learn-0.1.0.dist-info/licenses/LICENCE.txt,sha256=yK3mD1PXzN7jWtO03x7BQoPgKqepJ5H-tAW7ZNumvNI,1136
5
+ pangloss_learn-0.1.0.dist-info/WHEEL,sha256=3NO1oYsF7mANFUWVdyEQLM-zmecczWWEmmF5rEbXrWk,80
6
+ pangloss_learn-0.1.0.dist-info/METADATA,sha256=Pu8C4jF1NmtwvnS1jsr6NG4ZK8EiXsXUqZ9dPVNyvbs,846
7
+ pangloss_learn-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: uv 0.13.6
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2026, Richard Hadden, Department of Digital Humanities, University of Graz
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.