kx-plot 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.
Files changed (76) hide show
  1. {kx_plot-0.4.0 → kx_plot-0.5.0}/CHANGELOG.md +78 -1
  2. kx_plot-0.4.0/README.md → kx_plot-0.5.0/PKG-INFO +78 -1
  3. kx_plot-0.4.0/PKG-INFO → kx_plot-0.5.0/README.md +40 -29
  4. {kx_plot-0.4.0 → kx_plot-0.5.0}/kx/__init__.py +13 -4
  5. kx_plot-0.5.0/kx/_evaluate.py +80 -0
  6. kx_plot-0.5.0/kx/_metrics.py +176 -0
  7. {kx_plot-0.4.0 → kx_plot-0.5.0}/kx/_plot.py +22 -2
  8. {kx_plot-0.4.0 → kx_plot-0.5.0}/kx/_util.py +11 -0
  9. kx_plot-0.5.0/kx/data/binary.csv +1001 -0
  10. kx_plot-0.5.0/kx/data/curves.csv +11 -0
  11. kx_plot-0.5.0/kx/data/history.csv +61 -0
  12. kx_plot-0.5.0/kx/data/importance.csv +16 -0
  13. kx_plot-0.5.0/kx/data/multiclass.csv +601 -0
  14. kx_plot-0.5.0/kx/data/regression.csv +501 -0
  15. {kx_plot-0.4.0 → kx_plot-0.5.0}/kx/kinds/__init__.py +1 -1
  16. {kx_plot-0.4.0 → kx_plot-0.5.0}/kx/kinds/basic.py +38 -6
  17. {kx_plot-0.4.0 → kx_plot-0.5.0}/kx/kinds/dist.py +6 -1
  18. kx_plot-0.5.0/kx/kinds/ml.py +437 -0
  19. {kx_plot-0.4.0 → kx_plot-0.5.0}/kx/kinds/table.py +5 -3
  20. {kx_plot-0.4.0 → kx_plot-0.5.0}/pyproject.toml +15 -4
  21. {kx_plot-0.4.0 → kx_plot-0.5.0}/tests/test_kx.py +721 -1
  22. {kx_plot-0.4.0 → kx_plot-0.5.0}/.gitignore +0 -0
  23. {kx_plot-0.4.0 → kx_plot-0.5.0}/LICENSE +0 -0
  24. {kx_plot-0.4.0 → kx_plot-0.5.0}/kx/_data.py +0 -0
  25. {kx_plot-0.4.0 → kx_plot-0.5.0}/kx/_files.py +0 -0
  26. {kx_plot-0.4.0 → kx_plot-0.5.0}/kx/_grid.py +0 -0
  27. {kx_plot-0.4.0 → kx_plot-0.5.0}/kx/_save.py +0 -0
  28. {kx_plot-0.4.0 → kx_plot-0.5.0}/kx/_spec.py +0 -0
  29. {kx_plot-0.4.0 → kx_plot-0.5.0}/kx/_theme.py +0 -0
  30. {kx_plot-0.4.0 → kx_plot-0.5.0}/kx/data/cloud.csv +0 -0
  31. {kx_plot-0.4.0 → kx_plot-0.5.0}/kx/data/daily.csv +0 -0
  32. {kx_plot-0.4.0 → kx_plot-0.5.0}/kx/data/dists.csv +0 -0
  33. {kx_plot-0.4.0 → kx_plot-0.5.0}/kx/data/monthly.csv +0 -0
  34. {kx_plot-0.4.0 → kx_plot-0.5.0}/kx/data/passengers.csv +0 -0
  35. {kx_plot-0.4.0 → kx_plot-0.5.0}/kx/data/waves.csv +0 -0
  36. {kx_plot-0.4.0 → kx_plot-0.5.0}/kx/styles/cmaps/LICENCES.md +0 -0
  37. {kx_plot-0.4.0 → kx_plot-0.5.0}/kx/styles/cmaps/balance.txt +0 -0
  38. {kx_plot-0.4.0 → kx_plot-0.5.0}/kx/styles/cmaps/bam.txt +0 -0
  39. {kx_plot-0.4.0 → kx_plot-0.5.0}/kx/styles/cmaps/batlow.txt +0 -0
  40. {kx_plot-0.4.0 → kx_plot-0.5.0}/kx/styles/cmaps/cork.txt +0 -0
  41. {kx_plot-0.4.0 → kx_plot-0.5.0}/kx/styles/cmaps/davos.txt +0 -0
  42. {kx_plot-0.4.0 → kx_plot-0.5.0}/kx/styles/cmaps/deep.txt +0 -0
  43. {kx_plot-0.4.0 → kx_plot-0.5.0}/kx/styles/cmaps/haline.txt +0 -0
  44. {kx_plot-0.4.0 → kx_plot-0.5.0}/kx/styles/cmaps/hawaii.txt +0 -0
  45. {kx_plot-0.4.0 → kx_plot-0.5.0}/kx/styles/cmaps/lipari.txt +0 -0
  46. {kx_plot-0.4.0 → kx_plot-0.5.0}/kx/styles/cmaps/oslo.txt +0 -0
  47. {kx_plot-0.4.0 → kx_plot-0.5.0}/kx/styles/cmaps/roma.txt +0 -0
  48. {kx_plot-0.4.0 → kx_plot-0.5.0}/kx/styles/cmaps/romaO.txt +0 -0
  49. {kx_plot-0.4.0 → kx_plot-0.5.0}/kx/styles/cmaps/thermal.txt +0 -0
  50. {kx_plot-0.4.0 → kx_plot-0.5.0}/kx/styles/cmaps/vik.txt +0 -0
  51. {kx_plot-0.4.0 → kx_plot-0.5.0}/kx/styles/dark.mplstyle +0 -0
  52. {kx_plot-0.4.0 → kx_plot-0.5.0}/kx/styles/light.mplstyle +0 -0
  53. {kx_plot-0.4.0 → kx_plot-0.5.0}/kx/styles/palettes/LICENCES.md +0 -0
  54. {kx_plot-0.4.0 → kx_plot-0.5.0}/kx/styles/palettes/dark2.txt +0 -0
  55. {kx_plot-0.4.0 → kx_plot-0.5.0}/kx/styles/palettes/ibm.txt +0 -0
  56. {kx_plot-0.4.0 → kx_plot-0.5.0}/kx/styles/palettes/okabe.txt +0 -0
  57. {kx_plot-0.4.0 → kx_plot-0.5.0}/kx/styles/palettes/paired.txt +0 -0
  58. {kx_plot-0.4.0 → kx_plot-0.5.0}/kx/styles/palettes/petroff10.txt +0 -0
  59. {kx_plot-0.4.0 → kx_plot-0.5.0}/kx/styles/palettes/petroff6.txt +0 -0
  60. {kx_plot-0.4.0 → kx_plot-0.5.0}/kx/styles/palettes/petroff8.txt +0 -0
  61. {kx_plot-0.4.0 → kx_plot-0.5.0}/kx/styles/palettes/set1.txt +0 -0
  62. {kx_plot-0.4.0 → kx_plot-0.5.0}/kx/styles/palettes/set2.txt +0 -0
  63. {kx_plot-0.4.0 → kx_plot-0.5.0}/kx/styles/palettes/tab10.txt +0 -0
  64. {kx_plot-0.4.0 → kx_plot-0.5.0}/kx/styles/palettes/tab20.txt +0 -0
  65. {kx_plot-0.4.0 → kx_plot-0.5.0}/kx/styles/palettes/tableaucb.txt +0 -0
  66. {kx_plot-0.4.0 → kx_plot-0.5.0}/kx/styles/palettes/tolbright.txt +0 -0
  67. {kx_plot-0.4.0 → kx_plot-0.5.0}/kx/styles/palettes/tolhc.txt +0 -0
  68. {kx_plot-0.4.0 → kx_plot-0.5.0}/kx/styles/palettes/tollight.txt +0 -0
  69. {kx_plot-0.4.0 → kx_plot-0.5.0}/kx/styles/palettes/tolmc.txt +0 -0
  70. {kx_plot-0.4.0 → kx_plot-0.5.0}/kx/styles/palettes/tolvibrant.txt +0 -0
  71. {kx_plot-0.4.0 → kx_plot-0.5.0}/kx/styles/paper.mplstyle +0 -0
  72. {kx_plot-0.4.0 → kx_plot-0.5.0}/kx/styles/poster.mplstyle +0 -0
  73. {kx_plot-0.4.0 → kx_plot-0.5.0}/kx/styles/science.mplstyle +0 -0
  74. {kx_plot-0.4.0 → kx_plot-0.5.0}/kx/styles/talk.mplstyle +0 -0
  75. {kx_plot-0.4.0 → kx_plot-0.5.0}/kx/styles/thesis.mplstyle +0 -0
  76. {kx_plot-0.4.0 → kx_plot-0.5.0}/tests/conftest.py +0 -0
