bitskitten 0.2.1__tar.gz → 0.4.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/PKG-INFO +279 -0
- bitskitten-0.4.0/README.md +258 -0
- {bitskitten-0.2.1 → bitskitten-0.4.0}/__init__.py +7 -1
- bitskitten-0.4.0/bandit.py +266 -0
- bitskitten-0.4.0/bitskitten.egg-info/PKG-INFO +279 -0
- bitskitten-0.4.0/bitskitten.egg-info/SOURCES.txt +36 -0
- {bitskitten-0.2.1 → bitskitten-0.4.0}/classes.py +212 -168
- bitskitten-0.4.0/metrics.py +36 -0
- {bitskitten-0.2.1 → bitskitten-0.4.0}/output.py +28 -19
- {bitskitten-0.2.1 → bitskitten-0.4.0}/pyproject.toml +3 -2
- bitskitten-0.4.0/qa/__init__.py +52 -0
- bitskitten-0.4.0/qa/checks.py +230 -0
- bitskitten-0.4.0/qa/failures.py +137 -0
- bitskitten-0.4.0/qa/judge.py +322 -0
- bitskitten-0.4.0/qa/runner.py +167 -0
- bitskitten-0.4.0/qa/scenario.py +211 -0
- bitskitten-0.4.0/qa/users.py +339 -0
- bitskitten-0.4.0/tests/test_bandit.py +134 -0
- bitskitten-0.4.0/tests/test_fit_time.py +207 -0
- bitskitten-0.4.0/tests/test_qa.py +205 -0
- bitskitten-0.4.0/tests/test_qa_judge.py +142 -0
- bitskitten-0.4.0/tests/test_qa_runner.py +148 -0
- bitskitten-0.4.0/tests/test_qa_users.py +186 -0
- {bitskitten-0.2.1 → bitskitten-0.4.0}/tests/test_smoke.py +2 -1
- bitskitten-0.4.0/text.py +77 -0
- bitskitten-0.2.1/PKG-INFO +0 -193
- bitskitten-0.2.1/README.md +0 -172
- bitskitten-0.2.1/bitskitten.egg-info/PKG-INFO +0 -193
- bitskitten-0.2.1/bitskitten.egg-info/SOURCES.txt +0 -17
- {bitskitten-0.2.1 → bitskitten-0.4.0}/LICENSE +0 -0
- {bitskitten-0.2.1 → bitskitten-0.4.0}/bitskitten.egg-info/dependency_links.txt +0 -0
- {bitskitten-0.2.1 → bitskitten-0.4.0}/bitskitten.egg-info/requires.txt +0 -0
- {bitskitten-0.2.1 → bitskitten-0.4.0}/bitskitten.egg-info/top_level.txt +0 -0
- {bitskitten-0.2.1 → bitskitten-0.4.0}/input.py +0 -0
- {bitskitten-0.2.1 → bitskitten-0.4.0}/setup.cfg +0 -0
|
@@ -0,0 +1,279 @@
|
|
|
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
|
+
# bitskitten
|
|
23
|
+
|
|
24
|
+
A small toolbox of things I kept re-typing in every EDA notebook:
|
|
25
|
+
quick dataset reports, a few plots, and sklearn-compatible encoders that can be
|
|
26
|
+
dropped straight into a `Pipeline` / `GridSearchCV`.
|
|
27
|
+
|
|
28
|
+
Nothing here is a framework. Each helper is one function or one class you can read in a minute.
|
|
29
|
+
|
|
30
|
+
## Install
|
|
31
|
+
|
|
32
|
+
```bash
|
|
33
|
+
pip install bitskitten
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
The latest commit: `pip install git+https://github.com/Caerno/bitskit.git`.
|
|
37
|
+
On Kaggle / Colab the same lines work in a cell (`!pip install ...`).
|
|
38
|
+
For a kernel with no internet, add
|
|
39
|
+
[the archive GitHub builds for every commit](https://github.com/Caerno/bitskit/archive/refs/heads/main.zip)
|
|
40
|
+
as a dataset and install it from disk:
|
|
41
|
+
|
|
42
|
+
```bash
|
|
43
|
+
pip install --no-deps /kaggle/input/<your-dataset>/bitskit-main.zip
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
Requires Python ≥ 3.9, numpy, pandas, scikit-learn, matplotlib, seaborn.
|
|
47
|
+
|
|
48
|
+
## Quick start
|
|
49
|
+
|
|
50
|
+
```python
|
|
51
|
+
import pandas as pd
|
|
52
|
+
from bitskitten import informer, informer_print, imperfection, text_imperfection, NanFixer, Digitalize
|
|
53
|
+
|
|
54
|
+
df = pd.concat([train, test]) # test rows have no target -> NaN
|
|
55
|
+
|
|
56
|
+
informer_print(informer(df, "Survived"))
|
|
57
|
+
# Features: 12
|
|
58
|
+
# Observations: 891/418
|
|
59
|
+
# train dataset: 68.0%
|
|
60
|
+
# classes: 0: 61.6%, 1: 38.4%
|
|
61
|
+
|
|
62
|
+
imperfection(df) # what is missing and how varied it is
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
`imperfection` returns a frame sorted by NA share — share of missing values, number of
|
|
66
|
+
unique values, dtype and the values themselves. By default it shows non-numeric columns
|
|
67
|
+
only; `numeric=True` adds the rest, `no_nan=True` keeps only columns that actually have gaps.
|
|
68
|
+
`informer` switches to `describe()` of the target when it has more than `max_classes` distinct
|
|
69
|
+
values (regression).
|
|
70
|
+
|
|
71
|
+
`text_imperfection(texts)` is the same look at a corpus: one row per defect — empty, too short,
|
|
72
|
+
control characters, not NFKC-normalized, URL, HTML tag, base64-like run, repeated character or
|
|
73
|
+
word, Cyrillic and Latin mixed inside a word, few letters, exact duplicate — with share, count
|
|
74
|
+
and a few offending examples. Rows with zero hits are hidden (`no_clean=False` shows them).
|
|
75
|
+
|
|
76
|
+
## Encoders
|
|
77
|
+
|
|
78
|
+
Both are `TransformerMixin` + `BaseEstimator` and pass `check_estimator`: statistics are
|
|
79
|
+
learned at `fit` and applied at `transform`, so the test set never leaks into its own filling,
|
|
80
|
+
a batch that lacks a category still comes out with the same columns, `get_feature_names_out`,
|
|
81
|
+
`set_output(transform="pandas")`, `check_is_fitted`, `clone` and grid search all work.
|
|
82
|
+
A frame in gives a frame out; an array in gives an array out (or a frame with `set_output`).
|
|
83
|
+
|
|
84
|
+
```python
|
|
85
|
+
from sklearn.pipeline import Pipeline
|
|
86
|
+
from sklearn.model_selection import GridSearchCV
|
|
87
|
+
from sklearn.ensemble import RandomForestClassifier
|
|
88
|
+
|
|
89
|
+
pipe = Pipeline([
|
|
90
|
+
("nan", NanFixer()), # fill the gaps
|
|
91
|
+
("dig", Digitalize()), # make everything numeric
|
|
92
|
+
("clf", RandomForestClassifier()),
|
|
93
|
+
])
|
|
94
|
+
|
|
95
|
+
grid = GridSearchCV(pipe, {
|
|
96
|
+
"nan__lim": [0.1, 0.225, 0.5],
|
|
97
|
+
"nan__method": ["mean", "median"],
|
|
98
|
+
"dig__mode": ["raw", "cut", "qcut"],
|
|
99
|
+
"dig__ncut": [5, 10],
|
|
100
|
+
})
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
**`NanFixer(lim=0.225, method="mean", filler="U", random_state=None)`** — picks a filling
|
|
104
|
+
strategy per column at `fit` time, measures it on the fit data, applies it at `transform`:
|
|
105
|
+
|
|
106
|
+
| column | condition (on the fit data) | fill |
|
|
107
|
+
|---|---|---|
|
|
108
|
+
| numeric | NA share ≤ `lim` | `method` (`mean`/`median`) of the fit data |
|
|
109
|
+
| numeric | NA share > `lim` | draws from N(mean, std) of the fit data, clipped to its range |
|
|
110
|
+
| object | one value dominates (>25%) | that mode |
|
|
111
|
+
| object | otherwise | the `filler` string |
|
|
112
|
+
|
|
113
|
+
Columns of any other dtype pass through untouched. The plan is in `plan_` after `fit`.
|
|
114
|
+
|
|
115
|
+
**`Digitalize(alim=10, mode="raw", ncut=5)`** — turns a mixed frame into a numeric one:
|
|
116
|
+
|
|
117
|
+
| column | condition (on the fit data) | result |
|
|
118
|
+
|---|---|---|
|
|
119
|
+
| numeric | < 3 unique values | as is |
|
|
120
|
+
| any | < `alim` unique values | one-hot over the categories seen at fit: `col_value`; an unseen value → all zeros |
|
|
121
|
+
| numeric | `mode="cut"` / `"qcut"` | `col_cut5` / `col_qcut5`: `ncut` equal-spaced / equal-sized bins with edges from the fit data; out-of-range values go to the edge bins |
|
|
122
|
+
| numeric | `mode="raw"` | as is |
|
|
123
|
+
| non-numeric | ≥ `alim` unique values | `col_top5`: frequency rank from the fit data (most frequent → 1, the tail and unseen values → `ncut`) |
|
|
124
|
+
|
|
125
|
+
Output column names are `get_feature_names_out()`; up to 0.2 they were `pd.get_dummies`
|
|
126
|
+
prefixes (`col[:5]_value`) and depended on the batch.
|
|
127
|
+
|
|
128
|
+
**`FeatureTrans(series)`** is the shared kit both encoders are built from, and it is
|
|
129
|
+
iterable: it yields every transformation that makes sense for that column's dtype —
|
|
130
|
+
handy when you want to throw candidate features at a selector.
|
|
131
|
+
|
|
132
|
+
```python
|
|
133
|
+
candidates = pd.concat(list(FeatureTrans(df["Fare"])), axis=1)
|
|
134
|
+
# Fare_count, Fare_freqn, Fare_top5..., Fare_cut5..., Fare_qcut5..., Fare_sqrt, Fare_log2, Fare_pow2 ...
|
|
135
|
+
```
|
|
136
|
+
|
|
137
|
+
Its pieces are static methods you can also call directly: `count`, `freq`, `top`,
|
|
138
|
+
`cut`, `qcut`, `math`, `bilabel`, `fuzzy_mean`, `robust`, `fill`.
|
|
139
|
+
|
|
140
|
+
## Metric
|
|
141
|
+
|
|
142
|
+
```python
|
|
143
|
+
from bitskitten import harmonic_score, harmonic_scorer
|
|
144
|
+
|
|
145
|
+
harmonic_score(y_true, y_pred) # 1.0 perfect, 0.0 if any class is lost
|
|
146
|
+
cross_val_score(clf, X, y, scoring=harmonic_scorer)
|
|
147
|
+
GridSearchCV(pipe, grid, scoring=harmonic_scorer)
|
|
148
|
+
```
|
|
149
|
+
|
|
150
|
+
`harmonic_score` is the harmonic mean of every per-class precision and every per-class
|
|
151
|
+
recall — a class-agnostic generalization of F1 for when no class is "the positive one".
|
|
152
|
+
A class that is never predicted or never recovered pulls it to 0. `harmonic_from_confusion(conf)`
|
|
153
|
+
returns `(score, precision[], recall[])` from a ready confusion matrix.
|
|
154
|
+
|
|
155
|
+
## Test scheduler for flaky suites
|
|
156
|
+
|
|
157
|
+
```python
|
|
158
|
+
from bitskitten.bandit import ThompsonScheduler
|
|
159
|
+
|
|
160
|
+
sched = ThompsonScheduler(["happy_path", "reschedule", "angry_user"],
|
|
161
|
+
threshold=0.9, seed=0)
|
|
162
|
+
report = sched.run(run_scenario, budget=80) # run_scenario(name) -> bool
|
|
163
|
+
print(report) # runs, passes, mean, 95 % interval, pass^3, verdict per scenario
|
|
164
|
+
```
|
|
165
|
+
|
|
166
|
+
For suites where one run of a scenario is a coin flip (LLM bots, anything
|
|
167
|
+
stochastic). Each scenario carries a Beta posterior over its pass rate; the next
|
|
168
|
+
run goes to the scenario most likely to fail (Thompson sampling), scenarios whose
|
|
169
|
+
interval has cleared or missed the threshold are retired, and the loop stops when
|
|
170
|
+
nothing is left to learn or the budget is out. `pass_power(alpha, beta, k)` is the
|
|
171
|
+
tau-bench pass^k with the posterior integrated out; `width=` retires scenarios that
|
|
172
|
+
sit on the threshold once their interval is narrow enough; `min_runs=` (default 3)
|
|
173
|
+
stops a single failure from deciding a verdict.
|
|
174
|
+
|
|
175
|
+
## Regression testing for dialogue agents
|
|
176
|
+
|
|
177
|
+
```python
|
|
178
|
+
from bitskitten.qa import Suite, Judge, Checklist, ScriptedUser, TopicClassifier, BotStep, format_report
|
|
179
|
+
|
|
180
|
+
suite = Suite(scenarios, # Scenario.from_dict(...) per YAML entry
|
|
181
|
+
new_bot=lambda sc: MyBot(), # bot(text) -> str | BotStep(text, state, slots, signals)
|
|
182
|
+
new_user=lambda sc, seed: ScriptedUser(classify, asks, facts=sc.facts, seed=seed),
|
|
183
|
+
gates={"collecting_states": {"collecting_date"}},
|
|
184
|
+
judge=Judge(model, Checklist.from_dicts(items))) # model(prompt) -> str, any provider
|
|
185
|
+
result = suite.run(budget=80, threshold=0.9, max_runs=40)
|
|
186
|
+
print(result.report) # per scenario: runs, mean, 95 % interval, pass^3, verdict
|
|
187
|
+
print(format_report(result.failures)) # failed runs grouped by what failed
|
|
188
|
+
```
|
|
189
|
+
|
|
190
|
+
For bots where one run is a coin flip. Per run, cheapest first: the outcome
|
|
191
|
+
against the scenario and trace invariants (stuck in a state, the same reply
|
|
192
|
+
verbatim, invalid slot value, a number not in the allowed set, a scripted user's
|
|
193
|
+
record of re-asks) need no model; the judge is called only on runs that pass
|
|
194
|
+
them. The next run goes where a failure is most likely (Thompson sampling);
|
|
195
|
+
decided scenarios retire, the loop stops when nothing is left to learn.
|
|
196
|
+
|
|
197
|
+
- **Users.** `ScriptedUser` reacts to what the bot said (markers you supply),
|
|
198
|
+
hands out facts and records `repeated_ask` / `unexpected_ask` instead of
|
|
199
|
+
quietly answering them. `MarkovUsers` varies wording from real utterances at
|
|
200
|
+
zero model cost. `CallableUser` wraps any model.
|
|
201
|
+
- **Judge.** Repeated judging merges binary items by majority, not by mean.
|
|
202
|
+
`item_agreement(judged, human)` gives per-item kappa against your own labels
|
|
203
|
+
— check it before trusting an item; `pick_threshold` picks the score cut.
|
|
204
|
+
- **Cost of a verdict.** Proving "passes at least 90 %" at 95 % takes 35 clean
|
|
205
|
+
runs in a row; that is the threshold's price, not the scheduler's. A scenario
|
|
206
|
+
sitting right at the threshold cannot be decided cheaply — cap it with `max_runs`.
|
|
207
|
+
- `validate_scenarios(entries, Vocabulary(...))` checks a scenario file and flags
|
|
208
|
+
absolute dates that will expire.
|
|
209
|
+
|
|
210
|
+
## Plots
|
|
211
|
+
|
|
212
|
+
```python
|
|
213
|
+
from bitskitten import plot_conf_map, plot_some_scatters
|
|
214
|
+
|
|
215
|
+
hm, precision, recall = plot_conf_map(confusion_matrix(y_true, y_pred), title="RF")
|
|
216
|
+
```
|
|
217
|
+
|
|
218
|
+
`plot_conf_map` draws the confusion matrix as shares, with a precision row, a recall
|
|
219
|
+
column and — in the corner — `harmonic_score`. Returns `(harmonic_mean, precision, recall)`;
|
|
220
|
+
`blind=True` computes without drawing.
|
|
221
|
+
|
|
222
|
+
`plot_some_scatters(X, y)` — pairwise scatter plots of every column combination, coloured by `y`.
|
|
223
|
+
|
|
224
|
+
`multicolumn(series, cols=5)` folds a long series into several columns so a wide
|
|
225
|
+
`df.sample().T` fits on one screen.
|
|
226
|
+
|
|
227
|
+
## Image compression demo
|
|
228
|
+
|
|
229
|
+
`img_squeeze` reduces the dimensionality of an RGBA image by unrolling channels into a
|
|
230
|
+
flat 2D matrix, running any sklearn decomposition on it and rebuilding the picture:
|
|
231
|
+
|
|
232
|
+
```python
|
|
233
|
+
from sklearn.decomposition import PCA
|
|
234
|
+
from bitskitten import img_framaker
|
|
235
|
+
|
|
236
|
+
img_framaker(img, 20, PCA) # image restored from 20 components
|
|
237
|
+
```
|
|
238
|
+
|
|
239
|
+
## Estimator from scratch
|
|
240
|
+
|
|
241
|
+
`SlowPolyLinearReg(gener=[0, 1], norm=None, alpha=None)` — linear regression written on
|
|
242
|
+
numpy/pandas, with polynomial and non-linear feature generation (`0` = intercept,
|
|
243
|
+
integers = powers, `"sqrt"`/`"cbrt"`/`"log2"`/`"ln"`/`"log10"`), optional normalization
|
|
244
|
+
(`"minmax"`, `"std"`, `"max"`, `"mean"`) and L2 regularization. Closed-form solution,
|
|
245
|
+
so it warns you about singular and ill-conditioned matrices instead of hiding them
|
|
246
|
+
(and falls back to the least-norm solution rather than giving up).
|
|
247
|
+
It exists to show the mechanics, not to compete with `sklearn.linear_model`.
|
|
248
|
+
|
|
249
|
+
The default `gener=[0, 1]` is the plain intercept + x. Drop the `0` only if you
|
|
250
|
+
really want the line forced through the origin.
|
|
251
|
+
|
|
252
|
+
```python
|
|
253
|
+
model = SlowPolyLinearReg(gener=[0, 1, 2], norm="std", alpha=0.01)
|
|
254
|
+
model.fit(X, y)
|
|
255
|
+
model.score(X, y) # R²
|
|
256
|
+
```
|
|
257
|
+
|
|
258
|
+
## Input
|
|
259
|
+
|
|
260
|
+
`number("How many? ", t=int, op=">=", limit=0)` — keeps asking until the answer parses
|
|
261
|
+
and satisfies the condition.
|
|
262
|
+
|
|
263
|
+
## Development
|
|
264
|
+
|
|
265
|
+
```bash
|
|
266
|
+
pip install -e .[test]
|
|
267
|
+
pytest
|
|
268
|
+
```
|
|
269
|
+
|
|
270
|
+
The repo root *is* the package (flat layout), so the clone has to be in a folder named
|
|
271
|
+
`bitskitten` for `pytest` to import it; CI installs the wheel first for the same reason.
|
|
272
|
+
|
|
273
|
+
The drop-in zip in `download/` is built from committed files only, so no `__pycache__`
|
|
274
|
+
gets in:
|
|
275
|
+
|
|
276
|
+
```bash
|
|
277
|
+
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
|
|
279
|
+
```
|
|
@@ -0,0 +1,258 @@
|
|
|
1
|
+
# bitskitten
|
|
2
|
+
|
|
3
|
+
A small toolbox of things I kept re-typing in every EDA notebook:
|
|
4
|
+
quick dataset reports, a few plots, and sklearn-compatible encoders that can be
|
|
5
|
+
dropped straight into a `Pipeline` / `GridSearchCV`.
|
|
6
|
+
|
|
7
|
+
Nothing here is a framework. Each helper is one function or one class you can read in a minute.
|
|
8
|
+
|
|
9
|
+
## Install
|
|
10
|
+
|
|
11
|
+
```bash
|
|
12
|
+
pip install bitskitten
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
The latest commit: `pip install git+https://github.com/Caerno/bitskit.git`.
|
|
16
|
+
On Kaggle / Colab the same lines work in a cell (`!pip install ...`).
|
|
17
|
+
For a kernel with no internet, add
|
|
18
|
+
[the archive GitHub builds for every commit](https://github.com/Caerno/bitskit/archive/refs/heads/main.zip)
|
|
19
|
+
as a dataset and install it from disk:
|
|
20
|
+
|
|
21
|
+
```bash
|
|
22
|
+
pip install --no-deps /kaggle/input/<your-dataset>/bitskit-main.zip
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
Requires Python ≥ 3.9, numpy, pandas, scikit-learn, matplotlib, seaborn.
|
|
26
|
+
|
|
27
|
+
## Quick start
|
|
28
|
+
|
|
29
|
+
```python
|
|
30
|
+
import pandas as pd
|
|
31
|
+
from bitskitten import informer, informer_print, imperfection, text_imperfection, NanFixer, Digitalize
|
|
32
|
+
|
|
33
|
+
df = pd.concat([train, test]) # test rows have no target -> NaN
|
|
34
|
+
|
|
35
|
+
informer_print(informer(df, "Survived"))
|
|
36
|
+
# Features: 12
|
|
37
|
+
# Observations: 891/418
|
|
38
|
+
# train dataset: 68.0%
|
|
39
|
+
# classes: 0: 61.6%, 1: 38.4%
|
|
40
|
+
|
|
41
|
+
imperfection(df) # what is missing and how varied it is
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
`imperfection` returns a frame sorted by NA share — share of missing values, number of
|
|
45
|
+
unique values, dtype and the values themselves. By default it shows non-numeric columns
|
|
46
|
+
only; `numeric=True` adds the rest, `no_nan=True` keeps only columns that actually have gaps.
|
|
47
|
+
`informer` switches to `describe()` of the target when it has more than `max_classes` distinct
|
|
48
|
+
values (regression).
|
|
49
|
+
|
|
50
|
+
`text_imperfection(texts)` is the same look at a corpus: one row per defect — empty, too short,
|
|
51
|
+
control characters, not NFKC-normalized, URL, HTML tag, base64-like run, repeated character or
|
|
52
|
+
word, Cyrillic and Latin mixed inside a word, few letters, exact duplicate — with share, count
|
|
53
|
+
and a few offending examples. Rows with zero hits are hidden (`no_clean=False` shows them).
|
|
54
|
+
|
|
55
|
+
## Encoders
|
|
56
|
+
|
|
57
|
+
Both are `TransformerMixin` + `BaseEstimator` and pass `check_estimator`: statistics are
|
|
58
|
+
learned at `fit` and applied at `transform`, so the test set never leaks into its own filling,
|
|
59
|
+
a batch that lacks a category still comes out with the same columns, `get_feature_names_out`,
|
|
60
|
+
`set_output(transform="pandas")`, `check_is_fitted`, `clone` and grid search all work.
|
|
61
|
+
A frame in gives a frame out; an array in gives an array out (or a frame with `set_output`).
|
|
62
|
+
|
|
63
|
+
```python
|
|
64
|
+
from sklearn.pipeline import Pipeline
|
|
65
|
+
from sklearn.model_selection import GridSearchCV
|
|
66
|
+
from sklearn.ensemble import RandomForestClassifier
|
|
67
|
+
|
|
68
|
+
pipe = Pipeline([
|
|
69
|
+
("nan", NanFixer()), # fill the gaps
|
|
70
|
+
("dig", Digitalize()), # make everything numeric
|
|
71
|
+
("clf", RandomForestClassifier()),
|
|
72
|
+
])
|
|
73
|
+
|
|
74
|
+
grid = GridSearchCV(pipe, {
|
|
75
|
+
"nan__lim": [0.1, 0.225, 0.5],
|
|
76
|
+
"nan__method": ["mean", "median"],
|
|
77
|
+
"dig__mode": ["raw", "cut", "qcut"],
|
|
78
|
+
"dig__ncut": [5, 10],
|
|
79
|
+
})
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
**`NanFixer(lim=0.225, method="mean", filler="U", random_state=None)`** — picks a filling
|
|
83
|
+
strategy per column at `fit` time, measures it on the fit data, applies it at `transform`:
|
|
84
|
+
|
|
85
|
+
| column | condition (on the fit data) | fill |
|
|
86
|
+
|---|---|---|
|
|
87
|
+
| numeric | NA share ≤ `lim` | `method` (`mean`/`median`) of the fit data |
|
|
88
|
+
| numeric | NA share > `lim` | draws from N(mean, std) of the fit data, clipped to its range |
|
|
89
|
+
| object | one value dominates (>25%) | that mode |
|
|
90
|
+
| object | otherwise | the `filler` string |
|
|
91
|
+
|
|
92
|
+
Columns of any other dtype pass through untouched. The plan is in `plan_` after `fit`.
|
|
93
|
+
|
|
94
|
+
**`Digitalize(alim=10, mode="raw", ncut=5)`** — turns a mixed frame into a numeric one:
|
|
95
|
+
|
|
96
|
+
| column | condition (on the fit data) | result |
|
|
97
|
+
|---|---|---|
|
|
98
|
+
| numeric | < 3 unique values | as is |
|
|
99
|
+
| any | < `alim` unique values | one-hot over the categories seen at fit: `col_value`; an unseen value → all zeros |
|
|
100
|
+
| numeric | `mode="cut"` / `"qcut"` | `col_cut5` / `col_qcut5`: `ncut` equal-spaced / equal-sized bins with edges from the fit data; out-of-range values go to the edge bins |
|
|
101
|
+
| numeric | `mode="raw"` | as is |
|
|
102
|
+
| non-numeric | ≥ `alim` unique values | `col_top5`: frequency rank from the fit data (most frequent → 1, the tail and unseen values → `ncut`) |
|
|
103
|
+
|
|
104
|
+
Output column names are `get_feature_names_out()`; up to 0.2 they were `pd.get_dummies`
|
|
105
|
+
prefixes (`col[:5]_value`) and depended on the batch.
|
|
106
|
+
|
|
107
|
+
**`FeatureTrans(series)`** is the shared kit both encoders are built from, and it is
|
|
108
|
+
iterable: it yields every transformation that makes sense for that column's dtype —
|
|
109
|
+
handy when you want to throw candidate features at a selector.
|
|
110
|
+
|
|
111
|
+
```python
|
|
112
|
+
candidates = pd.concat(list(FeatureTrans(df["Fare"])), axis=1)
|
|
113
|
+
# Fare_count, Fare_freqn, Fare_top5..., Fare_cut5..., Fare_qcut5..., Fare_sqrt, Fare_log2, Fare_pow2 ...
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
Its pieces are static methods you can also call directly: `count`, `freq`, `top`,
|
|
117
|
+
`cut`, `qcut`, `math`, `bilabel`, `fuzzy_mean`, `robust`, `fill`.
|
|
118
|
+
|
|
119
|
+
## Metric
|
|
120
|
+
|
|
121
|
+
```python
|
|
122
|
+
from bitskitten import harmonic_score, harmonic_scorer
|
|
123
|
+
|
|
124
|
+
harmonic_score(y_true, y_pred) # 1.0 perfect, 0.0 if any class is lost
|
|
125
|
+
cross_val_score(clf, X, y, scoring=harmonic_scorer)
|
|
126
|
+
GridSearchCV(pipe, grid, scoring=harmonic_scorer)
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
`harmonic_score` is the harmonic mean of every per-class precision and every per-class
|
|
130
|
+
recall — a class-agnostic generalization of F1 for when no class is "the positive one".
|
|
131
|
+
A class that is never predicted or never recovered pulls it to 0. `harmonic_from_confusion(conf)`
|
|
132
|
+
returns `(score, precision[], recall[])` from a ready confusion matrix.
|
|
133
|
+
|
|
134
|
+
## Test scheduler for flaky suites
|
|
135
|
+
|
|
136
|
+
```python
|
|
137
|
+
from bitskitten.bandit import ThompsonScheduler
|
|
138
|
+
|
|
139
|
+
sched = ThompsonScheduler(["happy_path", "reschedule", "angry_user"],
|
|
140
|
+
threshold=0.9, seed=0)
|
|
141
|
+
report = sched.run(run_scenario, budget=80) # run_scenario(name) -> bool
|
|
142
|
+
print(report) # runs, passes, mean, 95 % interval, pass^3, verdict per scenario
|
|
143
|
+
```
|
|
144
|
+
|
|
145
|
+
For suites where one run of a scenario is a coin flip (LLM bots, anything
|
|
146
|
+
stochastic). Each scenario carries a Beta posterior over its pass rate; the next
|
|
147
|
+
run goes to the scenario most likely to fail (Thompson sampling), scenarios whose
|
|
148
|
+
interval has cleared or missed the threshold are retired, and the loop stops when
|
|
149
|
+
nothing is left to learn or the budget is out. `pass_power(alpha, beta, k)` is the
|
|
150
|
+
tau-bench pass^k with the posterior integrated out; `width=` retires scenarios that
|
|
151
|
+
sit on the threshold once their interval is narrow enough; `min_runs=` (default 3)
|
|
152
|
+
stops a single failure from deciding a verdict.
|
|
153
|
+
|
|
154
|
+
## Regression testing for dialogue agents
|
|
155
|
+
|
|
156
|
+
```python
|
|
157
|
+
from bitskitten.qa import Suite, Judge, Checklist, ScriptedUser, TopicClassifier, BotStep, format_report
|
|
158
|
+
|
|
159
|
+
suite = Suite(scenarios, # Scenario.from_dict(...) per YAML entry
|
|
160
|
+
new_bot=lambda sc: MyBot(), # bot(text) -> str | BotStep(text, state, slots, signals)
|
|
161
|
+
new_user=lambda sc, seed: ScriptedUser(classify, asks, facts=sc.facts, seed=seed),
|
|
162
|
+
gates={"collecting_states": {"collecting_date"}},
|
|
163
|
+
judge=Judge(model, Checklist.from_dicts(items))) # model(prompt) -> str, any provider
|
|
164
|
+
result = suite.run(budget=80, threshold=0.9, max_runs=40)
|
|
165
|
+
print(result.report) # per scenario: runs, mean, 95 % interval, pass^3, verdict
|
|
166
|
+
print(format_report(result.failures)) # failed runs grouped by what failed
|
|
167
|
+
```
|
|
168
|
+
|
|
169
|
+
For bots where one run is a coin flip. Per run, cheapest first: the outcome
|
|
170
|
+
against the scenario and trace invariants (stuck in a state, the same reply
|
|
171
|
+
verbatim, invalid slot value, a number not in the allowed set, a scripted user's
|
|
172
|
+
record of re-asks) need no model; the judge is called only on runs that pass
|
|
173
|
+
them. The next run goes where a failure is most likely (Thompson sampling);
|
|
174
|
+
decided scenarios retire, the loop stops when nothing is left to learn.
|
|
175
|
+
|
|
176
|
+
- **Users.** `ScriptedUser` reacts to what the bot said (markers you supply),
|
|
177
|
+
hands out facts and records `repeated_ask` / `unexpected_ask` instead of
|
|
178
|
+
quietly answering them. `MarkovUsers` varies wording from real utterances at
|
|
179
|
+
zero model cost. `CallableUser` wraps any model.
|
|
180
|
+
- **Judge.** Repeated judging merges binary items by majority, not by mean.
|
|
181
|
+
`item_agreement(judged, human)` gives per-item kappa against your own labels
|
|
182
|
+
— check it before trusting an item; `pick_threshold` picks the score cut.
|
|
183
|
+
- **Cost of a verdict.** Proving "passes at least 90 %" at 95 % takes 35 clean
|
|
184
|
+
runs in a row; that is the threshold's price, not the scheduler's. A scenario
|
|
185
|
+
sitting right at the threshold cannot be decided cheaply — cap it with `max_runs`.
|
|
186
|
+
- `validate_scenarios(entries, Vocabulary(...))` checks a scenario file and flags
|
|
187
|
+
absolute dates that will expire.
|
|
188
|
+
|
|
189
|
+
## Plots
|
|
190
|
+
|
|
191
|
+
```python
|
|
192
|
+
from bitskitten import plot_conf_map, plot_some_scatters
|
|
193
|
+
|
|
194
|
+
hm, precision, recall = plot_conf_map(confusion_matrix(y_true, y_pred), title="RF")
|
|
195
|
+
```
|
|
196
|
+
|
|
197
|
+
`plot_conf_map` draws the confusion matrix as shares, with a precision row, a recall
|
|
198
|
+
column and — in the corner — `harmonic_score`. Returns `(harmonic_mean, precision, recall)`;
|
|
199
|
+
`blind=True` computes without drawing.
|
|
200
|
+
|
|
201
|
+
`plot_some_scatters(X, y)` — pairwise scatter plots of every column combination, coloured by `y`.
|
|
202
|
+
|
|
203
|
+
`multicolumn(series, cols=5)` folds a long series into several columns so a wide
|
|
204
|
+
`df.sample().T` fits on one screen.
|
|
205
|
+
|
|
206
|
+
## Image compression demo
|
|
207
|
+
|
|
208
|
+
`img_squeeze` reduces the dimensionality of an RGBA image by unrolling channels into a
|
|
209
|
+
flat 2D matrix, running any sklearn decomposition on it and rebuilding the picture:
|
|
210
|
+
|
|
211
|
+
```python
|
|
212
|
+
from sklearn.decomposition import PCA
|
|
213
|
+
from bitskitten import img_framaker
|
|
214
|
+
|
|
215
|
+
img_framaker(img, 20, PCA) # image restored from 20 components
|
|
216
|
+
```
|
|
217
|
+
|
|
218
|
+
## Estimator from scratch
|
|
219
|
+
|
|
220
|
+
`SlowPolyLinearReg(gener=[0, 1], norm=None, alpha=None)` — linear regression written on
|
|
221
|
+
numpy/pandas, with polynomial and non-linear feature generation (`0` = intercept,
|
|
222
|
+
integers = powers, `"sqrt"`/`"cbrt"`/`"log2"`/`"ln"`/`"log10"`), optional normalization
|
|
223
|
+
(`"minmax"`, `"std"`, `"max"`, `"mean"`) and L2 regularization. Closed-form solution,
|
|
224
|
+
so it warns you about singular and ill-conditioned matrices instead of hiding them
|
|
225
|
+
(and falls back to the least-norm solution rather than giving up).
|
|
226
|
+
It exists to show the mechanics, not to compete with `sklearn.linear_model`.
|
|
227
|
+
|
|
228
|
+
The default `gener=[0, 1]` is the plain intercept + x. Drop the `0` only if you
|
|
229
|
+
really want the line forced through the origin.
|
|
230
|
+
|
|
231
|
+
```python
|
|
232
|
+
model = SlowPolyLinearReg(gener=[0, 1, 2], norm="std", alpha=0.01)
|
|
233
|
+
model.fit(X, y)
|
|
234
|
+
model.score(X, y) # R²
|
|
235
|
+
```
|
|
236
|
+
|
|
237
|
+
## Input
|
|
238
|
+
|
|
239
|
+
`number("How many? ", t=int, op=">=", limit=0)` — keeps asking until the answer parses
|
|
240
|
+
and satisfies the condition.
|
|
241
|
+
|
|
242
|
+
## Development
|
|
243
|
+
|
|
244
|
+
```bash
|
|
245
|
+
pip install -e .[test]
|
|
246
|
+
pytest
|
|
247
|
+
```
|
|
248
|
+
|
|
249
|
+
The repo root *is* the package (flat layout), so the clone has to be in a folder named
|
|
250
|
+
`bitskitten` for `pytest` to import it; CI installs the wheel first for the same reason.
|
|
251
|
+
|
|
252
|
+
The drop-in zip in `download/` is built from committed files only, so no `__pycache__`
|
|
253
|
+
gets in:
|
|
254
|
+
|
|
255
|
+
```bash
|
|
256
|
+
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
|
|
258
|
+
```
|
|
@@ -6,10 +6,13 @@ Submodules stay importable on their own (`from bitskitten import output`),
|
|
|
6
6
|
which is also how the zipped drop-in build is used: `from classes import NanFixer`.
|
|
7
7
|
'''
|
|
8
8
|
|
|
9
|
-
__version__ = "0.
|
|
9
|
+
__version__ = "0.4.0"
|
|
10
10
|
|
|
11
|
+
from .bandit import ThompsonScheduler, pass_power
|
|
11
12
|
from .classes import Digitalize, Encoder, FeatureTrans, NanFixer, SlowPolyLinearReg
|
|
12
13
|
from .input import number
|
|
14
|
+
from .metrics import harmonic_from_confusion, harmonic_score, harmonic_scorer
|
|
15
|
+
from .text import text_imperfection
|
|
13
16
|
from .output import (
|
|
14
17
|
imperfection,
|
|
15
18
|
img_framaker,
|
|
@@ -22,8 +25,11 @@ from .output import (
|
|
|
22
25
|
)
|
|
23
26
|
|
|
24
27
|
__all__ = [
|
|
28
|
+
"ThompsonScheduler", "pass_power",
|
|
25
29
|
"Digitalize", "Encoder", "FeatureTrans", "NanFixer", "SlowPolyLinearReg",
|
|
26
30
|
"number",
|
|
31
|
+
"harmonic_from_confusion", "harmonic_score", "harmonic_scorer",
|
|
32
|
+
"text_imperfection",
|
|
27
33
|
"imperfection", "informer", "informer_print", "multicolumn",
|
|
28
34
|
"plot_conf_map", "plot_some_scatters", "img_squeeze", "img_framaker",
|
|
29
35
|
]
|