bitskitten 0.4.0__tar.gz → 0.5.0__tar.gz
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.
- {bitskitten-0.4.0 → bitskitten-0.5.0}/PKG-INFO +33 -19
- bitskitten-0.4.0/bitskitten.egg-info/PKG-INFO → bitskitten-0.5.0/README.md +20 -32
- bitskitten-0.5.0/__init__.py +51 -0
- bitskitten-0.5.0/_deps.py +20 -0
- {bitskitten-0.4.0 → bitskitten-0.5.0}/bandit.py +14 -10
- bitskitten-0.4.0/README.md → bitskitten-0.5.0/bitskitten.egg-info/PKG-INFO +46 -11
- {bitskitten-0.4.0 → bitskitten-0.5.0}/bitskitten.egg-info/SOURCES.txt +3 -0
- {bitskitten-0.4.0 → bitskitten-0.5.0}/bitskitten.egg-info/requires.txt +9 -1
- bitskitten-0.5.0/metrics.py +64 -0
- {bitskitten-0.4.0 → bitskitten-0.5.0}/pyproject.toml +7 -11
- {bitskitten-0.4.0 → bitskitten-0.5.0}/qa/__init__.py +2 -2
- {bitskitten-0.4.0 → bitskitten-0.5.0}/qa/judge.py +14 -6
- {bitskitten-0.4.0 → bitskitten-0.5.0}/qa/runner.py +8 -3
- {bitskitten-0.4.0 → bitskitten-0.5.0}/tests/test_bandit.py +12 -2
- bitskitten-0.5.0/tests/test_boundary.py +52 -0
- {bitskitten-0.4.0 → bitskitten-0.5.0}/tests/test_fit_time.py +12 -0
- {bitskitten-0.4.0 → bitskitten-0.5.0}/tests/test_qa_judge.py +10 -1
- {bitskitten-0.4.0 → bitskitten-0.5.0}/tests/test_qa_runner.py +5 -3
- bitskitten-0.4.0/__init__.py +0 -35
- bitskitten-0.4.0/metrics.py +0 -36
- {bitskitten-0.4.0 → bitskitten-0.5.0}/LICENSE +0 -0
- {bitskitten-0.4.0 → bitskitten-0.5.0}/bitskitten.egg-info/dependency_links.txt +0 -0
- {bitskitten-0.4.0 → bitskitten-0.5.0}/bitskitten.egg-info/top_level.txt +0 -0
- {bitskitten-0.4.0 → bitskitten-0.5.0}/classes.py +0 -0
- {bitskitten-0.4.0 → bitskitten-0.5.0}/input.py +0 -0
- {bitskitten-0.4.0 → bitskitten-0.5.0}/output.py +0 -0
- {bitskitten-0.4.0 → bitskitten-0.5.0}/qa/checks.py +0 -0
- {bitskitten-0.4.0 → bitskitten-0.5.0}/qa/failures.py +0 -0
- {bitskitten-0.4.0 → bitskitten-0.5.0}/qa/scenario.py +0 -0
- {bitskitten-0.4.0 → bitskitten-0.5.0}/qa/users.py +0 -0
- {bitskitten-0.4.0 → bitskitten-0.5.0}/setup.cfg +0 -0
- {bitskitten-0.4.0 → bitskitten-0.5.0}/tests/test_qa.py +0 -0
- {bitskitten-0.4.0 → bitskitten-0.5.0}/tests/test_qa_users.py +0 -0
- {bitskitten-0.4.0 → bitskitten-0.5.0}/tests/test_smoke.py +0 -0
- {bitskitten-0.4.0 → bitskitten-0.5.0}/text.py +0 -0
|
@@ -1,38 +1,49 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: bitskitten
|
|
3
|
-
Version: 0.
|
|
4
|
-
Summary: EDA
|
|
3
|
+
Version: 0.5.0
|
|
4
|
+
Summary: Small tools for data work (EDA, plots, sklearn-compatible encoders) and for testing LLM bots (scenario suites, checklist judge, Thompson-sampling scheduler); heavy dependencies only per extra
|
|
5
5
|
Author: Caerno
|
|
6
6
|
License-Expression: Apache-2.0
|
|
7
7
|
Project-URL: Homepage, https://github.com/Caerno/bitskit
|
|
8
|
-
Keywords: eda,pandas,sklearn,kaggle
|
|
8
|
+
Keywords: eda,pandas,sklearn,kaggle,llm,chatbot,testing,thompson-sampling
|
|
9
9
|
Requires-Python: >=3.9
|
|
10
10
|
Description-Content-Type: text/markdown
|
|
11
11
|
License-File: LICENSE
|
|
12
12
|
Requires-Dist: numpy>=1.21
|
|
13
|
-
|
|
14
|
-
Requires-Dist:
|
|
15
|
-
Requires-Dist:
|
|
16
|
-
|
|
17
|
-
Requires-Dist:
|
|
13
|
+
Provides-Extra: ml
|
|
14
|
+
Requires-Dist: pandas>=1.3; extra == "ml"
|
|
15
|
+
Requires-Dist: scikit-learn>=1.0; extra == "ml"
|
|
16
|
+
Provides-Extra: eda
|
|
17
|
+
Requires-Dist: pandas>=1.3; extra == "eda"
|
|
18
|
+
Requires-Dist: matplotlib>=3.4; extra == "eda"
|
|
19
|
+
Requires-Dist: seaborn>=0.11; extra == "eda"
|
|
20
|
+
Requires-Dist: jinja2>=3; extra == "eda"
|
|
21
|
+
Provides-Extra: all
|
|
22
|
+
Requires-Dist: bitskitten[eda,ml]; extra == "all"
|
|
18
23
|
Provides-Extra: test
|
|
19
24
|
Requires-Dist: pytest>=7; extra == "test"
|
|
20
25
|
Dynamic: license-file
|
|
21
26
|
|
|
22
27
|
# bitskitten
|
|
23
28
|
|
|
24
|
-
A small toolbox of things I kept re-typing
|
|
25
|
-
|
|
26
|
-
|
|
29
|
+
A small toolbox of things I kept re-typing: quick dataset reports, a few plots and
|
|
30
|
+
sklearn-compatible encoders for EDA notebooks, and a regression harness for LLM bots
|
|
31
|
+
(scenario suites, checklist judge, Thompson-sampling scheduler).
|
|
27
32
|
|
|
28
33
|
Nothing here is a framework. Each helper is one function or one class you can read in a minute.
|
|
29
34
|
|
|
30
35
|
## Install
|
|
31
36
|
|
|
32
37
|
```bash
|
|
33
|
-
pip install bitskitten
|
|
38
|
+
pip install bitskitten # numpy only: test scheduler, bot regression harness, metric
|
|
39
|
+
pip install 'bitskitten[ml]' # + pandas, scikit-learn: encoders, NanFixer, harmonic_scorer
|
|
40
|
+
pip install 'bitskitten[eda]' # + pandas, matplotlib, seaborn: reports and plots
|
|
41
|
+
pip install 'bitskitten[all]' # everything
|
|
34
42
|
```
|
|
35
43
|
|
|
44
|
+
Each part loads its dependencies only when you use it: `import bitskitten` costs numpy,
|
|
45
|
+
not pandas and scikit-learn. A name whose extra is missing fails with the line to install.
|
|
46
|
+
|
|
36
47
|
The latest commit: `pip install git+https://github.com/Caerno/bitskit.git`.
|
|
37
48
|
On Kaggle / Colab the same lines work in a cell (`!pip install ...`).
|
|
38
49
|
For a kernel with no internet, add
|
|
@@ -43,7 +54,7 @@ as a dataset and install it from disk:
|
|
|
43
54
|
pip install --no-deps /kaggle/input/<your-dataset>/bitskit-main.zip
|
|
44
55
|
```
|
|
45
56
|
|
|
46
|
-
Requires Python ≥ 3.9
|
|
57
|
+
Requires Python ≥ 3.9 and numpy; the rest comes with the extras above.
|
|
47
58
|
|
|
48
59
|
## Quick start
|
|
49
60
|
|
|
@@ -159,8 +170,9 @@ from bitskitten.bandit import ThompsonScheduler
|
|
|
159
170
|
|
|
160
171
|
sched = ThompsonScheduler(["happy_path", "reschedule", "angry_user"],
|
|
161
172
|
threshold=0.9, seed=0)
|
|
162
|
-
|
|
163
|
-
|
|
173
|
+
rows = sched.run(run_scenario, budget=80) # run_scenario(name) -> bool
|
|
174
|
+
# one dict per scenario, worst first: runs, passes, mean, 95 % interval, pass^3, verdict
|
|
175
|
+
print(sched.report()) # the same as a DataFrame, needs pandas
|
|
164
176
|
```
|
|
165
177
|
|
|
166
178
|
For suites where one run of a scenario is a coin flip (LLM bots, anything
|
|
@@ -183,7 +195,8 @@ suite = Suite(scenarios, # Scenario.from_dict(
|
|
|
183
195
|
gates={"collecting_states": {"collecting_date"}},
|
|
184
196
|
judge=Judge(model, Checklist.from_dicts(items))) # model(prompt) -> str, any provider
|
|
185
197
|
result = suite.run(budget=80, threshold=0.9, max_runs=40)
|
|
186
|
-
print(result.
|
|
198
|
+
print(result.rows) # per scenario: runs, mean, 95 % interval, pass^3, verdict
|
|
199
|
+
# result.report: the same as a DataFrame, needs pandas
|
|
187
200
|
print(format_report(result.failures)) # failed runs grouped by what failed
|
|
188
201
|
```
|
|
189
202
|
|
|
@@ -199,7 +212,8 @@ decided scenarios retire, the loop stops when nothing is left to learn.
|
|
|
199
212
|
quietly answering them. `MarkovUsers` varies wording from real utterances at
|
|
200
213
|
zero model cost. `CallableUser` wraps any model.
|
|
201
214
|
- **Judge.** Repeated judging merges binary items by majority, not by mean.
|
|
202
|
-
`
|
|
215
|
+
`item_agreement_rows(judged, human)` gives per-item kappa against your own labels
|
|
216
|
+
(`item_agreement` — the same as a DataFrame)
|
|
203
217
|
— check it before trusting an item; `pick_threshold` picks the score cut.
|
|
204
218
|
- **Cost of a verdict.** Proving "passes at least 90 %" at 95 % takes 35 clean
|
|
205
219
|
runs in a row; that is the threshold's price, not the scheduler's. A scenario
|
|
@@ -263,7 +277,7 @@ and satisfies the condition.
|
|
|
263
277
|
## Development
|
|
264
278
|
|
|
265
279
|
```bash
|
|
266
|
-
pip install
|
|
280
|
+
pip install '.[all,test]'
|
|
267
281
|
pytest
|
|
268
282
|
```
|
|
269
283
|
|
|
@@ -275,5 +289,5 @@ gets in:
|
|
|
275
289
|
|
|
276
290
|
```bash
|
|
277
291
|
git archive --format=zip -o download/bitskitten.zip HEAD \
|
|
278
|
-
__init__.py bandit.py classes.py input.py metrics.py output.py text.py qa
|
|
292
|
+
__init__.py _deps.py bandit.py classes.py input.py metrics.py output.py text.py qa
|
|
279
293
|
```
|
|
@@ -1,38 +1,23 @@
|
|
|
1
|
-
Metadata-Version: 2.4
|
|
2
|
-
Name: bitskitten
|
|
3
|
-
Version: 0.4.0
|
|
4
|
-
Summary: EDA reports, plots and sklearn-compatible encoders
|
|
5
|
-
Author: Caerno
|
|
6
|
-
License-Expression: Apache-2.0
|
|
7
|
-
Project-URL: Homepage, https://github.com/Caerno/bitskit
|
|
8
|
-
Keywords: eda,pandas,sklearn,kaggle
|
|
9
|
-
Requires-Python: >=3.9
|
|
10
|
-
Description-Content-Type: text/markdown
|
|
11
|
-
License-File: LICENSE
|
|
12
|
-
Requires-Dist: numpy>=1.21
|
|
13
|
-
Requires-Dist: pandas>=1.3
|
|
14
|
-
Requires-Dist: scikit-learn>=1.0
|
|
15
|
-
Requires-Dist: matplotlib>=3.4
|
|
16
|
-
Requires-Dist: seaborn>=0.11
|
|
17
|
-
Requires-Dist: jinja2>=3
|
|
18
|
-
Provides-Extra: test
|
|
19
|
-
Requires-Dist: pytest>=7; extra == "test"
|
|
20
|
-
Dynamic: license-file
|
|
21
|
-
|
|
22
1
|
# bitskitten
|
|
23
2
|
|
|
24
|
-
A small toolbox of things I kept re-typing
|
|
25
|
-
|
|
26
|
-
|
|
3
|
+
A small toolbox of things I kept re-typing: quick dataset reports, a few plots and
|
|
4
|
+
sklearn-compatible encoders for EDA notebooks, and a regression harness for LLM bots
|
|
5
|
+
(scenario suites, checklist judge, Thompson-sampling scheduler).
|
|
27
6
|
|
|
28
7
|
Nothing here is a framework. Each helper is one function or one class you can read in a minute.
|
|
29
8
|
|
|
30
9
|
## Install
|
|
31
10
|
|
|
32
11
|
```bash
|
|
33
|
-
pip install bitskitten
|
|
12
|
+
pip install bitskitten # numpy only: test scheduler, bot regression harness, metric
|
|
13
|
+
pip install 'bitskitten[ml]' # + pandas, scikit-learn: encoders, NanFixer, harmonic_scorer
|
|
14
|
+
pip install 'bitskitten[eda]' # + pandas, matplotlib, seaborn: reports and plots
|
|
15
|
+
pip install 'bitskitten[all]' # everything
|
|
34
16
|
```
|
|
35
17
|
|
|
18
|
+
Each part loads its dependencies only when you use it: `import bitskitten` costs numpy,
|
|
19
|
+
not pandas and scikit-learn. A name whose extra is missing fails with the line to install.
|
|
20
|
+
|
|
36
21
|
The latest commit: `pip install git+https://github.com/Caerno/bitskit.git`.
|
|
37
22
|
On Kaggle / Colab the same lines work in a cell (`!pip install ...`).
|
|
38
23
|
For a kernel with no internet, add
|
|
@@ -43,7 +28,7 @@ as a dataset and install it from disk:
|
|
|
43
28
|
pip install --no-deps /kaggle/input/<your-dataset>/bitskit-main.zip
|
|
44
29
|
```
|
|
45
30
|
|
|
46
|
-
Requires Python ≥ 3.9
|
|
31
|
+
Requires Python ≥ 3.9 and numpy; the rest comes with the extras above.
|
|
47
32
|
|
|
48
33
|
## Quick start
|
|
49
34
|
|
|
@@ -159,8 +144,9 @@ from bitskitten.bandit import ThompsonScheduler
|
|
|
159
144
|
|
|
160
145
|
sched = ThompsonScheduler(["happy_path", "reschedule", "angry_user"],
|
|
161
146
|
threshold=0.9, seed=0)
|
|
162
|
-
|
|
163
|
-
|
|
147
|
+
rows = sched.run(run_scenario, budget=80) # run_scenario(name) -> bool
|
|
148
|
+
# one dict per scenario, worst first: runs, passes, mean, 95 % interval, pass^3, verdict
|
|
149
|
+
print(sched.report()) # the same as a DataFrame, needs pandas
|
|
164
150
|
```
|
|
165
151
|
|
|
166
152
|
For suites where one run of a scenario is a coin flip (LLM bots, anything
|
|
@@ -183,7 +169,8 @@ suite = Suite(scenarios, # Scenario.from_dict(
|
|
|
183
169
|
gates={"collecting_states": {"collecting_date"}},
|
|
184
170
|
judge=Judge(model, Checklist.from_dicts(items))) # model(prompt) -> str, any provider
|
|
185
171
|
result = suite.run(budget=80, threshold=0.9, max_runs=40)
|
|
186
|
-
print(result.
|
|
172
|
+
print(result.rows) # per scenario: runs, mean, 95 % interval, pass^3, verdict
|
|
173
|
+
# result.report: the same as a DataFrame, needs pandas
|
|
187
174
|
print(format_report(result.failures)) # failed runs grouped by what failed
|
|
188
175
|
```
|
|
189
176
|
|
|
@@ -199,7 +186,8 @@ decided scenarios retire, the loop stops when nothing is left to learn.
|
|
|
199
186
|
quietly answering them. `MarkovUsers` varies wording from real utterances at
|
|
200
187
|
zero model cost. `CallableUser` wraps any model.
|
|
201
188
|
- **Judge.** Repeated judging merges binary items by majority, not by mean.
|
|
202
|
-
`
|
|
189
|
+
`item_agreement_rows(judged, human)` gives per-item kappa against your own labels
|
|
190
|
+
(`item_agreement` — the same as a DataFrame)
|
|
203
191
|
— check it before trusting an item; `pick_threshold` picks the score cut.
|
|
204
192
|
- **Cost of a verdict.** Proving "passes at least 90 %" at 95 % takes 35 clean
|
|
205
193
|
runs in a row; that is the threshold's price, not the scheduler's. A scenario
|
|
@@ -263,7 +251,7 @@ and satisfies the condition.
|
|
|
263
251
|
## Development
|
|
264
252
|
|
|
265
253
|
```bash
|
|
266
|
-
pip install
|
|
254
|
+
pip install '.[all,test]'
|
|
267
255
|
pytest
|
|
268
256
|
```
|
|
269
257
|
|
|
@@ -275,5 +263,5 @@ gets in:
|
|
|
275
263
|
|
|
276
264
|
```bash
|
|
277
265
|
git archive --format=zip -o download/bitskitten.zip HEAD \
|
|
278
|
-
__init__.py bandit.py classes.py input.py metrics.py output.py text.py qa
|
|
266
|
+
__init__.py _deps.py bandit.py classes.py input.py metrics.py output.py text.py qa
|
|
279
267
|
```
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
'''bitskitten - small tools for data work and for LLM bots and agents.
|
|
2
|
+
|
|
3
|
+
from bitskitten import imperfection, NanFixer, Digitalize # pip install 'bitskitten[eda,ml]'
|
|
4
|
+
from bitskitten import ThompsonScheduler # numpy only
|
|
5
|
+
from bitskitten.qa import Scenario, Suite # numpy only
|
|
6
|
+
|
|
7
|
+
One distribution, independent parts: a name is imported only when you use it, so `import bitskitten` and the
|
|
8
|
+
light parts (qa, bandit, metrics, input) do not load pandas, scikit-learn or matplotlib. A part whose extra is
|
|
9
|
+
not installed says which one to install. Submodules stay importable on their own (`from bitskitten import output`).
|
|
10
|
+
'''
|
|
11
|
+
import importlib
|
|
12
|
+
|
|
13
|
+
from ._deps import hint as _hint
|
|
14
|
+
|
|
15
|
+
__version__ = "0.5.0"
|
|
16
|
+
|
|
17
|
+
_EXPORTS = {
|
|
18
|
+
"ThompsonScheduler": "bandit", "pass_power": "bandit",
|
|
19
|
+
"Digitalize": "classes", "Encoder": "classes", "FeatureTrans": "classes", "NanFixer": "classes",
|
|
20
|
+
"SlowPolyLinearReg": "classes",
|
|
21
|
+
"number": "input",
|
|
22
|
+
"harmonic_from_confusion": "metrics", "harmonic_score": "metrics", "harmonic_scorer": "metrics",
|
|
23
|
+
"text_imperfection": "text",
|
|
24
|
+
"imperfection": "output", "informer": "output", "informer_print": "output", "multicolumn": "output",
|
|
25
|
+
"plot_conf_map": "output", "plot_some_scatters": "output", "img_squeeze": "output", "img_framaker": "output",
|
|
26
|
+
}
|
|
27
|
+
_SUBMODULES = {"bandit", "classes", "input", "metrics", "text", "output", "qa"}
|
|
28
|
+
|
|
29
|
+
__all__ = list(_EXPORTS)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
_MODULE_EXTRA = {"classes": "ml", "metrics": "ml", "output": "eda", "text": "eda"}
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def __getattr__(name):
|
|
36
|
+
mod = _EXPORTS.get(name) or (name if name in _SUBMODULES else None)
|
|
37
|
+
if mod is None:
|
|
38
|
+
raise AttributeError(f"module 'bitskitten' has no attribute {name!r}")
|
|
39
|
+
try:
|
|
40
|
+
m = importlib.import_module(f".{mod}", __name__)
|
|
41
|
+
except ModuleNotFoundError as e:
|
|
42
|
+
if e.name and e.name.split(".")[0] != __name__:
|
|
43
|
+
raise ImportError(_hint(e.name, f"bitskitten.{name}", _MODULE_EXTRA.get(mod))) from e
|
|
44
|
+
raise
|
|
45
|
+
value = m if name == mod else getattr(m, name)
|
|
46
|
+
globals()[name] = value
|
|
47
|
+
return value
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def __dir__():
|
|
51
|
+
return sorted(set(globals()) | set(_EXPORTS) | _SUBMODULES)
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
"""Optional dependencies: which extra brings which package, and a clear error when it is missing."""
|
|
2
|
+
import importlib
|
|
3
|
+
|
|
4
|
+
EXTRA = {"pandas": "ml", "sklearn": "ml", "matplotlib": "eda", "seaborn": "eda", "jinja2": "eda",
|
|
5
|
+
"onnxruntime": "search", "tokenizers": "search", "yaml": "nollm", "Stemmer": "nollm"}
|
|
6
|
+
PIP = {"sklearn": "scikit-learn", "yaml": "PyYAML", "Stemmer": "PyStemmer"}
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def hint(missing, what="this", extra=None):
|
|
10
|
+
top = (missing or "").split(".")[0]
|
|
11
|
+
return (f"{what} needs {PIP.get(top, top)}: pip install 'bitskitten[{extra or EXTRA.get(top, 'all')}]' "
|
|
12
|
+
f"(or pip install {PIP.get(top, top)})")
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def need(module, what="this"):
|
|
16
|
+
"""import an optional module or raise ImportError naming the extra to install"""
|
|
17
|
+
try:
|
|
18
|
+
return importlib.import_module(module)
|
|
19
|
+
except ModuleNotFoundError as e:
|
|
20
|
+
raise ImportError(hint(e.name or module, what)) from e
|
|
@@ -32,7 +32,6 @@ from dataclasses import dataclass, field
|
|
|
32
32
|
from typing import Dict, Iterable, List, Optional, Tuple
|
|
33
33
|
|
|
34
34
|
import numpy as np
|
|
35
|
-
import pandas as pd
|
|
36
35
|
|
|
37
36
|
__all__ = ["Arm", "ThompsonScheduler", "pass_power", "beta_interval"]
|
|
38
37
|
|
|
@@ -231,9 +230,10 @@ class ThompsonScheduler:
|
|
|
231
230
|
|
|
232
231
|
# -- reporting ----------------------------------------------------------
|
|
233
232
|
|
|
234
|
-
def
|
|
235
|
-
"""One
|
|
236
|
-
pass^k and the verdict against the threshold. Sorted worst first.
|
|
233
|
+
def rows(self, *, k: int = 3) -> List[dict]:
|
|
234
|
+
"""One dict per scenario: runs, passes, posterior mean, interval,
|
|
235
|
+
pass^k and the verdict against the threshold. Sorted worst first.
|
|
236
|
+
Plain Python: no pandas needed."""
|
|
237
237
|
rows = []
|
|
238
238
|
for name, arm in self.arms.items():
|
|
239
239
|
lo, hi = self.interval(name)
|
|
@@ -247,15 +247,19 @@ class ThompsonScheduler:
|
|
|
247
247
|
f"pass^{k}": pass_power(arm.alpha, arm.beta, k),
|
|
248
248
|
"verdict": self.status(name),
|
|
249
249
|
})
|
|
250
|
-
return (
|
|
251
|
-
.sort_values(["mean", "runs"])
|
|
252
|
-
.reset_index(drop=True))
|
|
250
|
+
return sorted(rows, key=lambda r: (r["mean"], r["runs"]))
|
|
253
251
|
|
|
254
|
-
def
|
|
252
|
+
def report(self, *, k: int = 3):
|
|
253
|
+
"""`rows()` as a pandas DataFrame (needs pandas)."""
|
|
254
|
+
from ._deps import need
|
|
255
|
+
return need("pandas", "ThompsonScheduler.report").DataFrame(self.rows(k=k))
|
|
256
|
+
|
|
257
|
+
def run(self, run_once, *, budget: int, k: int = 3):
|
|
255
258
|
"""Drive the loop: pick -> run_once(name) -> update, until `done()`.
|
|
256
259
|
|
|
257
260
|
`run_once(name)` must return a truthy value for a pass. Returns the
|
|
258
|
-
final
|
|
261
|
+
final `rows(k)`, worst scenario first; `report(k)` gives the same as a
|
|
262
|
+
DataFrame. Raising inside `run_once` aborts the loop; the state
|
|
259
263
|
collected so far stays on the scheduler.
|
|
260
264
|
"""
|
|
261
265
|
if budget <= 0:
|
|
@@ -263,4 +267,4 @@ class ThompsonScheduler:
|
|
|
263
267
|
while not self.done(budget=budget):
|
|
264
268
|
name = self.pick()
|
|
265
269
|
self.update(name, bool(run_once(name)))
|
|
266
|
-
return self.
|
|
270
|
+
return self.rows(k=k)
|
|
@@ -1,17 +1,49 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: bitskitten
|
|
3
|
+
Version: 0.5.0
|
|
4
|
+
Summary: Small tools for data work (EDA, plots, sklearn-compatible encoders) and for testing LLM bots (scenario suites, checklist judge, Thompson-sampling scheduler); heavy dependencies only per extra
|
|
5
|
+
Author: Caerno
|
|
6
|
+
License-Expression: Apache-2.0
|
|
7
|
+
Project-URL: Homepage, https://github.com/Caerno/bitskit
|
|
8
|
+
Keywords: eda,pandas,sklearn,kaggle,llm,chatbot,testing,thompson-sampling
|
|
9
|
+
Requires-Python: >=3.9
|
|
10
|
+
Description-Content-Type: text/markdown
|
|
11
|
+
License-File: LICENSE
|
|
12
|
+
Requires-Dist: numpy>=1.21
|
|
13
|
+
Provides-Extra: ml
|
|
14
|
+
Requires-Dist: pandas>=1.3; extra == "ml"
|
|
15
|
+
Requires-Dist: scikit-learn>=1.0; extra == "ml"
|
|
16
|
+
Provides-Extra: eda
|
|
17
|
+
Requires-Dist: pandas>=1.3; extra == "eda"
|
|
18
|
+
Requires-Dist: matplotlib>=3.4; extra == "eda"
|
|
19
|
+
Requires-Dist: seaborn>=0.11; extra == "eda"
|
|
20
|
+
Requires-Dist: jinja2>=3; extra == "eda"
|
|
21
|
+
Provides-Extra: all
|
|
22
|
+
Requires-Dist: bitskitten[eda,ml]; extra == "all"
|
|
23
|
+
Provides-Extra: test
|
|
24
|
+
Requires-Dist: pytest>=7; extra == "test"
|
|
25
|
+
Dynamic: license-file
|
|
26
|
+
|
|
1
27
|
# bitskitten
|
|
2
28
|
|
|
3
|
-
A small toolbox of things I kept re-typing
|
|
4
|
-
|
|
5
|
-
|
|
29
|
+
A small toolbox of things I kept re-typing: quick dataset reports, a few plots and
|
|
30
|
+
sklearn-compatible encoders for EDA notebooks, and a regression harness for LLM bots
|
|
31
|
+
(scenario suites, checklist judge, Thompson-sampling scheduler).
|
|
6
32
|
|
|
7
33
|
Nothing here is a framework. Each helper is one function or one class you can read in a minute.
|
|
8
34
|
|
|
9
35
|
## Install
|
|
10
36
|
|
|
11
37
|
```bash
|
|
12
|
-
pip install bitskitten
|
|
38
|
+
pip install bitskitten # numpy only: test scheduler, bot regression harness, metric
|
|
39
|
+
pip install 'bitskitten[ml]' # + pandas, scikit-learn: encoders, NanFixer, harmonic_scorer
|
|
40
|
+
pip install 'bitskitten[eda]' # + pandas, matplotlib, seaborn: reports and plots
|
|
41
|
+
pip install 'bitskitten[all]' # everything
|
|
13
42
|
```
|
|
14
43
|
|
|
44
|
+
Each part loads its dependencies only when you use it: `import bitskitten` costs numpy,
|
|
45
|
+
not pandas and scikit-learn. A name whose extra is missing fails with the line to install.
|
|
46
|
+
|
|
15
47
|
The latest commit: `pip install git+https://github.com/Caerno/bitskit.git`.
|
|
16
48
|
On Kaggle / Colab the same lines work in a cell (`!pip install ...`).
|
|
17
49
|
For a kernel with no internet, add
|
|
@@ -22,7 +54,7 @@ as a dataset and install it from disk:
|
|
|
22
54
|
pip install --no-deps /kaggle/input/<your-dataset>/bitskit-main.zip
|
|
23
55
|
```
|
|
24
56
|
|
|
25
|
-
Requires Python ≥ 3.9
|
|
57
|
+
Requires Python ≥ 3.9 and numpy; the rest comes with the extras above.
|
|
26
58
|
|
|
27
59
|
## Quick start
|
|
28
60
|
|
|
@@ -138,8 +170,9 @@ from bitskitten.bandit import ThompsonScheduler
|
|
|
138
170
|
|
|
139
171
|
sched = ThompsonScheduler(["happy_path", "reschedule", "angry_user"],
|
|
140
172
|
threshold=0.9, seed=0)
|
|
141
|
-
|
|
142
|
-
|
|
173
|
+
rows = sched.run(run_scenario, budget=80) # run_scenario(name) -> bool
|
|
174
|
+
# one dict per scenario, worst first: runs, passes, mean, 95 % interval, pass^3, verdict
|
|
175
|
+
print(sched.report()) # the same as a DataFrame, needs pandas
|
|
143
176
|
```
|
|
144
177
|
|
|
145
178
|
For suites where one run of a scenario is a coin flip (LLM bots, anything
|
|
@@ -162,7 +195,8 @@ suite = Suite(scenarios, # Scenario.from_dict(
|
|
|
162
195
|
gates={"collecting_states": {"collecting_date"}},
|
|
163
196
|
judge=Judge(model, Checklist.from_dicts(items))) # model(prompt) -> str, any provider
|
|
164
197
|
result = suite.run(budget=80, threshold=0.9, max_runs=40)
|
|
165
|
-
print(result.
|
|
198
|
+
print(result.rows) # per scenario: runs, mean, 95 % interval, pass^3, verdict
|
|
199
|
+
# result.report: the same as a DataFrame, needs pandas
|
|
166
200
|
print(format_report(result.failures)) # failed runs grouped by what failed
|
|
167
201
|
```
|
|
168
202
|
|
|
@@ -178,7 +212,8 @@ decided scenarios retire, the loop stops when nothing is left to learn.
|
|
|
178
212
|
quietly answering them. `MarkovUsers` varies wording from real utterances at
|
|
179
213
|
zero model cost. `CallableUser` wraps any model.
|
|
180
214
|
- **Judge.** Repeated judging merges binary items by majority, not by mean.
|
|
181
|
-
`
|
|
215
|
+
`item_agreement_rows(judged, human)` gives per-item kappa against your own labels
|
|
216
|
+
(`item_agreement` — the same as a DataFrame)
|
|
182
217
|
— check it before trusting an item; `pick_threshold` picks the score cut.
|
|
183
218
|
- **Cost of a verdict.** Proving "passes at least 90 %" at 95 % takes 35 clean
|
|
184
219
|
runs in a row; that is the threshold's price, not the scheduler's. A scenario
|
|
@@ -242,7 +277,7 @@ and satisfies the condition.
|
|
|
242
277
|
## Development
|
|
243
278
|
|
|
244
279
|
```bash
|
|
245
|
-
pip install
|
|
280
|
+
pip install '.[all,test]'
|
|
246
281
|
pytest
|
|
247
282
|
```
|
|
248
283
|
|
|
@@ -254,5 +289,5 @@ gets in:
|
|
|
254
289
|
|
|
255
290
|
```bash
|
|
256
291
|
git archive --format=zip -o download/bitskitten.zip HEAD \
|
|
257
|
-
__init__.py bandit.py classes.py input.py metrics.py output.py text.py qa
|
|
292
|
+
__init__.py _deps.py bandit.py classes.py input.py metrics.py output.py text.py qa
|
|
258
293
|
```
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
LICENSE
|
|
2
2
|
README.md
|
|
3
3
|
__init__.py
|
|
4
|
+
_deps.py
|
|
4
5
|
bandit.py
|
|
5
6
|
classes.py
|
|
6
7
|
input.py
|
|
@@ -9,6 +10,7 @@ output.py
|
|
|
9
10
|
pyproject.toml
|
|
10
11
|
text.py
|
|
11
12
|
./__init__.py
|
|
13
|
+
./_deps.py
|
|
12
14
|
./bandit.py
|
|
13
15
|
./classes.py
|
|
14
16
|
./input.py
|
|
@@ -28,6 +30,7 @@ qa/runner.py
|
|
|
28
30
|
qa/scenario.py
|
|
29
31
|
qa/users.py
|
|
30
32
|
tests/test_bandit.py
|
|
33
|
+
tests/test_boundary.py
|
|
31
34
|
tests/test_fit_time.py
|
|
32
35
|
tests/test_qa.py
|
|
33
36
|
tests/test_qa_judge.py
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
"""Class-agnostic classification quality as plain functions (and a scorer). numpy only; `harmonic_scorer`
|
|
2
|
+
loads scikit-learn when first used."""
|
|
3
|
+
import numpy as np
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
def confusion(y_true, y_pred, labels=None):
|
|
7
|
+
'''Square confusion matrix, rows = true class, columns = predicted, as `sklearn.metrics.confusion_matrix`:
|
|
8
|
+
classes = sorted union of both, or `labels` in the given order (samples with other labels are not counted).'''
|
|
9
|
+
yt, yp = np.asarray(y_true).ravel(), np.asarray(y_pred).ravel()
|
|
10
|
+
if yt.shape != yp.shape:
|
|
11
|
+
raise ValueError(f"y_true and y_pred differ in length: {yt.shape[0]} and {yp.shape[0]}")
|
|
12
|
+
if labels is None:
|
|
13
|
+
labs, inv = np.unique(np.concatenate([yt, yp]), return_inverse=True)
|
|
14
|
+
q, n = len(labs), len(yt)
|
|
15
|
+
inv = inv.ravel()
|
|
16
|
+
return np.bincount(inv[:n] * q + inv[n:], minlength=q * q).reshape(q, q)
|
|
17
|
+
labs = list(np.asarray(labels).ravel().tolist())
|
|
18
|
+
if not labs:
|
|
19
|
+
raise ValueError("labels is empty")
|
|
20
|
+
idx = {v: i for i, v in enumerate(labs)}
|
|
21
|
+
i = np.array([idx.get(v, -1) for v in yt.tolist()]); j = np.array([idx.get(v, -1) for v in yp.tolist()])
|
|
22
|
+
ok = (i >= 0) & (j >= 0)
|
|
23
|
+
q = len(labs)
|
|
24
|
+
return np.bincount(i[ok] * q + j[ok], minlength=q * q).reshape(q, q)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def harmonic_from_confusion(conf):
|
|
28
|
+
'''(harmonic mean of every per-class precision and recall, precision[], recall[]) from a square confusion matrix.
|
|
29
|
+
|
|
30
|
+
No class is "the positive one": the mean runs over all 2q numbers, so one class that is
|
|
31
|
+
never predicted (precision 0) or never recovered (recall 0) pulls the score to 0.
|
|
32
|
+
'''
|
|
33
|
+
conf = np.asarray(conf, dtype=float)
|
|
34
|
+
q = conf.shape[0]
|
|
35
|
+
conf = conf.reshape(q, q)
|
|
36
|
+
hits = np.diag(conf)
|
|
37
|
+
with np.errstate(divide="ignore", invalid="ignore"):
|
|
38
|
+
precision = np.where(conf.sum(axis=0) > 0, hits / conf.sum(axis=0), 0.0)
|
|
39
|
+
recall = np.where(conf.sum(axis=1) > 0, hits / conf.sum(axis=1), 0.0)
|
|
40
|
+
rates = np.r_[precision, recall]
|
|
41
|
+
if (rates <= 0).any():
|
|
42
|
+
hm = 0.0
|
|
43
|
+
else:
|
|
44
|
+
hm = len(rates) / np.sum(1.0 / rates)
|
|
45
|
+
return float(hm), precision, recall
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def harmonic_score(y_true, y_pred, labels=None):
|
|
49
|
+
'''Harmonic mean of all per-class precisions and recalls; 1.0 = perfect, 0.0 if any class is lost.
|
|
50
|
+
|
|
51
|
+
`labels` fixes the class set (as in `confusion_matrix`); without it classes absent from both
|
|
52
|
+
`y_true` and `y_pred` are not counted.
|
|
53
|
+
'''
|
|
54
|
+
return harmonic_from_confusion(confusion(y_true, y_pred, labels=labels))[0]
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def __getattr__(name):
|
|
59
|
+
if name == "harmonic_scorer": # a scikit-learn scorer: built on first use, so the module stays numpy-only
|
|
60
|
+
from ._deps import need
|
|
61
|
+
scorer = need("sklearn.metrics", "harmonic_scorer").make_scorer(harmonic_score)
|
|
62
|
+
globals()[name] = scorer
|
|
63
|
+
return scorer
|
|
64
|
+
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
|
|
@@ -4,23 +4,19 @@ build-backend = "setuptools.build_meta"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "bitskitten"
|
|
7
|
-
version = "0.
|
|
8
|
-
description = "EDA
|
|
7
|
+
version = "0.5.0"
|
|
8
|
+
description = "Small tools for data work (EDA, plots, sklearn-compatible encoders) and for testing LLM bots (scenario suites, checklist judge, Thompson-sampling scheduler); heavy dependencies only per extra"
|
|
9
9
|
readme = "README.md"
|
|
10
10
|
requires-python = ">=3.9"
|
|
11
11
|
license = "Apache-2.0"
|
|
12
12
|
authors = [{ name = "Caerno" }]
|
|
13
|
-
keywords = ["eda", "pandas", "sklearn", "kaggle"]
|
|
14
|
-
dependencies = [
|
|
15
|
-
"numpy>=1.21",
|
|
16
|
-
"pandas>=1.3",
|
|
17
|
-
"scikit-learn>=1.0",
|
|
18
|
-
"matplotlib>=3.4",
|
|
19
|
-
"seaborn>=0.11",
|
|
20
|
-
"jinja2>=3", # multicolumn() renders through DataFrame.style
|
|
21
|
-
]
|
|
13
|
+
keywords = ["eda", "pandas", "sklearn", "kaggle", "llm", "chatbot", "testing", "thompson-sampling"]
|
|
14
|
+
dependencies = ["numpy>=1.21"] # qa, bandit, metrics, input; the rest per extra
|
|
22
15
|
|
|
23
16
|
[project.optional-dependencies]
|
|
17
|
+
ml = ["pandas>=1.3", "scikit-learn>=1.0"] # encoders, harmonic_scorer
|
|
18
|
+
eda = ["pandas>=1.3", "matplotlib>=3.4", "seaborn>=0.11", "jinja2>=3"] # reports, plots (multicolumn renders through DataFrame.style)
|
|
19
|
+
all = ["bitskitten[ml,eda]"]
|
|
24
20
|
test = ["pytest>=7"]
|
|
25
21
|
|
|
26
22
|
[project.urls]
|
|
@@ -37,7 +37,7 @@ from .checks import (
|
|
|
37
37
|
)
|
|
38
38
|
from .failures import FailureGroup, FailureReport, classify_items, format_report, group_failures
|
|
39
39
|
from .users import CallableUser, MarkovUser, MarkovUsers, ScriptedUser, TopicClassifier
|
|
40
|
-
from .judge import Checklist, ChecklistItem, Judge, item_agreement, pick_threshold
|
|
40
|
+
from .judge import Checklist, ChecklistItem, Judge, item_agreement, item_agreement_rows, pick_threshold
|
|
41
41
|
from .runner import BotStep, Suite, SuiteResult, simulate
|
|
42
42
|
|
|
43
43
|
__all__ = [
|
|
@@ -47,6 +47,6 @@ __all__ = [
|
|
|
47
47
|
"check_grounded_numbers", "check_script_adherence",
|
|
48
48
|
"FailureGroup", "FailureReport", "classify_items", "group_failures", "format_report",
|
|
49
49
|
"ScriptedUser", "TopicClassifier", "MarkovUsers", "MarkovUser", "CallableUser",
|
|
50
|
-
"Checklist", "ChecklistItem", "Judge", "item_agreement", "pick_threshold",
|
|
50
|
+
"Checklist", "ChecklistItem", "Judge", "item_agreement", "item_agreement_rows", "pick_threshold",
|
|
51
51
|
"BotStep", "Suite", "SuiteResult", "simulate",
|
|
52
52
|
]
|
|
@@ -28,14 +28,13 @@ import statistics
|
|
|
28
28
|
from dataclasses import dataclass, field
|
|
29
29
|
from typing import Any, Callable, Dict, Iterable, List, Mapping, Optional, Sequence, Tuple
|
|
30
30
|
|
|
31
|
-
import pandas as pd
|
|
32
31
|
|
|
33
32
|
from .scenario import Run, Scenario, Turn
|
|
34
33
|
|
|
35
34
|
__all__ = [
|
|
36
35
|
"ChecklistItem", "Checklist", "Judge", "format_transcript", "build_prompt",
|
|
37
36
|
"parse_verdict", "total_score", "merge_verdicts", "verbosity",
|
|
38
|
-
"cohen_kappa", "item_agreement", "pick_threshold",
|
|
37
|
+
"cohen_kappa", "item_agreement", "item_agreement_rows", "pick_threshold",
|
|
39
38
|
]
|
|
40
39
|
|
|
41
40
|
|
|
@@ -273,11 +272,21 @@ def cohen_kappa(a: Sequence[int], b: Sequence[int]) -> float:
|
|
|
273
272
|
|
|
274
273
|
|
|
275
274
|
def item_agreement(judged: Sequence[Mapping[str, Any]], human: Sequence[Mapping[str, int]],
|
|
276
|
-
checklist: Optional[Checklist] = None)
|
|
275
|
+
checklist: Optional[Checklist] = None):
|
|
276
|
+
"""`item_agreement_rows` as a pandas DataFrame (needs pandas)."""
|
|
277
|
+
from .._deps import need
|
|
278
|
+
return need("pandas", "item_agreement").DataFrame(
|
|
279
|
+
item_agreement_rows(judged, human, checklist),
|
|
280
|
+
columns=["item", "n", "agree", "kappa", "judge_pass_rate", "human_pass_rate"])
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
def item_agreement_rows(judged: Sequence[Mapping[str, Any]], human: Sequence[Mapping[str, int]],
|
|
284
|
+
checklist: Optional[Checklist] = None) -> List[Dict[str, Any]]:
|
|
277
285
|
"""Per binary item: how often the judge agrees with a human on the same
|
|
278
286
|
transcripts. ``judged[i]`` is a verdict's ``items`` mapping (or the verdict
|
|
279
287
|
itself), ``human[i]`` maps item id -> 0/1. Pairs where either side is
|
|
280
|
-
missing or null are skipped.
|
|
288
|
+
missing or null are skipped. One dict per item, worst kappa first (no
|
|
289
|
+
kappa first of all)."""
|
|
281
290
|
if len(judged) != len(human):
|
|
282
291
|
raise ValueError("judged and human must be aligned per transcript")
|
|
283
292
|
ids = [i.id for i in checklist.items if i.type == "binary"] if checklist else \
|
|
@@ -299,8 +308,7 @@ def item_agreement(judged: Sequence[Mapping[str, Any]], human: Sequence[Mapping[
|
|
|
299
308
|
"agree": sum(x == y for x, y in zip(a, b)) / len(a),
|
|
300
309
|
"kappa": cohen_kappa(a, b),
|
|
301
310
|
"judge_pass_rate": sum(a) / len(a), "human_pass_rate": sum(b) / len(b)})
|
|
302
|
-
|
|
303
|
-
return df.sort_values("kappa", na_position="first").reset_index(drop=True)
|
|
311
|
+
return sorted(rows, key=lambda r: (not math.isnan(r["kappa"]), 0.0 if math.isnan(r["kappa"]) else r["kappa"]))
|
|
304
312
|
|
|
305
313
|
|
|
306
314
|
def pick_threshold(scores: Sequence[float], human_pass: Sequence[bool]) -> Tuple[float, float]:
|
|
@@ -23,7 +23,6 @@ from __future__ import annotations
|
|
|
23
23
|
from dataclasses import dataclass, field
|
|
24
24
|
from typing import Any, Callable, Dict, List, Mapping, Optional, Sequence, Union
|
|
25
25
|
|
|
26
|
-
import pandas as pd
|
|
27
26
|
|
|
28
27
|
from ..bandit import ThompsonScheduler
|
|
29
28
|
from .checks import check_run, validate_run
|
|
@@ -88,11 +87,17 @@ class Outcome:
|
|
|
88
87
|
|
|
89
88
|
@dataclass
|
|
90
89
|
class SuiteResult:
|
|
91
|
-
|
|
90
|
+
rows: List[Dict[str, Any]] # ThompsonScheduler.rows(): one dict per scenario, worst first
|
|
92
91
|
outcomes: List[Outcome]
|
|
93
92
|
failures: FailureReport
|
|
94
93
|
spent: int
|
|
95
94
|
|
|
95
|
+
@property
|
|
96
|
+
def report(self):
|
|
97
|
+
"""`rows` as a pandas DataFrame (needs pandas)."""
|
|
98
|
+
from .._deps import need
|
|
99
|
+
return need("pandas", "SuiteResult.report").DataFrame(self.rows)
|
|
100
|
+
|
|
96
101
|
|
|
97
102
|
@dataclass
|
|
98
103
|
class Suite:
|
|
@@ -158,7 +163,7 @@ class Suite:
|
|
|
158
163
|
spent += 1
|
|
159
164
|
if out.passed is not None:
|
|
160
165
|
sched.update(sid, out.passed)
|
|
161
|
-
return SuiteResult(sched.
|
|
166
|
+
return SuiteResult(sched.rows(), outcomes, self.failure_report(outcomes), spent)
|
|
162
167
|
|
|
163
168
|
def failure_report(self, outcomes: Sequence[Outcome]) -> FailureReport:
|
|
164
169
|
gate_items = {k for o in outcomes for k in (o.run.items or {}) if k.startswith("gate:")}
|
|
@@ -83,9 +83,9 @@ def test_decided_scenario_is_retired_so_others_get_budget():
|
|
|
83
83
|
rep = s.run(_coin(rates), budget=10_000)
|
|
84
84
|
assert s.total_runs < 60
|
|
85
85
|
assert s.arms["bad"].runs == 3 # min_runs, then retired
|
|
86
|
-
verdict =
|
|
86
|
+
verdict = {r["scenario"]: r["verdict"] for r in rep}
|
|
87
87
|
assert verdict == {"good": "pass", "bad": "fail"}
|
|
88
|
-
assert
|
|
88
|
+
assert [r["scenario"] for r in rep] == ["bad", "good"] # worst first
|
|
89
89
|
assert s.pick() is None and s.done()
|
|
90
90
|
|
|
91
91
|
|
|
@@ -111,7 +111,17 @@ def test_seed_makes_picks_reproducible():
|
|
|
111
111
|
assert picks[0] == picks[1]
|
|
112
112
|
|
|
113
113
|
|
|
114
|
+
def test_rows_are_plain_dicts_worst_first():
|
|
115
|
+
s = ThompsonScheduler(["a", "b"], threshold=0.5, min_runs=0,
|
|
116
|
+
prior={"a": (1, 1), "b": (9, 1)}, seed=0)
|
|
117
|
+
rows = s.rows(k=2)
|
|
118
|
+
assert [r["scenario"] for r in rows] == ["a", "b"]
|
|
119
|
+
assert set(rows[1]) == {"scenario", "runs", "passes", "mean", "lo", "hi", "pass^2", "verdict"}
|
|
120
|
+
assert rows[1]["verdict"] == "pass" and rows[1]["mean"] == pytest.approx(0.9)
|
|
121
|
+
|
|
122
|
+
|
|
114
123
|
def test_per_scenario_prior_and_report_columns():
|
|
124
|
+
pytest.importorskip("pandas")
|
|
115
125
|
s = ThompsonScheduler(["a", "b"], threshold=0.5, min_runs=0,
|
|
116
126
|
prior={"a": (1, 1), "b": (9, 1)}, seed=0)
|
|
117
127
|
rep = s.report(k=2)
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
"""The light parts load without pandas, scikit-learn and matplotlib; a heavy part names its extra."""
|
|
2
|
+
import subprocess, sys, textwrap
|
|
3
|
+
|
|
4
|
+
BLOCK = textwrap.dedent('''
|
|
5
|
+
import sys, importlib.abc
|
|
6
|
+
HEAVY = {"pandas", "sklearn", "matplotlib", "seaborn", "jinja2", "scipy"}
|
|
7
|
+
class Block(importlib.abc.MetaPathFinder):
|
|
8
|
+
def find_spec(self, name, path, target=None):
|
|
9
|
+
if name.split(".")[0] in HEAVY:
|
|
10
|
+
raise ModuleNotFoundError(f"No module named {name!r} (blocked)", name=name)
|
|
11
|
+
sys.meta_path.insert(0, Block())
|
|
12
|
+
''')
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def run(code):
|
|
16
|
+
r = subprocess.run([sys.executable, "-c", BLOCK + textwrap.dedent(code)], capture_output=True, text=True)
|
|
17
|
+
assert r.returncode == 0, r.stderr
|
|
18
|
+
return r.stdout
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def test_light_parts_without_heavy_dependencies():
|
|
22
|
+
out = run('''
|
|
23
|
+
import bitskitten
|
|
24
|
+
from bitskitten import ThompsonScheduler, harmonic_score, number
|
|
25
|
+
from bitskitten.qa import Scenario, Suite, check_run, item_agreement_rows
|
|
26
|
+
s = ThompsonScheduler(["a", "b"], seed=0)
|
|
27
|
+
s.update("a", True)
|
|
28
|
+
assert s.rows()[0]["scenario"] in ("a", "b")
|
|
29
|
+
assert harmonic_score([0, 1, 1], [0, 1, 1]) == 1.0
|
|
30
|
+
print(sorted(m for m in sys.modules if m.split(".")[0] in ("pandas", "sklearn", "matplotlib")))
|
|
31
|
+
''')
|
|
32
|
+
assert out.strip() == "[]"
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def test_heavy_part_names_its_extra():
|
|
36
|
+
out = run('''
|
|
37
|
+
for name, extra in (("NanFixer", "ml"), ("informer", "eda"), ("harmonic_scorer", "ml")):
|
|
38
|
+
try:
|
|
39
|
+
import bitskitten
|
|
40
|
+
getattr(bitskitten, name)
|
|
41
|
+
except ImportError as e:
|
|
42
|
+
assert f"bitskitten[{extra}]" in str(e), str(e)
|
|
43
|
+
print("ok", name)
|
|
44
|
+
else:
|
|
45
|
+
raise SystemExit(f"{name} imported with its dependency blocked")
|
|
46
|
+
try:
|
|
47
|
+
from bitskitten import ThompsonScheduler
|
|
48
|
+
ThompsonScheduler(["a"]).report()
|
|
49
|
+
except ImportError as e:
|
|
50
|
+
assert "pandas" in str(e); print("ok report")
|
|
51
|
+
''')
|
|
52
|
+
assert out.split() == ["ok", "NanFixer", "ok", "informer", "ok", "harmonic_scorer", "ok", "report"]
|
|
@@ -166,6 +166,18 @@ def test_harmonic_score():
|
|
|
166
166
|
assert 0 < harmonic_score(y, [0, 0, 0, 1, 2, 2]) < 1
|
|
167
167
|
|
|
168
168
|
|
|
169
|
+
@pytest.mark.parametrize("y, p, labels", [
|
|
170
|
+
([0, 1, 2, 2, 1], [0, 2, 2, 1, 1], None),
|
|
171
|
+
(["b", "a", "c", "a"], ["a", "a", "c", "b"], None),
|
|
172
|
+
([0, 1, 1, 3], [0, 1, 2, 3], [3, 1, 0]), # given order, label 2 not counted
|
|
173
|
+
([0, 1, 1], [0, 1, 1], [0, 1, 5]), # a label nobody has
|
|
174
|
+
])
|
|
175
|
+
def test_confusion_matches_sklearn(y, p, labels):
|
|
176
|
+
from sklearn.metrics import confusion_matrix
|
|
177
|
+
from bitskitten.metrics import confusion
|
|
178
|
+
assert (confusion(y, p, labels) == confusion_matrix(y, p, labels=labels)).all()
|
|
179
|
+
|
|
180
|
+
|
|
169
181
|
def test_harmonic_scorer_in_cv():
|
|
170
182
|
rng = np.random.default_rng(0)
|
|
171
183
|
X = pd.DataFrame(rng.normal(size=(120, 3)))
|
|
@@ -8,7 +8,7 @@ import pytest
|
|
|
8
8
|
from bitskitten.qa import Run, Scenario, Turn, group_failures
|
|
9
9
|
from bitskitten.qa.judge import (
|
|
10
10
|
Checklist, ChecklistItem, Judge, build_prompt, cohen_kappa, format_transcript,
|
|
11
|
-
item_agreement, merge_verdicts, parse_verdict, pick_threshold, total_score, verbosity,
|
|
11
|
+
item_agreement, item_agreement_rows, merge_verdicts, parse_verdict, pick_threshold, total_score, verbosity,
|
|
12
12
|
)
|
|
13
13
|
|
|
14
14
|
CL = Checklist.from_dicts([
|
|
@@ -122,7 +122,16 @@ def test_cohen_kappa_known_values():
|
|
|
122
122
|
cohen_kappa([1], [1, 0])
|
|
123
123
|
|
|
124
124
|
|
|
125
|
+
def test_item_agreement_rows_without_pandas():
|
|
126
|
+
judged = [verdict(greeted=1, fee=f) for f in (1, 0, 1, 0)]
|
|
127
|
+
human = [{"greeted": 1, "correct_fee": h} for h in (0, 1, 0, 1)]
|
|
128
|
+
rows = item_agreement_rows(judged, human, CL)
|
|
129
|
+
assert [r["item"] for r in rows] == ["greeted", "correct_fee"]
|
|
130
|
+
assert rows[1]["kappa"] == -1.0 and rows[1]["n"] == 4
|
|
131
|
+
|
|
132
|
+
|
|
125
133
|
def test_item_agreement_ranks_worst_item_first():
|
|
134
|
+
pytest.importorskip("pandas")
|
|
126
135
|
judged = [verdict(greeted=1, fee=f) for f in (1, 0, 1, 0)]
|
|
127
136
|
human = [{"greeted": 1, "correct_fee": h} for h in (0, 1, 0, 1)]
|
|
128
137
|
df = item_agreement(judged, human, CL)
|
|
@@ -108,16 +108,18 @@ def test_suite_spends_budget_on_broken_scenario_and_groups_failures():
|
|
|
108
108
|
scenarios = [renew("renew"), renew("loop"), renew("crash")]
|
|
109
109
|
suite = Suite(scenarios, new_bot, make_user, gates=GATES)
|
|
110
110
|
res = suite.run(budget=40, threshold=0.9, seed=1)
|
|
111
|
-
verdict =
|
|
111
|
+
verdict = {r["scenario"]: r["verdict"] for r in res.rows}
|
|
112
112
|
assert verdict["loop"] == "fail" and verdict["crash"] == "fail"
|
|
113
113
|
assert verdict["renew"] in ("pass", "undecided")
|
|
114
|
-
runs =
|
|
114
|
+
runs = {r["scenario"]: r["runs"] for r in res.rows}
|
|
115
115
|
assert runs["loop"] == runs["crash"] == 3 # min_runs, then retired
|
|
116
116
|
assert res.spent == sum(runs.values()) <= 40
|
|
117
117
|
rep = res.failures
|
|
118
118
|
assert rep.errors == 3 and rep.failing == 3
|
|
119
119
|
assert rep.by_class()["gate"] == 3
|
|
120
120
|
assert "gate" in format_report(rep)
|
|
121
|
+
pd = pytest.importorskip("pandas")
|
|
122
|
+
assert isinstance(res.report, pd.DataFrame) and list(res.report["scenario"]) == [r["scenario"] for r in res.rows]
|
|
121
123
|
|
|
122
124
|
|
|
123
125
|
def test_flaky_judge_scenario_gets_more_runs_than_stable():
|
|
@@ -136,7 +138,7 @@ def test_flaky_judge_scenario_gets_more_runs_than_stable():
|
|
|
136
138
|
# (0.85) sits near the threshold: without a cap it can eat the budget.
|
|
137
139
|
for seed in range(4):
|
|
138
140
|
res = suite.run(budget=120, threshold=0.9, seed=seed, max_runs=50)
|
|
139
|
-
r = {d["scenario"]: (d["runs"], d["verdict"]) for d in res.
|
|
141
|
+
r = {d["scenario"]: (d["runs"], d["verdict"]) for d in res.rows}
|
|
140
142
|
assert r["stable"][1] == "pass" and r["stable"][0] <= 40, (seed, r)
|
|
141
143
|
assert r["flaky"][1] in ("fail", "undecided") and r["flaky"][0] <= 50, (seed, r)
|
|
142
144
|
|
bitskitten-0.4.0/__init__.py
DELETED
|
@@ -1,35 +0,0 @@
|
|
|
1
|
-
'''bitskitten - small helpers for EDA, plotting and feature encoding.
|
|
2
|
-
|
|
3
|
-
from bitskitten import imperfection, NanFixer, Digitalize
|
|
4
|
-
|
|
5
|
-
Submodules stay importable on their own (`from bitskitten import output`),
|
|
6
|
-
which is also how the zipped drop-in build is used: `from classes import NanFixer`.
|
|
7
|
-
'''
|
|
8
|
-
|
|
9
|
-
__version__ = "0.4.0"
|
|
10
|
-
|
|
11
|
-
from .bandit import ThompsonScheduler, pass_power
|
|
12
|
-
from .classes import Digitalize, Encoder, FeatureTrans, NanFixer, SlowPolyLinearReg
|
|
13
|
-
from .input import number
|
|
14
|
-
from .metrics import harmonic_from_confusion, harmonic_score, harmonic_scorer
|
|
15
|
-
from .text import text_imperfection
|
|
16
|
-
from .output import (
|
|
17
|
-
imperfection,
|
|
18
|
-
img_framaker,
|
|
19
|
-
img_squeeze,
|
|
20
|
-
informer,
|
|
21
|
-
informer_print,
|
|
22
|
-
multicolumn,
|
|
23
|
-
plot_conf_map,
|
|
24
|
-
plot_some_scatters,
|
|
25
|
-
)
|
|
26
|
-
|
|
27
|
-
__all__ = [
|
|
28
|
-
"ThompsonScheduler", "pass_power",
|
|
29
|
-
"Digitalize", "Encoder", "FeatureTrans", "NanFixer", "SlowPolyLinearReg",
|
|
30
|
-
"number",
|
|
31
|
-
"harmonic_from_confusion", "harmonic_score", "harmonic_scorer",
|
|
32
|
-
"text_imperfection",
|
|
33
|
-
"imperfection", "informer", "informer_print", "multicolumn",
|
|
34
|
-
"plot_conf_map", "plot_some_scatters", "img_squeeze", "img_framaker",
|
|
35
|
-
]
|
bitskitten-0.4.0/metrics.py
DELETED
|
@@ -1,36 +0,0 @@
|
|
|
1
|
-
"""Class-agnostic classification quality as plain functions (and a scorer)."""
|
|
2
|
-
import numpy as np
|
|
3
|
-
from sklearn.metrics import confusion_matrix, make_scorer
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
def harmonic_from_confusion(conf):
|
|
7
|
-
'''(harmonic mean of every per-class precision and recall, precision[], recall[]) from a square confusion matrix.
|
|
8
|
-
|
|
9
|
-
No class is "the positive one": the mean runs over all 2q numbers, so one class that is
|
|
10
|
-
never predicted (precision 0) or never recovered (recall 0) pulls the score to 0.
|
|
11
|
-
'''
|
|
12
|
-
conf = np.asarray(conf, dtype=float)
|
|
13
|
-
q = conf.shape[0]
|
|
14
|
-
conf = conf.reshape(q, q)
|
|
15
|
-
hits = np.diag(conf)
|
|
16
|
-
with np.errstate(divide="ignore", invalid="ignore"):
|
|
17
|
-
precision = np.where(conf.sum(axis=0) > 0, hits / conf.sum(axis=0), 0.0)
|
|
18
|
-
recall = np.where(conf.sum(axis=1) > 0, hits / conf.sum(axis=1), 0.0)
|
|
19
|
-
rates = np.r_[precision, recall]
|
|
20
|
-
if (rates <= 0).any():
|
|
21
|
-
hm = 0.0
|
|
22
|
-
else:
|
|
23
|
-
hm = len(rates) / np.sum(1.0 / rates)
|
|
24
|
-
return float(hm), precision, recall
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
def harmonic_score(y_true, y_pred, labels=None):
|
|
28
|
-
'''Harmonic mean of all per-class precisions and recalls; 1.0 = perfect, 0.0 if any class is lost.
|
|
29
|
-
|
|
30
|
-
`labels` fixes the class set (as in `confusion_matrix`); without it classes absent from both
|
|
31
|
-
`y_true` and `y_pred` are not counted.
|
|
32
|
-
'''
|
|
33
|
-
return harmonic_from_confusion(confusion_matrix(y_true, y_pred, labels=labels))[0]
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
harmonic_scorer = make_scorer(harmonic_score)
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|