@@ -6,6 +6,82 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
6
6
 
7
7
  ## [Unreleased]
8
8
 
9
+ ## [0.5.0] - 2026-10-24
10
+
11
+ ### Added
12
+
13
+ - `kx.roc_auc(y_true, score)` and `kx.pr_ap(y_true, score)`: the area under the ROC curve (by trapezoids) and
14
+ the average precision (the step sum `Σ (Rₙ − Rₙ₋₁) Pₙ`), in numpy with no scikit-learn needed, and tied scores
15
+ counted as one step as scikit-learn does. Labels are 0/1 or bool with `1`/`True` positive; with two other labels
16
+ the later one in sorted order is positive. More than two labels, a 2-D score or only one class raise.
17
+ - **Datasets** for the machine-learning kinds, for `kx.load`: `binary` (a 0/1 `y` scored by two models, `gbm`
18
+ ranking better and `logreg` better calibrated), `multiclass` (a 3-class `y`, one probability column per class
19
+ `cat`, `dog`, `bird` summing to 1, and `pred`), `regression` (`actual`, `predicted` and an `x` the error grows
20
+ with), `history` (`loss`, `val_loss`, `accuracy`, `val_accuracy` per `epoch`, overfitting after about 30 epochs),
21
+ `importance` (`feature`, `importance`, `std`) and `curves` (learning-curve scores per training `size`,
22
+ `train_1..5` and `val_1..5`). `scripts/make_ml.py` writes them with a fixed seed.
23
+ - **Flag** `diag` (`scatter`, `hexbin`): a dashed `y = x` line across the range `x` and `y` share, to compare
24
+ predicted with actual values or two measurements of the same thing.
25
+ - **Flag** `fit` (`scatter`): a least-squares line with its slope and R² in the legend, which it draws. With a
26
+ categorical `z`, one line per group in the group's colour. With a log axis it raises, because a straight fit
27
+ is a curve there; fit the logs instead.
28
+ - **Plot kind** `cm`: a confusion matrix, `kx.plot(y_true, y_pred, 'cm')`, with the true classes down the rows
29
+ and the predicted ones along the columns, as in scikit-learn. Every label of either array gets a row and a
30
+ column, so a class that is never predicted still shows. `norm` divides each row by its total (the recall of
31
+ each class) with a percent colorbar, `ann` writes each cell's value and `nocb` drops the colorbar. A 2-D
32
+ `y_pred` raises with a hint to pass `proba.argmax(axis=1)`.
33
+ - **Plot kind** `roc`: the ROC curve, `kx.plot(y_true, score, 'roc')`, with the AUC in the legend
34
+ (`gbm (AUC 0.80)`), which it draws without `leg`. A dotted diagonal marks a random model, and both axes run
35
+ from 0 to 1 at equal scale. `z` adds a second model's score. A 2-D score, one column per class, draws one
36
+ curve per class, one-vs-rest, named after the DataFrame's columns or else the sorted labels of `y_true`.
37
+ - **Plot kind** `pr`: the precision-recall curve, `kx.plot(y_true, score, 'pr')`, with the average precision in
38
+ the legend (`gbm (AP 0.80)`) and a dotted baseline at the positive rate, what a random model gets. The curve
39
+ is drawn in the steps that the average precision sums. `z` adds a second model on the same baseline; a 2-D
40
+ score draws one curve per class, each with its own baseline in its colour.
41
+ - **Plot kind** `calib`: a reliability diagram, `kx.plot(y_true, score, 'calib')`: the observed positive rate
42
+ against the mean score in `bins=` equal-width bins over 0..1 (10 by default), with markers sized by the rows
43
+ in each bin, the diagonal a calibrated model lies on, and the Brier score in the legend (`gbm (Brier 0.201)`).
44
+ Empty bins are left out. `z` adds a second model; scores outside 0..1 raise.
45
+ - **Plot kind** `proba`: the score distribution per true class, `kx.plot(y_true, score, 'proba')`: one
46
+ histogram per class on the same `bins=` equal-width bins over 0..1 (20 by default), so their overlap shows
47
+ where the model confuses them. `norm` draws densities, for imbalanced classes. A 2-D score shows each row's
48
+ score for its own true class.
49
+ - **Plot kind** `thresh`: precision, recall and F1 against the decision threshold,
50
+ `kx.plot(y_true, score, 'thresh')`, where a row is positive when its score is at or above the threshold.
51
+ - **Flag** `best` (`thresh`, `loss`, `elbow`): a dashed vertical line at the threshold with the highest F1, labelled in the legend
52
+ (`best F1 0.74 at 0.38`).
53
+ - **Plot kinds** `gain` and `lift`: `kx.plot(y_true, score, 'gain')` draws the share of positives found against
54
+ the share of rows taken, highest scores first, between a dotted diagonal (a random order) and a dashed corner
55
+ at the positive rate (a perfect one). `lift` divides the gain by the random order's, so how many times more
56
+ positives the top rows hold, with a dotted line at 1. `z` adds a second model to both.
57
+ - **Plot kind** `pva`: predicted against actual for a regression, `kx.plot(actual, predicted, 'pva')`, with the
58
+ dashed `y = x` line, equal scales, and R², RMSE and MAE in the corner. Above 5,000 points it draws hexagons
59
+ (`hexbin`) instead of dots, so big test sets stay readable.
60
+ - **Plot kind** `resid`: residuals (`actual - predicted`) against predicted, with a dashed line at 0. `z` colours
61
+ the points as in `scatter`, such as by a feature, and takes `nocb`, `sym` and `logc`.
62
+ - **Plot kind** `imp`: feature importance, `kx.plot(df, 'feature', 'importance', 'std', 'imp')`, as bars lying
63
+ down with the largest on top and `z` as error bars. `top=` keeps the largest (20 by default) and the y label
64
+ says how many were left out.
65
+ - **Plot kind** `loss`: training curves, `kx.plot(history, 'loss')`. The first metric is a solid line and its
66
+ `val_` pair a dashed one in the same colour, against an `epoch` column or the row number from 1. Other metrics
67
+ have other scales, so `kx.plot(h[['accuracy', 'val_accuracy']], 'loss')` draws them. `best` marks the best
68
+ validation epoch: the lowest, or the highest for metrics named with `acc`, `auc`, `f1`, `precision` or `recall`.
69
+ - Table kinds also take a dict of columns, or anything with a `.history` dict such as a Keras `History`, so
70
+ `kx.plot(model.fit(...), 'loss')` works without importing Keras.
71
+ - **Plot kinds** `lcurve` and `vcurve`: cross-validated scores, `kx.plot(sizes, train_scores, val_scores,
72
+ 'lcurve')`, in the shapes scikit-learn's `learning_curve` and `validation_curve` return (one row per x, one
73
+ column per fold). The mean is a line and ± one standard deviation a band in its colour; 1-D scores draw a line
74
+ without a band. `vcurve` is the same with a hyperparameter on x, so `logx` is the usual flag.
75
+ - **Plot kind** `elbow`: choosing the number of clusters, `kx.plot(ks, inertia, 'elbow')`, with `z` (such as the
76
+ silhouette score) on a second y axis on the right. `best` marks the knee: the point farthest from the line
77
+ between the first and last points, with both axes scaled to 0..1.
78
+ - `kx.evaluate(y_true, *scores)`: a model report in one figure, with the panels picked from the data. A binary
79
+ `y` with 1-D scores gets `roc`, `pr`, `calib` and `proba` (2 x 2), with up to two models in each panel but
80
+ `proba`. A 2-D score gets `roc` per class, the `cm` of the most likely class and `proba` of the true class. A
81
+ numeric `y` with more than 10 values gets `pva`, `resid` and a `hist` of the residuals. `spec=` adds a theme and
82
+ flags to every panel, and other keywords go to `kx.grid`. It returns the flat array of axes, as `kx.grid` does;
83
+ the figure is `axs[0].figure`.
84
+
9
85
  ## [0.4.0] - 2026-10-18
10
86
 
11
87
  ### Added
@@ -194,7 +270,8 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
194
270
  - `kx.use`, `kx.show`, `kx.source`, `kx.grammar`, `kx.load` and the demo CSVs
195
271
  - a workflow that publishes the dataset to Kaggle
196
272
 
197
- [Unreleased]: https://github.com/vhrabar/kx-plot/compare/v0.4.0...HEAD
273
+ [Unreleased]: https://github.com/vhrabar/kx-plot/compare/v0.5.0...HEAD
274
+ [0.5.0]: https://github.com/vhrabar/kx-plot/compare/v0.4.0...v0.5.0
198
275
  [0.4.0]: https://github.com/vhrabar/kx-plot/compare/v0.3.0...v0.4.0
199
276
  [0.3.0]: https://github.com/vhrabar/kx-plot/compare/v0.2.0...v0.3.0
200
277
  [0.2.0]: https://github.com/vhrabar/kx-plot/compare/v0.1.0...v0.2.0
@@ -1,3 +1,41 @@
1
+ Metadata-Version: 2.5
2
+ Name: kx-plot
3
+ Version: 0.5.0
4
+ Summary: One-line matplotlib plots, themes and model-evaluation charts for notebooks and scripts, Kaggle-friendly
5
+ Project-URL: Homepage, https://github.com/vhrabar/kx-plot
6
+ Project-URL: Issues, https://github.com/vhrabar/kx-plot/issues
7
+ Project-URL: Changelog, https://github.com/vhrabar/kx-plot/blob/main/CHANGELOG.md
8
+ Project-URL: Kaggle, https://www.kaggle.com/datasets/vhrabar/kx-plot
9
+ Project-URL: Example Notebook, https://www.kaggle.com/code/vhrabar/kx-one-line-matplotlib-plots-and-themes
10
+ Author-email: Vedran Hrabar <vedran.hrabar@outlook.com>
11
+ License-Expression: MIT
12
+ License-File: LICENSE
13
+ License-File: kx/styles/cmaps/LICENCES.md
14
+ License-File: kx/styles/palettes/LICENCES.md
15
+ Keywords: confusion-matrix,data-science,jupyter,kaggle,machine-learning,matplotlib,model-evaluation,plotting,roc-curve,themes,visualization
16
+ Classifier: Development Status :: 4 - Beta
17
+ Classifier: Framework :: Jupyter
18
+ Classifier: Framework :: Matplotlib
19
+ Classifier: Intended Audience :: Developers
20
+ Classifier: Intended Audience :: Education
21
+ Classifier: Intended Audience :: Science/Research
22
+ Classifier: Operating System :: OS Independent
23
+ Classifier: Programming Language :: Python :: 3
24
+ Classifier: Programming Language :: Python :: 3 :: Only
25
+ Classifier: Programming Language :: Python :: 3.10
26
+ Classifier: Programming Language :: Python :: 3.11
27
+ Classifier: Programming Language :: Python :: 3.12
28
+ Classifier: Programming Language :: Python :: 3.13
29
+ Classifier: Programming Language :: Python :: 3.14
30
+ Classifier: Programming Language :: Python :: 3.15
31
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
32
+ Classifier: Topic :: Scientific/Engineering :: Visualization
33
+ Requires-Python: >=3.10
34
+ Requires-Dist: matplotlib>=3.7
35
+ Requires-Dist: numpy>=1.23
36
+ Requires-Dist: pandas>=1.5
37
+ Description-Content-Type: text/markdown
38
+
1
39
  # kx-plot
2
40
 
3
41
  One-line matplotlib plots and themes for notebooks and scripts.
@@ -46,14 +84,18 @@ kx.plot(df.value, spec='box', by=df.group) # one box per group (also rid
46
84
  |-------|-----------------------------------------------------------------------------------------------|
47
85
  | kind | `line` `step` `area` `band` `scatter` `bar` `barh` `hist` `kde` `ridge` `ecdf` `box` `violin` |
48
86
  | | `strip` `qq` `count` `crosstab` `hexbin` `heat` `missing` `nullmap` |
87
+ | | ML: `cm` `roc` `pr` `calib` `proba` `thresh` `gain` `lift` `pva` `resid` `imp` `loss` |
88
+ | | `lcurve` `vcurve` `elbow` |
49
89
  | theme | `dark` `light` `paper` `science` `talk` `poster` `thesis` |
50
90
  | flags | `grid` `leg` `legout` `tight` `rot` `wrap` `logx` `logy` `logxy` `symlogy` `zero` `eq` `pct` |
51
91
  | | `si`; per kind: `stack` `norm` `cum` `date` `mk` `sort` `ann` `mean` `median` `nocb` `sym` |
52
- | | `logc` `corr` `all` |
92
+ | | `logc` `corr` `all` `diag` `fit` `best` |
53
93
 
54
94
  `stack` works with `area`, `bar`, `barh` and `hist`. `norm` is a 100% stack for `area` and a
55
95
  density (area 1) for `hist`. `cum` makes `hist` cumulative; `hist-norm-cum` is the CDF.
56
96
  `hist` puts every series on the same bins, so the bars line up.
97
+ `diag` adds a dashed `y = x` line to `scatter` and `hexbin`; `fit` adds a least-squares line to `scatter`, with
98
+ its slope and R² in the legend (one line per group with a categorical `z`).
57
99
 
58
100
  Unknown tokens raise an error instead of being guessed, with the closest valid tokens as a hint.
59
101
  Everything is inspectable: `kx.grammar()`, `kx.grammar('area')`, `kx.parse('leg-scatter')`, `kx.show('dark')`,
@@ -76,6 +118,41 @@ kx.plot(df, 'age', 'fare', 'hexbin-logc') # points per hexagon; with a
76
118
  `heat`, `missing` and `nullmap` take the whole table and no column names; `kx.plot(df[cols], 'heat')` for some
77
119
  columns. `wrap` breaks long tick labels onto several lines.
78
120
 
121
+ ### Machine learning
122
+
123
+ `kx.load('binary')`, `'multiclass'`, `'regression'`, `'history'`, `'importance'` and `'curves'` are demo data for
124
+ these kinds. Metrics are computed in numpy: no scikit-learn needed.
125
+
126
+ ```python
127
+ kx.plot(y_true, score, 'roc') # ROC curve, AUC in the legend
128
+ kx.plot(y_true, gbm, logreg, 'pr') # a second model goes in z; AP and a random baseline
129
+ kx.plot(y_true, proba_df, 'roc') # a 2-D score: one curve per class, one-vs-rest
130
+ kx.plot(y_true, score, 'calib') # reliability diagram, Brier score in the legend
131
+ kx.plot(y_true, score, 'proba') # score histogram per true class
132
+ kx.plot(y_true, score, 'thresh-best') # precision, recall and F1 against the threshold
133
+ kx.plot(y_true, score, 'gain') # also 'lift'
134
+ kx.plot(y_true, y_pred, 'cm-norm-ann') # confusion matrix, each row the recall of a class
135
+ kx.plot(actual, predicted, 'pva') # predicted vs actual, R², RMSE and MAE
136
+ kx.plot(actual, predicted, feature, 'resid') # residuals, coloured by a feature
137
+ kx.plot(df, 'feature', 'importance', 'std', 'imp') # feature importance with error bars, top= 20
138
+ kx.plot(model.fit(...), 'loss-best') # training curves from a Keras History, dict or DataFrame
139
+ kx.plot(sizes, train_scores, val_scores, 'lcurve') # scikit-learn's learning_curve output; also 'vcurve'
140
+ kx.plot(ks, inertia, silhouette, 'elbow-best') # choosing k, the knee marked
141
+ kx.roc_auc(y_true, score), kx.pr_ap(y_true, score) # the metrics as numbers
142
+ kx.evaluate(y_true, gbm, logreg) # a report: the panels picked from the data
143
+ ```
144
+
145
+ The truth comes first, then the predictions. Binary labels are 0/1 or bool, with `1`/`True` the positive class;
146
+ with two other labels the later one in sorted order is positive. For multiclass, pass a 2-D score with one column
147
+ per class: the class names are the DataFrame's columns, or else the sorted labels of `y_true`. `roc`, `pr`, `calib`,
148
+ `gain` and `lift` draw their legend without `leg`, because the metric in it is the point of the plot.
149
+
150
+ `kx.evaluate(y_true, *scores)` draws `roc`, `pr`, `calib` and `proba` for a binary task, `roc`, `cm` and
151
+ `proba` for a 2-D score, and `pva`, `resid` and a residual `hist` for a numeric `y` with many values. It returns
152
+ the flat array of axes, like `kx.grid`; `spec='dark-grid'` styles every panel.
153
+
154
+ ![machine learning kinds](https://raw.githubusercontent.com/vhrabar/kx-plot/main/previews/dark-ml.png)
155
+
79
156
  rcParams can be overridden in `kx.use` with `__` for dots: `kx.use('dark', figure__figsize=(8, 4))`.
80
157
 
81
158
  Every kind, option, flag and config, with its output, is in the
@@ -1,31 +1,3 @@
1
- Metadata-Version: 2.5
2
- Name: kx-plot
3
- Version: 0.4.0
4
- Summary: One-line matplotlib plots and themes for notebook and scripts, Kaggle-friendly
5
- Project-URL: Homepage, https://github.com/vhrabar/kx-plot
6
- Project-URL: Issues, https://github.com/vhrabar/kx-plot/issues
7
- Project-URL: Changelog, https://github.com/vhrabar/kx-plot/blob/main/CHANGELOG.md
8
- Project-URL: Kaggle, https://www.kaggle.com/datasets/vhrabar/kx-plot
9
- Author-email: Vedran Hrabar <vedran.hrabar@outlook.com>
10
- License-Expression: MIT
11
- License-File: LICENSE
12
- License-File: kx/styles/cmaps/LICENCES.md
13
- License-File: kx/styles/palettes/LICENCES.md
14
- Keywords: jupyter,kaggle,matplotlib,plotting,themes,visualization
15
- Classifier: Development Status :: 3 - Alpha
16
- Classifier: Framework :: Jupyter
17
- Classifier: Framework :: Matplotlib
18
- Classifier: Intended Audience :: Science/Research
19
- Classifier: Operating System :: OS Independent
20
- Classifier: Programming Language :: Python :: 3
21
- Classifier: Programming Language :: Python :: 3 :: Only
22
- Classifier: Topic :: Scientific/Engineering :: Visualization
23
- Requires-Python: >=3.10
24
- Requires-Dist: matplotlib>=3.7
25
- Requires-Dist: numpy>=1.23
26
- Requires-Dist: pandas>=1.5
27
- Description-Content-Type: text/markdown
28
-
29
1
  # kx-plot
30
2
 
31
3
  One-line matplotlib plots and themes for notebooks and scripts.
@@ -74,14 +46,18 @@ kx.plot(df.value, spec='box', by=df.group) # one box per group (also rid
74
46
  |-------|-----------------------------------------------------------------------------------------------|
75
47
  | kind | `line` `step` `area` `band` `scatter` `bar` `barh` `hist` `kde` `ridge` `ecdf` `box` `violin` |
76
48
  | | `strip` `qq` `count` `crosstab` `hexbin` `heat` `missing` `nullmap` |
49
+ | | ML: `cm` `roc` `pr` `calib` `proba` `thresh` `gain` `lift` `pva` `resid` `imp` `loss` |
50
+ | | `lcurve` `vcurve` `elbow` |
77
51
  | theme | `dark` `light` `paper` `science` `talk` `poster` `thesis` |
78
52
  | flags | `grid` `leg` `legout` `tight` `rot` `wrap` `logx` `logy` `logxy` `symlogy` `zero` `eq` `pct` |
79
53
  | | `si`; per kind: `stack` `norm` `cum` `date` `mk` `sort` `ann` `mean` `median` `nocb` `sym` |
80
- | | `logc` `corr` `all` |
54
+ | | `logc` `corr` `all` `diag` `fit` `best` |
81
55
 
82
56
  `stack` works with `area`, `bar`, `barh` and `hist`. `norm` is a 100% stack for `area` and a
83
57
  density (area 1) for `hist`. `cum` makes `hist` cumulative; `hist-norm-cum` is the CDF.
84
58
  `hist` puts every series on the same bins, so the bars line up.
59
+ `diag` adds a dashed `y = x` line to `scatter` and `hexbin`; `fit` adds a least-squares line to `scatter`, with
60
+ its slope and R² in the legend (one line per group with a categorical `z`).
85
61
 
86
62
  Unknown tokens raise an error instead of being guessed, with the closest valid tokens as a hint.
87
63
  Everything is inspectable: `kx.grammar()`, `kx.grammar('area')`, `kx.parse('leg-scatter')`, `kx.show('dark')`,
@@ -104,6 +80,41 @@ kx.plot(df, 'age', 'fare', 'hexbin-logc') # points per hexagon; with a
104
80
  `heat`, `missing` and `nullmap` take the whole table and no column names; `kx.plot(df[cols], 'heat')` for some
105
81
  columns. `wrap` breaks long tick labels onto several lines.
106
82
 
83
+ ### Machine learning
84
+
85
+ `kx.load('binary')`, `'multiclass'`, `'regression'`, `'history'`, `'importance'` and `'curves'` are demo data for
86
+ these kinds. Metrics are computed in numpy: no scikit-learn needed.
87
+
88
+ ```python
89
+ kx.plot(y_true, score, 'roc') # ROC curve, AUC in the legend
90
+ kx.plot(y_true, gbm, logreg, 'pr') # a second model goes in z; AP and a random baseline
91
+ kx.plot(y_true, proba_df, 'roc') # a 2-D score: one curve per class, one-vs-rest
92
+ kx.plot(y_true, score, 'calib') # reliability diagram, Brier score in the legend
93
+ kx.plot(y_true, score, 'proba') # score histogram per true class
94
+ kx.plot(y_true, score, 'thresh-best') # precision, recall and F1 against the threshold
95
+ kx.plot(y_true, score, 'gain') # also 'lift'
96
+ kx.plot(y_true, y_pred, 'cm-norm-ann') # confusion matrix, each row the recall of a class
97
+ kx.plot(actual, predicted, 'pva') # predicted vs actual, R², RMSE and MAE
98
+ kx.plot(actual, predicted, feature, 'resid') # residuals, coloured by a feature
99
+ kx.plot(df, 'feature', 'importance', 'std', 'imp') # feature importance with error bars, top= 20
100
+ kx.plot(model.fit(...), 'loss-best') # training curves from a Keras History, dict or DataFrame
101
+ kx.plot(sizes, train_scores, val_scores, 'lcurve') # scikit-learn's learning_curve output; also 'vcurve'
102
+ kx.plot(ks, inertia, silhouette, 'elbow-best') # choosing k, the knee marked
103
+ kx.roc_auc(y_true, score), kx.pr_ap(y_true, score) # the metrics as numbers
104
+ kx.evaluate(y_true, gbm, logreg) # a report: the panels picked from the data
105
+ ```
106
+
107
+ The truth comes first, then the predictions. Binary labels are 0/1 or bool, with `1`/`True` the positive class;
108
+ with two other labels the later one in sorted order is positive. For multiclass, pass a 2-D score with one column
109
+ per class: the class names are the DataFrame's columns, or else the sorted labels of `y_true`. `roc`, `pr`, `calib`,
110
+ `gain` and `lift` draw their legend without `leg`, because the metric in it is the point of the plot.
111
+
112
+ `kx.evaluate(y_true, *scores)` draws `roc`, `pr`, `calib` and `proba` for a binary task, `roc`, `cm` and
113
+ `proba` for a 2-D score, and `pva`, `resid` and a residual `hist` for a numeric `y` with many values. It returns
114
+ the flat array of axes, like `kx.grid`; `spec='dark-grid'` styles every panel.
115
+
116
+ ![machine learning kinds](https://raw.githubusercontent.com/vhrabar/kx-plot/main/previews/dark-ml.png)
117
+
107
118
  rcParams can be overridden in `kx.use` with `__` for dots: `kx.use('dark', figure__figsize=(8, 4))`.
108
119
 
109
120
  Every kind, option, flag and config, with its output, is in the
@@ -4,15 +4,20 @@ kx: tiny matplotlib helper.
4
4
  Token grammar for kx.plot(spec): kind-theme-flag-flag-...
5
5
  kind : line | step | area | band | scatter | bar | barh | hist | kde | ridge | ecdf | box | violin | strip
6
6
  | qq | heat | crosstab | count | missing | nullmap | hexbin
7
+ | cm | roc | pr | calib | proba | thresh | gain | lift | pva | resid | imp | loss
8
+ | lcurve | vcurve | elbow
7
9
  theme : any file name in styles/
8
10
  flags : grid | leg | legout | tight | rot | wrap | logx | logy | logxy | symlogy | zero | eq | pct | si
9
11
  and per kind: stack norm cum (bars, area, hist), date mk (lines), sort ann (bars, count),
10
12
  stack norm (count),
11
13
  mean median ann (distributions), nocb sym logc (scatter, heat, hexbin), corr ann (heat),
12
- norm ann nocb logc (crosstab), ann all (missing), sort (nullmap).
14
+ norm ann nocb logc (crosstab), ann all (missing), sort (nullmap), diag (scatter, hexbin),
15
+ fit (scatter), norm ann nocb (cm), norm (proba), best (thresh, loss, elbow),
16
+ nocb sym logc (resid).
13
17
  kx.grammar(kind) lists them.
14
18
  by= : group labels for x, one series per group (kde, ridge, ecdf, box, violin, strip, qq, count)
15
- table : heat, missing and nullmap take a whole DataFrame or 2-D array, with no column names: kx.plot(df, 'heat-corr')
19
+ table : heat, missing, nullmap and loss take a whole DataFrame or 2-D array, with no column names:
20
+ kx.plot(df, 'heat-corr'); a dict or a Keras History works too: kx.plot(model.fit(...), 'loss')
16
21
 
17
22
  Palettes (kx.use(theme, palette="okabe")): any file name in styles/palettes/
18
23
  Colormaps (kx.use(theme, cmap="magma")): kx.cmaps()
@@ -20,6 +25,8 @@ with kx.context(theme, ...): the same as kx.use, for one block only.
20
25
  kx.save("fig.png"): saves to /kaggle/working on Kaggle, the current folder elsewhere.
21
26
  kx.missing(df): the share of missing values per column, the same as kx.plot(df, 'missing-ann').
22
27
  kx.grid(5): a figure of 5 panels as a flat array of axes, for kx.plot(..., ax=).
28
+ kx.roc_auc(y_true, score) and kx.pr_ap(y_true, score): area under the ROC curve and average precision, in numpy.
29
+ kx.evaluate(y_true, score): a model report, the panels picked from the data (binary, multiclass or regression).
23
30
  kx.grammar("area") and kx.source("area") explain one kind; kx.parse(spec) shows how a spec is read.
24
31
  """
25
32
  import glob
@@ -33,15 +40,17 @@ import pandas as pd
33
40
  from matplotlib.axes import Axes
34
41
 
35
42
  from ._data import datasets, load
43
+ from ._evaluate import evaluate
36
44
  from ._grid import grid
45
+ from ._metrics import pr_ap, roc_auc
37
46
  from ._plot import plot
38
47
  from ._save import save
39
48
  from ._spec import COMMON_FLAGS, KINDS, Spec, all_flags, parse
40
49
  from ._theme import BREWER_CMAPS, BUILTIN_CMAPS, VENDORED_CMAPS, cmaps, context, palette, palettes, show, styles, use
41
50
 
42
51
  __all__ = ["BREWER_CMAPS", "BUILTIN_CMAPS", "VENDORED_CMAPS", "Spec", "__version__", "cmaps", "context", "datasets",
43
- "grammar", "grid", "load", "missing", "palette", "palettes", "parse", "plot", "save", "show", "source",
44
- "styles", "use"]
52
+ "evaluate", "grammar", "grid", "load", "missing", "palette", "palettes", "parse", "plot", "pr_ap", "roc_auc",
53
+ "save", "show", "source", "styles", "use"]
45
54
 
46
55
 
47
56
  def _version() -> str:
@@ -0,0 +1,80 @@
1
+ """kx.evaluate: one call, every panel a model needs, picked from the data."""
2
+ import contextlib
3
+ from typing import Any
4
+
5
+ import matplotlib.pyplot as plt
6
+ import numpy as np
7
+ import pandas as pd
8
+ from numpy.typing import ArrayLike
9
+
10
+ from ._grid import grid
11
+ from ._metrics import classes
12
+ from ._plot import plot
13
+ from ._spec import parse
14
+ from ._theme import style_path
15
+
16
+ LABELS = 10 # a numeric y with more distinct values than this is a regression
17
+
18
+
19
+ def evaluate(y: ArrayLike, *scores: ArrayLike, spec: str = "", **kw: Any) -> np.ndarray:
20
+ """A model report in one figure: kx.evaluate(y_true, score) or kx.evaluate(y_true, gbm, logreg).
21
+ The task comes from the data:
22
+ binary y, 1-D scores roc, pr, calib, proba (2 x 2), every score in each panel but proba (the first)
23
+ 2-D score (multiclass) roc per class, cm of the most likely class, proba of the true class
24
+ numeric y, many values pva, resid, and a hist of the residuals
25
+ spec= adds a theme and flags to every panel: kx.evaluate(y, score, spec='dark-grid').
26
+ Other keywords go to kx.grid (figsize=...). Returns the flat array of axes; the figure is axs[0].figure."""
27
+ if not scores:
28
+ raise TypeError("kx.evaluate needs y_true and at least one score: kx.evaluate(y_true, score)")
29
+ task = _task(y, scores)
30
+ if task != "binary" and len(scores) > 1:
31
+ raise ValueError(f"a {task} report takes one model's {'scores' if task == 'multiclass' else 'predictions'}; "
32
+ f"got {len(scores)}")
33
+ if task == "binary" and len(scores) > 2:
34
+ raise ValueError(f"the panels compare at most 2 models; got {len(scores)}. Call kx.evaluate once per pair")
35
+ named = [s if getattr(s, "name", None) is not None or np.ndim(s) == 2
36
+ else pd.Series(np.asarray(s).ravel(), name="score" if len(scores) == 1 else f"score {i + 1}")
37
+ for i, s in enumerate(scores)]
38
+ theme = parse(spec).theme if spec else None
39
+ style = plt.style.context(["default", style_path(theme)]) if theme else contextlib.nullcontext()
40
+ with style:
41
+ panels = PANELS[task](y, named)
42
+ axs = grid(len(panels), cols=2 if len(panels) == 4 else 3, **kw)
43
+ for ax, (title, args, kind) in zip(axs, panels, strict=True):
44
+ plot(*args, spec="-".join([kind, *([spec] if spec else [])]), ax=ax, title=title)
45
+ if task == "regression":
46
+ axs[2].set_xlabel("residual (actual - predicted)")
47
+ return axs
48
+
49
+
50
+ def _task(y: ArrayLike, scores: tuple) -> str:
51
+ if any(np.ndim(s) == 2 and np.shape(s)[1] > 1 for s in scores):
52
+ return "multiclass"
53
+ v = pd.Series(np.asarray(y).ravel())
54
+ if pd.api.types.is_numeric_dtype(v) and not pd.api.types.is_bool_dtype(v) and v.nunique() > LABELS:
55
+ return "regression"
56
+ return "binary"
57
+
58
+
59
+ def _binary(y: ArrayLike, scores: list) -> list[tuple[str, tuple, str]]:
60
+ return [("ROC", (y, *scores), "roc"), ("precision-recall", (y, *scores), "pr"),
61
+ ("calibration", (y, *scores), "calib"), (f"scores by class: {scores[0].name}", (y, scores[0]), "proba")]
62
+
63
+
64
+ def _multiclass(y: ArrayLike, scores: list) -> list[tuple[str, tuple, str]]:
65
+ score = scores[0]
66
+ found = classes(y)
67
+ cols = list(score.columns) if isinstance(score, pd.DataFrame) else None
68
+ names = cols if cols is not None and set(cols) <= set(found) else found # as _scored pairs columns
69
+ pred = np.asarray(names, dtype=object)[np.asarray(score, dtype=float).argmax(axis=1)]
70
+ return [("ROC, one-vs-rest", (y, score), "roc"), ("confusion matrix", (y, pred), "cm-norm-ann"),
71
+ ("score of the true class", (y, score), "proba")]
72
+
73
+
74
+ def _regression(y: ArrayLike, scores: list) -> list[tuple[str, tuple, str]]:
75
+ actual, predicted = np.asarray(y, dtype=float).ravel(), np.asarray(scores[0], dtype=float).ravel()
76
+ return [("predicted vs actual", (y, scores[0]), "pva"), ("residuals", (y, scores[0]), "resid"),
77
+ ("residual distribution", (pd.Series(actual - predicted, name="residual"),), "hist")]
78
+
79
+
80
+ PANELS = {"binary": _binary, "multiclass": _multiclass, "regression": _regression}
@@ -0,0 +1,176 @@
1
+ """
2
+ Metrics for the machine-learning kinds
3
+ """
4
+ from typing import Any
5
+
6
+ import numpy as np
7
+ import pandas as pd
8
+ from numpy.typing import ArrayLike
9
+
10
+
11
+ def binary(y: ArrayLike) -> np.ndarray:
12
+ """y as a 0/1 int array: 1/True is positive, else the later of two labels in sorted order."""
13
+ v = np.asarray(y).ravel()
14
+ if pd.isna(v).any():
15
+ raise ValueError("y_true has missing values; drop those rows first")
16
+ if v.dtype == bool:
17
+ return v.astype(int)
18
+ found = sorted(pd.unique(v), key=lambda c: (str(type(c)), c))
19
+ if set(found) <= {0, 1}:
20
+ return (v == 1).astype(int)
21
+ if len(found) == 2:
22
+ return (v == found[1]).astype(int)
23
+ if len(found) == 1:
24
+ raise ValueError(f"y_true has one label only ({found[0]!r}); a binary metric needs two classes")
25
+ raise ValueError(f"y_true has {len(found)} labels but the score is 1-D; "
26
+ "for multiclass pass a 2-D score, one column per class")
27
+
28
+
29
+ def _pair(y: ArrayLike, s: ArrayLike) -> tuple[np.ndarray, np.ndarray]:
30
+ """0/1 labels and float scores of the same length, checked."""
31
+ sc = np.asarray(s, dtype=float)
32
+ if sc.ndim > 1 and sc.shape[1] > 1:
33
+ raise ValueError(f"score has {sc.shape[1]} columns; a binary metric takes one score per row")
34
+ sc = sc.ravel()
35
+ t = binary(y)
36
+ if len(t) != len(sc):
37
+ raise ValueError(f"y_true has {len(t)} values but the score has {len(sc)}")
38
+ if not np.isfinite(sc).all():
39
+ raise ValueError("score has NaN or inf values; drop those rows first")
40
+ return t, sc
41
+
42
+
43
+ def _counts(y: ArrayLike, s: ArrayLike) -> tuple[np.ndarray, np.ndarray, np.ndarray, int, int]:
44
+ """True and false positives at each distinct threshold, highest score first, so tied scores are one step.
45
+ Returns tps, fps, thresholds and the number of positives and negatives."""
46
+ t, sc = _pair(y, s)
47
+ order = np.argsort(-sc, kind="mergesort")
48
+ t, sc = t[order], sc[order]
49
+ last = np.r_[np.flatnonzero(np.diff(sc)), len(sc) - 1] # the last row of each run of tied scores
50
+ tps = np.cumsum(t)[last]
51
+ fps = (last + 1) - tps
52
+ return tps, fps, sc[last], int(t.sum()), len(t) - int(t.sum())
53
+
54
+
55
+ def _both(pos: int, neg: int, what: str) -> None:
56
+ if not pos or not neg:
57
+ raise ValueError(f"{what} needs both classes in y_true; it has only {'negatives' if neg else 'positives'}")
58
+
59
+
60
+ def roc_curve(y: ArrayLike, s: ArrayLike) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
61
+ """False and true positive rates at each distinct threshold, from (0, 0) at threshold inf to (1, 1)."""
62
+ tps, fps, thr, pos, neg = _counts(y, s)
63
+ _both(pos, neg, "a ROC curve")
64
+ return np.r_[0, fps / neg], np.r_[0, tps / pos], np.r_[np.inf, thr]
65
+
66
+
67
+ def pr_curve(y: ArrayLike, s: ArrayLike) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
68
+ """Precision and recall at each distinct threshold, highest first, from (1, 0) at threshold inf."""
69
+ tps, fps, thr, pos, _ = _counts(y, s)
70
+ if not pos:
71
+ raise ValueError("a PR curve needs positives in y_true; it has only negatives")
72
+ return np.r_[1, tps / (tps + fps)], np.r_[0, tps / pos], np.r_[np.inf, thr]
73
+
74
+
75
+ def roc_auc(y_true: ArrayLike, score: ArrayLike) -> float:
76
+ """Area under the ROC curve, by trapezoids: 1 is a perfect ranking, 0.5 a random one."""
77
+ fpr, tpr, _ = roc_curve(y_true, score)
78
+ return float(np.sum(np.diff(fpr) * (tpr[1:] + tpr[:-1]) / 2))
79
+
80
+
81
+ def pr_ap(y_true: ArrayLike, score: ArrayLike) -> float:
82
+ """Average precision: the step sum Σ (Rₙ - Rₙ₋₁) Pₙ over thresholds, as scikit-learn computes it.
83
+ Trapezoids would overstate it."""
84
+ precision, recall, _ = pr_curve(y_true, score)
85
+ return float(np.sum(np.diff(recall) * precision[1:]))
86
+
87
+
88
+ def classes(*arrays: ArrayLike) -> list[Any]:
89
+ """The labels found in any of arrays, sorted (numbers before text when both occur)."""
90
+ found = set().union(*(pd.unique(np.asarray(a, dtype=object).ravel()) for a in arrays))
91
+ return sorted(found, key=lambda c: (str(type(c)), c))
92
+
93
+
94
+ def confusion(y: ArrayLike, p: ArrayLike, labels: list[Any] | None = None) -> np.ndarray:
95
+ """Counts with the true class down the rows and the predicted class along the columns.
96
+ labels default to the union of both arrays in sorted order, so a class never predicted still gets a column."""
97
+ t, q = np.asarray(y, dtype=object).ravel(), np.asarray(p, dtype=object).ravel()
98
+ if len(t) != len(q):
99
+ raise ValueError(f"y_true has {len(t)} values but y_pred has {len(q)}")
100
+ if labels is None:
101
+ labels = classes(t, q)
102
+ index = {c: i for i, c in enumerate(labels)}
103
+ m = np.zeros((len(labels), len(labels)), dtype=int)
104
+ for a, b in zip(t, q, strict=True):
105
+ if a in index and b in index:
106
+ m[index[a], index[b]] += 1
107
+ return m
108
+
109
+
110
+ def fit_errors(actual: ArrayLike, predicted: ArrayLike) -> tuple[float, float, float]:
111
+ """R², RMSE and MAE of a regression's predictions. R² is 1 - SSres / SStot, so below 0 is worse than the mean."""
112
+ a, p = np.asarray(actual, dtype=float).ravel(), np.asarray(predicted, dtype=float).ravel()
113
+ if len(a) != len(p):
114
+ raise ValueError(f"actual has {len(a)} values but predicted has {len(p)}")
115
+ if not (np.isfinite(a).all() and np.isfinite(p).all()):
116
+ raise ValueError("actual or predicted has NaN or inf values; drop those rows first")
117
+ err = a - p
118
+ total = np.sum((a - a.mean()) ** 2)
119
+ r2 = 1 - np.sum(err ** 2) / total if total else float("nan")
120
+ return float(r2), float(np.sqrt(np.mean(err ** 2))), float(np.mean(np.abs(err)))
121
+
122
+
123
+ def brier(y: ArrayLike, s: ArrayLike) -> float:
124
+ """Mean squared gap between the score and the 0/1 outcome: 0 is perfect."""
125
+ t, sc = _pair(y, s)
126
+ return float(np.mean((sc - t) ** 2))
127
+
128
+
129
+ def calibration(y: ArrayLike, s: ArrayLike, bins: int = 10) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
130
+ """Mean score, observed positive rate and row count in each of bins equal-width bins over 0..1.
131
+ Empty bins are left out."""
132
+ if isinstance(bins, bool) or not isinstance(bins, (int, np.integer)) or bins < 1:
133
+ raise ValueError(f"bins= is the number of equal-width bins over 0..1, a whole number from 1; got {bins!r}")
134
+ t, sc = _pair(y, s)
135
+ if sc.min() < 0 or sc.max() > 1:
136
+ raise ValueError("calibration needs scores between 0 and 1, such as predicted probabilities")
137
+ which = np.clip(np.floor(sc * bins).astype(int), 0, bins - 1) # a score of exactly 1 goes in the last bin
138
+ n = np.bincount(which, minlength=bins)
139
+ full = n > 0
140
+ mean = np.bincount(which, weights=sc, minlength=bins)[full] / n[full]
141
+ rate = np.bincount(which, weights=t, minlength=bins)[full] / n[full]
142
+ return mean, rate, n[full]
143
+
144
+
145
+ def thresholds(y: ArrayLike, s: ArrayLike) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
146
+ """Each distinct score as a threshold (score >= it is positive), highest first, with the precision, recall
147
+ and F1 there."""
148
+ tps, fps, thr, pos, _ = _counts(y, s)
149
+ if not pos:
150
+ raise ValueError("precision and recall need positives in y_true; it has only negatives")
151
+ precision, recall = tps / (tps + fps), tps / pos
152
+ with np.errstate(invalid="ignore"):
153
+ f1 = np.nan_to_num(2 * precision * recall / (precision + recall)) # 0 where both are 0
154
+ return thr, precision, recall, f1
155
+
156
+
157
+ def gain(y: ArrayLike, s: ArrayLike) -> tuple[np.ndarray, np.ndarray]:
158
+ """Share of rows taken, best scores first, and the share of positives found, from (0, 0) to (1, 1)."""
159
+ tps, fps, _, pos, neg = _counts(y, s)
160
+ if not pos:
161
+ raise ValueError("a gain curve needs positives in y_true; it has only negatives")
162
+ return np.r_[0, (tps + fps) / (pos + neg)], np.r_[0, tps / pos]
163
+
164
+
165
+ def knee(x: ArrayLike, y: ArrayLike) -> int:
166
+ """Index of the knee: the point farthest from the straight line between the first and last points, with both
167
+ axes scaled to 0..1 so the units of x and y do not matter."""
168
+ xs, ys = np.asarray(x, dtype=float).ravel(), np.asarray(y, dtype=float).ravel()
169
+ if len(xs) < 3:
170
+ raise ValueError(f"a knee needs at least 3 points; got {len(xs)}")
171
+ if not (np.isfinite(xs).all() and np.isfinite(ys).all()):
172
+ raise ValueError("x or y has NaN or inf values; drop those points first")
173
+ span = np.ptp(xs) or 1.0, np.ptp(ys) or 1.0
174
+ u, v = (xs - xs[0]) / span[0], (ys - ys[0]) / span[1]
175
+ ex, ey = u[-1], v[-1] # the chord from the first point to the last
176
+ return int(np.argmax(np.abs(u * ey - v * ex))) # distance to the chord, up to its constant length
@@ -67,7 +67,8 @@ def _arrays(data: tuple, spec: str | Spec | None, by: ArrayLike | str | None) ->
67
67
  data = list(data)
68
68
  df = data.pop(0) if data and isinstance(data[0], pd.DataFrame) else None
69
69
  last = data[-1] if data else None
70
- if isinstance(last, Spec) or (isinstance(last, str) and (df is None or last not in df.columns)):
70
+ if isinstance(last, Spec) or (isinstance(last, str) and (df is None or last not in df.columns
71
+ or (spec is None and _table_spec(last)))):
71
72
  if spec is not None: # a trailing string that is not a column is the spec
72
73
  raise TypeError(f"spec given twice ({data[-1]!r} and spec={spec!r})")
73
74
  if df is not None and isinstance(last, str): # not a spec either, but close to a column: a typo
@@ -79,7 +80,9 @@ def _arrays(data: tuple, spec: str | Spec | None, by: ArrayLike | str | None) ->
79
80
  raise
80
81
  spec = data.pop()
81
82
  table = KINDS[parse(spec or "line").kind].takes_table
82
- if table and df is None and len(data) == 1 and np.ndim(data[0]) == 2:
83
+ if table and df is None and len(data) == 1 and _history(data[0]) is not None:
84
+ df, data = pd.DataFrame(_history(data[0])), [] # a dict, or a Keras History: kx.plot(model.fit(...), 'loss')
85
+ elif table and df is None and len(data) == 1 and np.ndim(data[0]) == 2:
83
86
  df, data = pd.DataFrame(data[0]), [] # a 2-D array is a table with 0..n labels
84
87
  if df is not None:
85
88
  if not data and table:
@@ -97,6 +100,23 @@ def _arrays(data: tuple, spec: str | Spec | None, by: ArrayLike | str | None) ->
97
100
  return *data, *[None] * (3 - len(data)), spec, by
98
101
 
99
102
 
103
+ def _table_spec(text: str) -> bool:
104
+ """text is a spec for a table kind. Table kinds take no columns, so a column named 'loss' (as in every Keras
105
+ history) does not hide kx.plot(h, 'loss')."""
106
+ try:
107
+ return KINDS[parse(text).kind].takes_table
108
+ except ValueError:
109
+ return False
110
+
111
+
112
+ def _history(obj: object) -> dict | None:
113
+ """A dict of columns: obj itself, or its .history (a Keras History), so Keras need not be imported."""
114
+ if isinstance(obj, dict):
115
+ return obj
116
+ history = getattr(obj, "history", None)
117
+ return history if isinstance(history, dict) else None
118
+
119
+
100
120
  def _column(df: pd.DataFrame, name: object) -> pd.Series:
101
121
  """df[name], or an error naming the columns that are close."""
102
122
  if not isinstance(name, str):