speechplotlib 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- speechplotlib/__init__.py +40 -0
- speechplotlib/accessor.py +102 -0
- speechplotlib/analyzers/__init__.py +12 -0
- speechplotlib/analyzers/_input.py +97 -0
- speechplotlib/analyzers/_stats.py +165 -0
- speechplotlib/analyzers/_text.py +192 -0
- speechplotlib/analyzers/categorical.py +211 -0
- speechplotlib/analyzers/distribution.py +409 -0
- speechplotlib/analyzers/model.py +456 -0
- speechplotlib/analyzers/overview.py +157 -0
- speechplotlib/analyzers/relationship.py +413 -0
- speechplotlib/analyzers/trend.py +281 -0
- speechplotlib/config.py +124 -0
- speechplotlib/errors.py +8 -0
- speechplotlib/plotting.py +102 -0
- speechplotlib/result.py +207 -0
- speechplotlib/rules.py +139 -0
- speechplotlib/session.py +73 -0
- speechplotlib/speech.py +117 -0
- speechplotlib/var.py +303 -0
- speechplotlib-0.1.0.dist-info/METADATA +166 -0
- speechplotlib-0.1.0.dist-info/RECORD +25 -0
- speechplotlib-0.1.0.dist-info/WHEEL +5 -0
- speechplotlib-0.1.0.dist-info/licenses/LICENSE +21 -0
- speechplotlib-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,456 @@
|
|
|
1
|
+
"""Model charts: elbow method, PCA explained variance, feature importance, ROC curve, residual plot."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import math
|
|
6
|
+
|
|
7
|
+
import numpy as np
|
|
8
|
+
import pandas as pd
|
|
9
|
+
from scipy import stats
|
|
10
|
+
|
|
11
|
+
from .. import rules
|
|
12
|
+
from .. import speech as sp
|
|
13
|
+
from ..config import config
|
|
14
|
+
from ..result import build
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _maybe_plot(res, plot, kind, **kw):
|
|
18
|
+
if plot:
|
|
19
|
+
from ..plotting import draw
|
|
20
|
+
|
|
21
|
+
res.figure = draw(kind, res.title, **kw)
|
|
22
|
+
return res
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _need_sklearn(what: str):
|
|
26
|
+
try:
|
|
27
|
+
import sklearn # noqa: F401
|
|
28
|
+
except ImportError as exc: # pragma: no cover
|
|
29
|
+
raise ImportError(f"{what} needs scikit-learn: pip install speechplotlib[ml]") from exc
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def kneedle_scores(xs, ys):
|
|
33
|
+
"""Kneedle difference curve (Satopaa and others, 2011): how far each point is from the
|
|
34
|
+
straight line joining the ends, with both axes scaled to 0 to 1. Higher is more knee-like."""
|
|
35
|
+
x = np.asarray(xs, float)
|
|
36
|
+
y = np.asarray(ys, float)
|
|
37
|
+
if len(x) < 3 or np.ptp(x) == 0 or np.ptp(y) == 0:
|
|
38
|
+
return None
|
|
39
|
+
xn = (x - x.min()) / np.ptp(x)
|
|
40
|
+
yn = (y - y.min()) / np.ptp(y)
|
|
41
|
+
if y[0] > y[-1]: # falling curve: compare with the line from (0, 1) to (1, 0)
|
|
42
|
+
return (1 - yn) - xn
|
|
43
|
+
return yn - xn # rising curve, as for cumulative variance
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def kneedle(xs, ys) -> int | None:
|
|
47
|
+
"""Index of the knee of a falling, flattening curve, or None when there is none."""
|
|
48
|
+
diff = kneedle_scores(xs, ys)
|
|
49
|
+
if diff is None:
|
|
50
|
+
return None
|
|
51
|
+
i = int(np.argmax(diff))
|
|
52
|
+
return i if diff[i] > 0 else None
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _knee_tie(xs, ys, knee, share=0.95):
|
|
56
|
+
"""Other points whose knee score is within 5% of the best: the elbow is not clear-cut."""
|
|
57
|
+
diff = kneedle_scores(xs, ys)
|
|
58
|
+
if diff is None or knee is None:
|
|
59
|
+
return []
|
|
60
|
+
return [i for i in range(len(diff)) if i != knee and diff[i] >= share * diff[knee]]
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
# ----- elbow ---------------------------------------------------------------------------
|
|
64
|
+
|
|
65
|
+
def elbow(X=None, *, k=range(1, 11), inertias=None, random_state=0, level=None, plot=False):
|
|
66
|
+
"""Describe an elbow plot for choosing the number of clusters.
|
|
67
|
+
|
|
68
|
+
Give data ``X`` to fit k-means for each k, or give the ``inertias`` you already have,
|
|
69
|
+
as a list matching ``k`` or a dict of k to inertia.
|
|
70
|
+
"""
|
|
71
|
+
if inertias is None:
|
|
72
|
+
if X is None:
|
|
73
|
+
raise ValueError("Give data X, or inertias=[...] with one value per k.")
|
|
74
|
+
_need_sklearn("elbow with data")
|
|
75
|
+
from sklearn.cluster import KMeans
|
|
76
|
+
|
|
77
|
+
ks = list(k)
|
|
78
|
+
inertias = [float(KMeans(n_clusters=kk, n_init=10, random_state=random_state).fit(X).inertia_) for kk in ks]
|
|
79
|
+
elif isinstance(inertias, dict):
|
|
80
|
+
ks = list(inertias.keys())
|
|
81
|
+
inertias = [float(v) for v in inertias.values()]
|
|
82
|
+
else:
|
|
83
|
+
ks = list(k)[: len(inertias)]
|
|
84
|
+
inertias = [float(v) for v in inertias]
|
|
85
|
+
if len(ks) != len(inertias):
|
|
86
|
+
raise ValueError("inertias needs one value per k.")
|
|
87
|
+
ks, vals = np.asarray(ks), np.asarray(inertias)
|
|
88
|
+
knee = kneedle(ks, vals)
|
|
89
|
+
drops = -np.diff(vals)
|
|
90
|
+
L = [("brief", f"Elbow plot, k from {ks[0]} to {ks[-1]}.")]
|
|
91
|
+
if knee is None:
|
|
92
|
+
L.append(("brief", f"Inertia goes from {sp.num(vals[0])} at k {ks[0]} to {sp.num(vals[-1])} at k {ks[-1]} with no clear elbow."))
|
|
93
|
+
else:
|
|
94
|
+
kk = ks[knee]
|
|
95
|
+
L.append(("brief", f"Inertia falls from {sp.num(vals[0])} at k {ks[0]} to {sp.num(vals[knee])} at k {kk}, then levels off."))
|
|
96
|
+
shown = [f"{sp.num(drops[i])} from k {ks[i]} to {ks[i + 1]}" for i in range(min(knee, 3))]
|
|
97
|
+
after = drops[knee:]
|
|
98
|
+
text = f"Drop at each step: {sp.join(shown)}"
|
|
99
|
+
if len(after):
|
|
100
|
+
text += f", then {sp.num(after.max())} or less per step"
|
|
101
|
+
L.append(("brief", text + "."))
|
|
102
|
+
ties = _knee_tie(ks, vals, knee)
|
|
103
|
+
if ties:
|
|
104
|
+
both = sorted([knee] + ties)
|
|
105
|
+
L.append(("brief", f"The elbow is not clear-cut: k {sp.join([str(ks[i]) for i in both], 'or')} fit about equally "
|
|
106
|
+
f"by the Kneedle method, with k {kk} slightly ahead."))
|
|
107
|
+
else:
|
|
108
|
+
L.append(("brief", f"Elbow at k {kk}, by the Kneedle method."))
|
|
109
|
+
total = vals[0] - vals.min()
|
|
110
|
+
if total > 0:
|
|
111
|
+
L.append(("standard", f"By k {kk}, {sp.pct((vals[0] - vals[knee]) / total)} of the total drop is done."))
|
|
112
|
+
L.append(("standard", "Every drop: " + "; ".join(f"k {ks[i]} to {ks[i + 1]}, {sp.num(d)}" for i, d in enumerate(drops)) + "."))
|
|
113
|
+
if np.any(drops < 0):
|
|
114
|
+
L.append(("standard", "Inertia rises at some steps, which k-means randomness can cause; try more starts, n_init."))
|
|
115
|
+
L = [(lv, t) for lv, t in L if t]
|
|
116
|
+
ties = _knee_tie(ks, vals, knee) if knee is not None else []
|
|
117
|
+
facts = {"k": ks.tolist(), "inertia": vals.tolist(), "drops": drops.tolist(),
|
|
118
|
+
"elbow_k": int(ks[knee]) if knee is not None else None,
|
|
119
|
+
"elbow_candidates": sorted(int(ks[i]) for i in ([knee] + ties)) if knee is not None else []}
|
|
120
|
+
gloss = {"inertia": "Inertia is the total squared distance from each point to its cluster centre. It always falls as k grows.",
|
|
121
|
+
"elbow": ("The elbow is where adding clusters stops paying off: before it inertia drops fast, after it slowly. "
|
|
122
|
+
"The Kneedle method finds it as the point furthest below the straight line joining the ends of the "
|
|
123
|
+
"curve, with both axes scaled to 0 to 1."),
|
|
124
|
+
"kneedle": ("Kneedle scales both axes to 0 to 1 and picks the k furthest below the straight line joining the "
|
|
125
|
+
"first and last points. When another k scores within 5% of it, both are named. The result can "
|
|
126
|
+
"shift with the range of k tried, so try k up to about 10."),
|
|
127
|
+
"largest drop": ("The largest drop is usually the very first step, from 1 to 2 clusters, so it does not mark "
|
|
128
|
+
"the elbow. The elbow is where the drops level off.")}
|
|
129
|
+
advice = ["Confirm the elbow with silhouette scores, and check the clusters make sense for the problem.",
|
|
130
|
+
"Scale features first, for example with StandardScaler, or the widest-range feature decides the clusters."]
|
|
131
|
+
res = build("elbow", "k-means", facts, L, title="Elbow plot", level=level, glossary=gloss, advice=advice)
|
|
132
|
+
return _maybe_plot(res, plot, "elbow", k=ks, inertia=vals, knee=knee)
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
# ----- PCA -----------------------------------------------------------------------------
|
|
136
|
+
|
|
137
|
+
def pca(model=None, *, explained=None, level=None, plot=False):
|
|
138
|
+
"""Describe PCA explained variance from a fitted scikit-learn PCA or a list of variance shares."""
|
|
139
|
+
if explained is None:
|
|
140
|
+
if model is None:
|
|
141
|
+
raise ValueError("Give a fitted PCA model, or explained=[...] with each component's share of variance.")
|
|
142
|
+
if not hasattr(model, "explained_variance_ratio_"):
|
|
143
|
+
raise TypeError("The model has no explained_variance_ratio_; fit it first, or pass explained=[...].")
|
|
144
|
+
ratios = np.asarray(model.explained_variance_ratio_, float)
|
|
145
|
+
else:
|
|
146
|
+
ratios = np.asarray(explained, float)
|
|
147
|
+
if ratios.sum() > 1.0001:
|
|
148
|
+
ratios = ratios / ratios.sum() # variances, not shares
|
|
149
|
+
n = len(ratios)
|
|
150
|
+
cum = np.cumsum(ratios)
|
|
151
|
+
targets = config.thresholds["pca_targets"]
|
|
152
|
+
reach = {}
|
|
153
|
+
for tgt in targets:
|
|
154
|
+
hit = np.where(cum >= tgt - 1e-12)[0]
|
|
155
|
+
reach[tgt] = int(hit[0] + 1) if len(hit) else None
|
|
156
|
+
L = [("brief", f"PCA, {sp.plural(n, 'component')}.")]
|
|
157
|
+
first = f"First component explains {sp.pct(ratios[0])}"
|
|
158
|
+
if n > 1:
|
|
159
|
+
first += f", first two {sp.pct(cum[1])}"
|
|
160
|
+
L.append(("brief", first + "."))
|
|
161
|
+
# Group the targets reached by the same number of components: "2 components reach 80%, 90% and 95%".
|
|
162
|
+
by_count: dict = {}
|
|
163
|
+
for tgt, c in reach.items():
|
|
164
|
+
if c:
|
|
165
|
+
by_count.setdefault(c, []).append(sp.pct(tgt))
|
|
166
|
+
parts = [f"{sp.plural(c, 'component')} {'reaches' if c == 1 else 'reach'} {sp.join(tgts)}" for c, tgts in by_count.items()]
|
|
167
|
+
if parts:
|
|
168
|
+
L.append(("brief", sp.sentence("; ".join(parts))))
|
|
169
|
+
unreached = [sp.pct(tgt) for tgt, c in reach.items() if c is None]
|
|
170
|
+
if unreached:
|
|
171
|
+
L.append(("brief", f"These components together explain {sp.pct(cum[-1])}, short of {sp.join(unreached)}."))
|
|
172
|
+
knee = kneedle(np.arange(1, n + 1), ratios) if n >= 3 else None
|
|
173
|
+
if knee is not None:
|
|
174
|
+
L.append(("standard", f"Scree elbow at component {knee + 1}: after it each component adds little."))
|
|
175
|
+
L.append(("standard", "Each component: " + "; ".join(f"{i + 1}, {sp.pct(r)}" for i, r in enumerate(ratios[:12]))
|
|
176
|
+
+ ("." if n <= 12 else f"; and {n - 12} more.")))
|
|
177
|
+
L = [(lv, t) for lv, t in L if t]
|
|
178
|
+
facts = {"n_components": n, "explained": ratios.tolist(), "cumulative": cum.tolist(),
|
|
179
|
+
"components_for": {f"{int(k * 100)}%": v for k, v in reach.items()},
|
|
180
|
+
"scree_elbow": knee + 1 if knee is not None else None}
|
|
181
|
+
advice = []
|
|
182
|
+
if ratios[0] >= 0.9:
|
|
183
|
+
advice.append("One component explains almost everything. If features were not scaled, it may only follow the "
|
|
184
|
+
"feature with the largest numbers; refit after StandardScaler to check.")
|
|
185
|
+
if reach.get(0.9):
|
|
186
|
+
advice.append(f"Keeping {reach[0.9]} components keeps 90% of the variance; check model accuracy with that number before going lower.")
|
|
187
|
+
gloss = {"explained variance": ("Each principal component's explained variance is the share of the total spread in the "
|
|
188
|
+
"data that it captures. They add up to 100% over all components."),
|
|
189
|
+
"cumulative": "Cumulative variance is the running total: how much the first n components explain together.",
|
|
190
|
+
"scree elbow": "The scree elbow is where the share per component stops falling fast, found with the Kneedle method."}
|
|
191
|
+
res = build("pca", "explained variance", facts, L, title="PCA explained variance", level=level,
|
|
192
|
+
glossary=gloss, advice=advice or ["Nothing here needs fixing."])
|
|
193
|
+
return _maybe_plot(res, plot, "pca", ratios=ratios, cum=cum)
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
# ----- feature importance --------------------------------------------------------------
|
|
197
|
+
|
|
198
|
+
def importance(model=None, feature_names=None, *, values=None, level=None, plot=False):
|
|
199
|
+
"""Describe feature importance from a fitted model, or from ``values``.
|
|
200
|
+
|
|
201
|
+
Uses ``feature_importances_`` (tree models) or ``coef_`` (linear models). ``values`` can
|
|
202
|
+
be a dict, a Series with feature names as index, or a list with ``feature_names``.
|
|
203
|
+
"""
|
|
204
|
+
source = "values"
|
|
205
|
+
signed = None
|
|
206
|
+
model_name = None
|
|
207
|
+
if values is None:
|
|
208
|
+
if model is None:
|
|
209
|
+
raise ValueError("Give a fitted model, or values=... with one importance per feature.")
|
|
210
|
+
model_name = type(model).__name__
|
|
211
|
+
if hasattr(model, "feature_importances_"):
|
|
212
|
+
raw = np.asarray(model.feature_importances_, float)
|
|
213
|
+
source = "importance"
|
|
214
|
+
elif hasattr(model, "coef_"):
|
|
215
|
+
coef = np.asarray(model.coef_, float)
|
|
216
|
+
if coef.ndim == 2 and coef.shape[0] > 1:
|
|
217
|
+
raw = np.abs(coef).mean(axis=0)
|
|
218
|
+
source = "mean absolute coefficient over classes"
|
|
219
|
+
else:
|
|
220
|
+
signed = coef.ravel()
|
|
221
|
+
raw = np.abs(signed)
|
|
222
|
+
source = "coefficient"
|
|
223
|
+
else:
|
|
224
|
+
raise TypeError(f"{model_name} has neither feature_importances_ nor coef_. Pass values=... instead, "
|
|
225
|
+
"for example from sklearn.inspection.permutation_importance.")
|
|
226
|
+
if feature_names is None:
|
|
227
|
+
feature_names = getattr(model, "feature_names_in_", None)
|
|
228
|
+
if feature_names is None:
|
|
229
|
+
feature_names = [f"feature {i}" for i in range(len(raw))]
|
|
230
|
+
s = pd.Series(raw, index=[str(f) for f in feature_names])
|
|
231
|
+
else:
|
|
232
|
+
if isinstance(values, dict):
|
|
233
|
+
s = pd.Series(values, dtype=float)
|
|
234
|
+
elif isinstance(values, pd.Series):
|
|
235
|
+
s = values.astype(float)
|
|
236
|
+
else:
|
|
237
|
+
if feature_names is None:
|
|
238
|
+
raise ValueError("Give feature_names with a list of values.")
|
|
239
|
+
s = pd.Series(np.asarray(values, float), index=[str(f) for f in feature_names])
|
|
240
|
+
if (s < 0).any():
|
|
241
|
+
signed = s.to_numpy()
|
|
242
|
+
s = s.abs()
|
|
243
|
+
source = "absolute value"
|
|
244
|
+
if len(s) == 0:
|
|
245
|
+
raise ValueError("No features to describe.")
|
|
246
|
+
sign_map = dict(zip(s.index, signed)) if signed is not None else None
|
|
247
|
+
s = s.sort_values(ascending=False, kind="mergesort")
|
|
248
|
+
total = float(s.sum())
|
|
249
|
+
shares = s / total if total > 0 else s * 0
|
|
250
|
+
cum = shares.cumsum()
|
|
251
|
+
t = config.thresholds
|
|
252
|
+
n80 = int(np.searchsorted(cum.to_numpy(), t["importance_cumulative"] - 1e-12) + 1)
|
|
253
|
+
near_zero = list(shares.index[shares < t["importance_near_zero"]])
|
|
254
|
+
|
|
255
|
+
def item(k):
|
|
256
|
+
if sign_map is not None:
|
|
257
|
+
return f"{k} {sp.num(sign_map[k])}"
|
|
258
|
+
return f"{k} {sp.num(s[k])}"
|
|
259
|
+
|
|
260
|
+
what = "Coefficients" if source in ("coefficient",) else "Feature importance"
|
|
261
|
+
origin = f" from {model_name}" if model_name else ""
|
|
262
|
+
L = [("brief", f"{what}{origin}, {sp.plural(len(s), 'feature')}.")]
|
|
263
|
+
top = list(s.index[: config.max_items])
|
|
264
|
+
if source == "coefficient":
|
|
265
|
+
L.append(("brief", f"Largest in size: {sp.join([item(k) for k in top])}."))
|
|
266
|
+
else:
|
|
267
|
+
L.append(("brief", f"Top {len(top)}: {sp.join([item(k) for k in top])}, together {sp.pct(shares.iloc[:len(top)].sum())}."))
|
|
268
|
+
if len(s) > 1:
|
|
269
|
+
L.append(("brief", f"{sp.plural(n80, 'feature')} {'makes' if n80 == 1 else 'make'} up {sp.pct(t['importance_cumulative'])} of the total."))
|
|
270
|
+
L.append(("brief", f"Lowest: {item(s.index[-1])}."))
|
|
271
|
+
if near_zero:
|
|
272
|
+
L.append(("standard", f"{sp.plural(len(near_zero), 'feature')} near zero, under {sp.pct(t['importance_near_zero'])} of the total: "
|
|
273
|
+
f"{sp.capped(near_zero, where='.table')}."))
|
|
274
|
+
if source == "coefficient":
|
|
275
|
+
pos = [k for k in s.index if sign_map[k] > 0]
|
|
276
|
+
neg = [k for k in s.index if sign_map[k] < 0]
|
|
277
|
+
L.append(("standard", f"Positive, pushing the prediction up: {sp.capped(pos) or 'none'}. Negative: {sp.capped(neg) or 'none'}."))
|
|
278
|
+
L.append(("standard", "Coefficient size depends on each feature's units; compare them only if features were scaled."))
|
|
279
|
+
L.append(("standard", "All, largest first: " + "; ".join(f"{k} {sp.pct(v)}" for k, v in shares.head(15).items())
|
|
280
|
+
+ ("." if len(s) <= 15 else f"; and {len(s) - 15} more, see .table.")))
|
|
281
|
+
L.append(("full", f"Source: {source}."))
|
|
282
|
+
facts = {"n_features": len(s), "source": source, "model": model_name, "top": top,
|
|
283
|
+
"features_for_80pct": n80, "near_zero": near_zero,
|
|
284
|
+
"importance": {k: float(v) for k, v in s.items()}, "shares": {k: float(v) for k, v in shares.items()}}
|
|
285
|
+
advice = []
|
|
286
|
+
if near_zero:
|
|
287
|
+
advice.append("Near-zero features can usually be dropped; confirm the score does not fall without them.")
|
|
288
|
+
if source == "importance":
|
|
289
|
+
advice.append("Tree importance favours features with many distinct values and splits credit between correlated "
|
|
290
|
+
"features; permutation importance on held-out data is a fairer check.")
|
|
291
|
+
gloss = {"importance": ("Importance shows how much a model relied on each feature. For tree models it is the total "
|
|
292
|
+
"reduction in impurity from splits on that feature, scaled to add up to 1."),
|
|
293
|
+
"share": "A feature's share is its importance divided by the total of all features."}
|
|
294
|
+
res = build("importance", model_name or "features", facts, L, title=f"{what}{origin}", level=level,
|
|
295
|
+
glossary=gloss, advice=advice or ["Nothing here needs fixing."], extras={"table": s})
|
|
296
|
+
return _maybe_plot(res, plot, "importance", names=list(s.index), values=s.to_numpy())
|
|
297
|
+
|
|
298
|
+
|
|
299
|
+
# ----- ROC -----------------------------------------------------------------------------
|
|
300
|
+
|
|
301
|
+
def roc_points(y_true, y_score, pos_label=None):
|
|
302
|
+
"""False and true positive rates at every threshold, highest threshold first."""
|
|
303
|
+
y = np.asarray(y_true)
|
|
304
|
+
score = np.asarray(y_score, float)
|
|
305
|
+
if y.shape[0] != score.shape[0]:
|
|
306
|
+
raise ValueError("y_true and y_score need the same length.")
|
|
307
|
+
if score.ndim != 1:
|
|
308
|
+
raise ValueError("y_score needs one score per case: the probability of the positive class, "
|
|
309
|
+
"for example model.predict_proba(X)[:, 1].")
|
|
310
|
+
labels = np.unique(y[~pd.isna(y)])
|
|
311
|
+
if len(labels) != 2:
|
|
312
|
+
raise ValueError(f"ROC needs exactly two classes; found {len(labels)}. For more classes, describe one class against the rest.")
|
|
313
|
+
if pos_label is None:
|
|
314
|
+
pos_label = labels.max()
|
|
315
|
+
pos = (y == pos_label)
|
|
316
|
+
order = np.argsort(-score, kind="mergesort")
|
|
317
|
+
s_sorted, p_sorted = score[order], pos[order]
|
|
318
|
+
distinct = np.where(np.diff(s_sorted))[0]
|
|
319
|
+
idx = np.r_[distinct, len(s_sorted) - 1]
|
|
320
|
+
tps = np.cumsum(p_sorted)[idx]
|
|
321
|
+
fps = (idx + 1) - tps
|
|
322
|
+
P, N = pos.sum(), (~pos).sum()
|
|
323
|
+
tpr = np.r_[0, tps / P]
|
|
324
|
+
fpr = np.r_[0, fps / N]
|
|
325
|
+
thr = np.r_[np.inf, s_sorted[idx]]
|
|
326
|
+
return fpr, tpr, thr, int(P), int(N), pos_label
|
|
327
|
+
|
|
328
|
+
|
|
329
|
+
def roc(y_true, y_score, *, pos_label=None, level=None, plot=False):
|
|
330
|
+
"""Describe a ROC curve for a binary classifier from true labels and scores."""
|
|
331
|
+
fpr, tpr, thr, P, N, pos_label = roc_points(y_true, y_score, pos_label)
|
|
332
|
+
auc = float(np.trapezoid(tpr, fpr)) if hasattr(np, "trapezoid") else float(np.trapz(tpr, fpr))
|
|
333
|
+
j = tpr - fpr
|
|
334
|
+
best = int(np.argmax(j))
|
|
335
|
+
band = rules.auc_band(auc)
|
|
336
|
+
L = [("brief", f"ROC curve, {sp.plural(P + N, 'case')}, {sp.integer(P)} positive, class {pos_label}."),
|
|
337
|
+
("brief", f"AUC {sp.num(auc)}, {band}.")]
|
|
338
|
+
if auc < 0.5:
|
|
339
|
+
L.append(("brief", "Below chance: the scores may be reversed, with high scores meaning the other class."))
|
|
340
|
+
L.append(("brief", f"Best threshold by Youden's J: {sp.num(thr[best])}, true positive rate {sp.num(tpr[best])} "
|
|
341
|
+
f"at false positive rate {sp.num(fpr[best])}."))
|
|
342
|
+
|
|
343
|
+
def tpr_at(f):
|
|
344
|
+
return float(np.interp(f, fpr, tpr))
|
|
345
|
+
|
|
346
|
+
L.append(("standard", f"At a false positive rate of 0.1, the true positive rate is {sp.num(tpr_at(0.1))}; at 0.2, {sp.num(tpr_at(0.2))}."))
|
|
347
|
+
reach90 = np.where(tpr >= 0.9)[0]
|
|
348
|
+
if len(reach90):
|
|
349
|
+
i = int(reach90[0])
|
|
350
|
+
L.append(("standard", f"To catch 90% of positives, accept a false positive rate of {sp.num(fpr[i])}, threshold {sp.num(thr[i])}."))
|
|
351
|
+
L.append(("full", f"Gini coefficient {sp.num(2 * auc - 1)}. {sp.plural(len(thr) - 1, 'distinct threshold')}."))
|
|
352
|
+
facts = {"auc": auc, "band": band, "n": P + N, "n_positive": P, "n_negative": N, "pos_label": pos_label,
|
|
353
|
+
"best_threshold": float(thr[best]), "best_tpr": float(tpr[best]), "best_fpr": float(fpr[best]),
|
|
354
|
+
"youden_j": float(j[best]), "gini": 2 * auc - 1}
|
|
355
|
+
gloss = {"auc": ("AUC, the area under the ROC curve, is the chance that a random positive case gets a higher score "
|
|
356
|
+
"than a random negative one. 0.5 is chance, 1 is perfect. Bands, Hosmer and Lemeshow: 0.9 outstanding, "
|
|
357
|
+
"0.8 excellent, 0.7 acceptable, below that weak."),
|
|
358
|
+
"true positive rate": "The true positive rate, or recall, is the share of real positives the model catches.",
|
|
359
|
+
"false positive rate": "The false positive rate is the share of real negatives wrongly flagged as positive.",
|
|
360
|
+
"youden's j": "Youden's J is the true positive rate minus the false positive rate; its highest point balances the two."}
|
|
361
|
+
advice = ["Pick the threshold by the cost of each mistake, not only by Youden's J.",
|
|
362
|
+
"With rare positives, also check the precision-recall curve; ROC can look good while precision is low."]
|
|
363
|
+
if P / (P + N) < config.thresholds["imbalance"]:
|
|
364
|
+
advice.insert(0, f"Only {sp.pct(P / (P + N))} of cases are positive, so precision matters: check it before trusting the AUC.")
|
|
365
|
+
res = build("roc", f"class {pos_label}", facts, L, title="ROC curve", level=level, glossary=gloss, advice=advice,
|
|
366
|
+
extras={"curve": pd.DataFrame({"fpr": fpr, "tpr": tpr, "threshold": thr}), "tpr_at": tpr_at})
|
|
367
|
+
return _maybe_plot(res, plot, "roc", fpr=fpr, tpr=tpr, best=best, auc=auc)
|
|
368
|
+
|
|
369
|
+
|
|
370
|
+
# ----- residuals -----------------------------------------------------------------------
|
|
371
|
+
|
|
372
|
+
def residuals(y_true, y_pred, *, level=None, plot=False):
|
|
373
|
+
"""Describe a residual plot for a regression model: actual minus predicted against predicted."""
|
|
374
|
+
yt = np.asarray(y_true, float).ravel()
|
|
375
|
+
yp = np.asarray(y_pred, float).ravel()
|
|
376
|
+
if len(yt) != len(yp):
|
|
377
|
+
raise ValueError("y_true and y_pred need the same length.")
|
|
378
|
+
keep = np.isfinite(yt) & np.isfinite(yp)
|
|
379
|
+
yt, yp = yt[keep], yp[keep]
|
|
380
|
+
n = len(yt)
|
|
381
|
+
if n < 3:
|
|
382
|
+
return build("residuals", "model", {"n": n}, [("brief", "Too few points to describe residuals.")], level=level)
|
|
383
|
+
e = yt - yp
|
|
384
|
+
mean, sd = float(e.mean()), float(e.std(ddof=1))
|
|
385
|
+
mae, rmse = float(np.mean(np.abs(e))), float(np.sqrt(np.mean(e ** 2)))
|
|
386
|
+
ss_tot = float(np.sum((yt - yt.mean()) ** 2))
|
|
387
|
+
r2 = 1 - float(np.sum(e ** 2)) / ss_tot if ss_tot > 0 else float("nan")
|
|
388
|
+
t = config.thresholds
|
|
389
|
+
# Spread against predicted values (Breusch-Pagan, Koenker form).
|
|
390
|
+
if np.ptp(yp) > 0 and np.std(e ** 2) > 0:
|
|
391
|
+
rc = np.corrcoef(yp, e ** 2)[0, 1]
|
|
392
|
+
bp_p = float(stats.chi2.sf(n * rc ** 2, 1))
|
|
393
|
+
spread_trend = float(stats.spearmanr(yp, np.abs(e))[0])
|
|
394
|
+
else:
|
|
395
|
+
bp_p, spread_trend = float("nan"), float("nan")
|
|
396
|
+
# Curve left in the residuals: is a squared term in the predictions significant?
|
|
397
|
+
curve_p = float("nan")
|
|
398
|
+
if n >= 10 and np.ptp(yp) > 0:
|
|
399
|
+
z = (yp - yp.mean()) / yp.std()
|
|
400
|
+
X = np.column_stack([np.ones(n), z, z ** 2])
|
|
401
|
+
beta, *_ = np.linalg.lstsq(X, e, rcond=None)
|
|
402
|
+
res_ = e - X @ beta
|
|
403
|
+
dof = n - 3
|
|
404
|
+
s2 = res_ @ res_ / dof
|
|
405
|
+
cov = s2 * np.linalg.inv(X.T @ X)
|
|
406
|
+
tval = beta[2] / math.sqrt(cov[2, 2]) if cov[2, 2] > 0 else 0.0
|
|
407
|
+
curve_p = float(2 * stats.t.sf(abs(tval), dof))
|
|
408
|
+
dw = float(np.sum(np.diff(e) ** 2) / np.sum(e ** 2)) if np.sum(e ** 2) > 0 else float("nan")
|
|
409
|
+
zres = (e - mean) / sd if sd > 0 else np.zeros(n)
|
|
410
|
+
big = np.where(np.abs(zres) > t["residual_z"])[0]
|
|
411
|
+
big = big[np.argsort(-np.abs(zres[big]))]
|
|
412
|
+
|
|
413
|
+
L = [("brief", f"Residuals, actual minus predicted, {sp.plural(n, 'point')}.")]
|
|
414
|
+
# A mean that is only floating-point noise is spoken as 0.
|
|
415
|
+
mean_text = "0" if sd > 0 and abs(mean) < 1e-9 * sd else sp.num(mean)
|
|
416
|
+
if sd > 0 and abs(mean) < t["residual_bias"] * sd:
|
|
417
|
+
L.append(("brief", f"Centred on zero: mean {mean_text}, against a spread of {sp.num(sd)}."))
|
|
418
|
+
else:
|
|
419
|
+
side = "under-predicts" if mean > 0 else "over-predicts"
|
|
420
|
+
L.append(("brief", f"Not centred on zero: mean {sp.num(mean)}, so the model {side} on average; spread {sp.num(sd)}."))
|
|
421
|
+
if not math.isnan(bp_p) and bp_p < t["normality_alpha"]:
|
|
422
|
+
word = "grows" if spread_trend > 0 else "shrinks"
|
|
423
|
+
L.append(("brief", f"Spread {word} with the predicted value, Breusch-Pagan {sp.pvalue(bp_p)}: heteroscedastic."))
|
|
424
|
+
elif not math.isnan(bp_p):
|
|
425
|
+
L.append(("brief", f"Spread is steady across predicted values, Breusch-Pagan {sp.pvalue(bp_p)}."))
|
|
426
|
+
if not math.isnan(curve_p) and curve_p < t["normality_alpha"]:
|
|
427
|
+
L.append(("brief", f"Residuals curve against the predicted values, {sp.pvalue(curve_p)}: a pattern the model misses."))
|
|
428
|
+
else:
|
|
429
|
+
L.append(("brief", "No curve left in the residuals."))
|
|
430
|
+
if len(big):
|
|
431
|
+
L.append(("brief", f"{sp.plural(len(big), 'residual')} beyond {sp.num(t['residual_z'])} standard deviations; largest {sp.num(e[big[0]])}."))
|
|
432
|
+
L.append(("standard", f"Mean absolute error {sp.num(mae)}, root mean squared error {sp.num(rmse)}, R-squared {sp.num(r2)}."))
|
|
433
|
+
L.append(("standard", f"Residuals run {sp.range_text(e.min(), e.max())}; half lie between {sp.num(np.percentile(e, 25))} and {sp.num(np.percentile(e, 75))}."))
|
|
434
|
+
if 3 <= n <= t["shapiro_max_n"] and sd > 0:
|
|
435
|
+
sw = float(stats.shapiro(e).pvalue)
|
|
436
|
+
L.append(("full", f"Residual normality, Shapiro-Wilk {sp.pvalue(sw)}: {rules.normal_verdict(sw)}."))
|
|
437
|
+
L.append(("full", f"Durbin-Watson {sp.num(dw)}, in the order given; near 2 means no autocorrelation, which matters only for ordered data such as time."))
|
|
438
|
+
facts = {"n": n, "mean": mean, "std": sd, "mae": mae, "rmse": rmse, "r2": r2, "bp_p": bp_p,
|
|
439
|
+
"curve_p": curve_p, "durbin_watson": dw, "n_large": int(len(big))}
|
|
440
|
+
advice = []
|
|
441
|
+
if not (sd > 0 and abs(mean) < t["residual_bias"] * sd):
|
|
442
|
+
advice.append("The model is biased: check for a missing intercept, a shifted target or a data leak between train and test.")
|
|
443
|
+
if not math.isnan(bp_p) and bp_p < t["normality_alpha"]:
|
|
444
|
+
advice.append("Uneven spread: try predicting the log of the target, or a model that handles it, and use robust intervals.")
|
|
445
|
+
if not math.isnan(curve_p) and curve_p < t["normality_alpha"]:
|
|
446
|
+
advice.append("The curve means a non-linear effect is missed: add transformed features or try a tree-based model.")
|
|
447
|
+
if len(big):
|
|
448
|
+
advice.append("Look at the largest residuals: data errors, or a kind of case the model has not learned.")
|
|
449
|
+
gloss = {"residual": "A residual is the actual value minus the predicted value. Positive means the model predicted too low.",
|
|
450
|
+
"heteroscedastic": "Heteroscedastic means the residual spread changes with the predicted value; Breusch-Pagan p below 0.05 means it does.",
|
|
451
|
+
"rmse": "Root mean squared error is the typical size of a mistake, in the target's units, weighting big mistakes more.",
|
|
452
|
+
"mae": "Mean absolute error is the average size of a mistake, in the target's units."}
|
|
453
|
+
res = build("residuals", "model", facts, L, title="Residual plot", level=level, glossary=gloss,
|
|
454
|
+
advice=advice or ["The residuals show no warning signs."],
|
|
455
|
+
extras={"residuals": e, "large": pd.DataFrame({"actual": yt[big], "predicted": yp[big], "residual": e[big]})})
|
|
456
|
+
return _maybe_plot(res, plot, "residuals", pred=yp, resid=e)
|
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
"""Dataset overview: what a sighted analyst gets from a glance at a profile report."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import pandas as pd
|
|
6
|
+
|
|
7
|
+
from .. import rules
|
|
8
|
+
from .. import speech as sp
|
|
9
|
+
from ..config import config
|
|
10
|
+
from ..result import build
|
|
11
|
+
from ..errors import SpeechKeyError
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def _kind(s: pd.Series) -> str:
|
|
15
|
+
if pd.api.types.is_bool_dtype(s):
|
|
16
|
+
return "true-false"
|
|
17
|
+
if pd.api.types.is_datetime64_any_dtype(s):
|
|
18
|
+
return "date"
|
|
19
|
+
if pd.api.types.is_numeric_dtype(s):
|
|
20
|
+
return "numeric"
|
|
21
|
+
return "text or category"
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _id_like(s: pd.Series, n_rows: int) -> bool:
|
|
25
|
+
non_null = s.dropna()
|
|
26
|
+
if len(non_null) < 20:
|
|
27
|
+
return False
|
|
28
|
+
ratio = non_null.nunique() / len(non_null)
|
|
29
|
+
if ratio < config.thresholds["id_unique_ratio"]:
|
|
30
|
+
return False
|
|
31
|
+
if pd.api.types.is_integer_dtype(s):
|
|
32
|
+
span = non_null.max() - non_null.min() + 1
|
|
33
|
+
return bool(non_null.is_monotonic_increasing or span <= 1.1 * len(non_null))
|
|
34
|
+
return _kind(s) == "text or category"
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def overview(df: pd.DataFrame, *, target=None, level=None):
|
|
38
|
+
"""Describe a whole DataFrame: size, column types, missing values, duplicates and odd columns."""
|
|
39
|
+
if not isinstance(df, pd.DataFrame):
|
|
40
|
+
raise TypeError("overview needs a pandas DataFrame.")
|
|
41
|
+
t = config.thresholds
|
|
42
|
+
n_rows, n_cols = df.shape
|
|
43
|
+
rows = []
|
|
44
|
+
for col in df.columns:
|
|
45
|
+
s = df[col]
|
|
46
|
+
missing = int(s.isna().sum())
|
|
47
|
+
try:
|
|
48
|
+
unique = int(s.nunique(dropna=True))
|
|
49
|
+
except TypeError: # unhashable values such as lists
|
|
50
|
+
unique = int(s.astype(str).nunique(dropna=True))
|
|
51
|
+
non_null = n_rows - missing
|
|
52
|
+
top_share = float(s.value_counts(dropna=True).iloc[0] / non_null) if non_null and unique else float("nan")
|
|
53
|
+
rows.append({"column": str(col), "dtype": str(s.dtype), "kind": _kind(s), "missing": missing,
|
|
54
|
+
"missing_share": missing / n_rows if n_rows else 0.0, "unique": unique,
|
|
55
|
+
"top_share": top_share, "id_like": _id_like(s, n_rows)})
|
|
56
|
+
cols = pd.DataFrame(rows).set_index("column")
|
|
57
|
+
|
|
58
|
+
kinds = cols["kind"].value_counts()
|
|
59
|
+
missing = cols[cols["missing"] > 0].sort_values("missing_share", ascending=False)
|
|
60
|
+
try:
|
|
61
|
+
dup_mask = df.duplicated()
|
|
62
|
+
except TypeError:
|
|
63
|
+
dup_mask = df.astype(str).duplicated()
|
|
64
|
+
n_dup = int(dup_mask.sum())
|
|
65
|
+
constant = list(cols.index[cols["unique"] <= 1])
|
|
66
|
+
near_constant = list(cols.index[(cols["unique"] > 1) & (cols["top_share"] >= t["near_constant_share"])])
|
|
67
|
+
id_like = list(cols.index[cols["id_like"]])
|
|
68
|
+
high_card = list(cols.index[(cols["kind"] == "text or category") & (cols["unique"] > t["high_cardinality"]) & ~cols["id_like"]])
|
|
69
|
+
total_missing = float(cols["missing"].sum() / (n_rows * n_cols)) if n_rows and n_cols else 0.0
|
|
70
|
+
|
|
71
|
+
order = ["numeric", "text or category", "true-false", "date"]
|
|
72
|
+
kind_text = sp.join([f"{sp.integer(kinds[k])} {k}" for k in order if k in kinds])
|
|
73
|
+
L = [("brief", f"Dataset: {sp.plural(n_rows, 'row')}, {sp.plural(n_cols, 'column')}: {kind_text}.")]
|
|
74
|
+
if missing.empty:
|
|
75
|
+
L.append(("brief", "No missing values."))
|
|
76
|
+
else:
|
|
77
|
+
named = sp.capped([f"{c} {sp.pct(r['missing_share'])}" for c, r in missing.iterrows()], where=".columns")
|
|
78
|
+
L.append(("brief", f"{sp.plural(len(missing), 'column')} {'has' if len(missing) == 1 else 'have'} missing values; most missing: {named}."))
|
|
79
|
+
L.append(("brief", "No duplicate rows." if n_dup == 0 else f"{sp.plural(n_dup, 'duplicate row')}, {sp.pct(n_dup / n_rows)}."))
|
|
80
|
+
if id_like:
|
|
81
|
+
L.append(("brief", f"Identifier-like: {sp.capped(id_like)}."))
|
|
82
|
+
if constant:
|
|
83
|
+
L.append(("brief", f"Constant: {sp.capped(constant)}."))
|
|
84
|
+
if near_constant:
|
|
85
|
+
L.append(("brief", f"Nearly constant, one value in {sp.pct(t['near_constant_share'])} or more of rows: {sp.capped(near_constant)}."))
|
|
86
|
+
|
|
87
|
+
facts = {"n_rows": n_rows, "n_columns": n_cols, "n_duplicates": n_dup, "missing_cell_share": total_missing,
|
|
88
|
+
"columns_with_missing": list(missing.index), "constant": constant, "near_constant": near_constant,
|
|
89
|
+
"id_like": id_like, "high_cardinality": high_card,
|
|
90
|
+
**{f"n_{k.replace(' ', '_').replace('-', '_')}": int(kinds.get(k, 0)) for k in order}}
|
|
91
|
+
|
|
92
|
+
advice = []
|
|
93
|
+
if target is not None:
|
|
94
|
+
if target not in df.columns:
|
|
95
|
+
raise SpeechKeyError(f"No column named {target!r} for target.")
|
|
96
|
+
ts = df[target].dropna()
|
|
97
|
+
if _kind(df[target]) == "numeric" and ts.nunique() > t["max_target_classes"]:
|
|
98
|
+
skew = float(ts.skew())
|
|
99
|
+
L.append(("brief", f"Target {target}: numeric, {rules.skew_words(skew)}, skewness {sp.num(skew)}."))
|
|
100
|
+
facts["target_skewness"] = skew
|
|
101
|
+
else:
|
|
102
|
+
shares = ts.value_counts(normalize=True)
|
|
103
|
+
band = rules.balance_band(float(shares.min()))
|
|
104
|
+
parts = sp.capped([f"{k} at {sp.pct(v)}" for k, v in shares.items()], where=".target_shares")
|
|
105
|
+
L.append(("brief", f"Target {target}: {sp.plural(len(shares), 'class', 'classes')}, {parts}; {band}."))
|
|
106
|
+
facts["target_shares"] = {str(k): float(v) for k, v in shares.items()}
|
|
107
|
+
facts["target_balance"] = band
|
|
108
|
+
if band != "balanced":
|
|
109
|
+
advice.append(f"The target is {band}: use a stratified split, class weights or resampling, and judge the model "
|
|
110
|
+
"with precision, recall or F1 rather than accuracy alone.")
|
|
111
|
+
|
|
112
|
+
for k in order:
|
|
113
|
+
names = list(cols.index[cols["kind"] == k])
|
|
114
|
+
if names:
|
|
115
|
+
L.append(("standard", f"{k.capitalize()} columns: {sp.capped(names, where='.columns', limit=10)}."))
|
|
116
|
+
if high_card:
|
|
117
|
+
L.append(("standard", f"High cardinality, more than {t['high_cardinality']} categories: {sp.capped(high_card)}."))
|
|
118
|
+
if not missing.empty:
|
|
119
|
+
L.append(("standard", f"{sp.pct(total_missing)} of all cells are missing."))
|
|
120
|
+
for c, r in cols.iterrows():
|
|
121
|
+
L.append(("full", f"{c}: {r['kind']}, {sp.integer(r['missing'])} missing, {sp.plural(r['unique'], 'unique value')}."))
|
|
122
|
+
|
|
123
|
+
for c, r in missing.iterrows():
|
|
124
|
+
band = rules.missing_band(r["missing_share"])
|
|
125
|
+
if band == "high":
|
|
126
|
+
advice.append(f"{c} is {sp.pct(r['missing_share'])} missing: consider dropping it or keeping only a missing-or-not flag.")
|
|
127
|
+
moderate = [c for c, r in missing.iterrows() if rules.missing_band(r["missing_share"]) == "moderate"]
|
|
128
|
+
if moderate:
|
|
129
|
+
advice.append(f"Moderate missing values in {sp.join(moderate)}: impute, and add a column marking which rows were missing.")
|
|
130
|
+
if id_like:
|
|
131
|
+
advice.append(f"Drop identifier-like columns before modelling: {sp.join(id_like)}.")
|
|
132
|
+
if constant:
|
|
133
|
+
advice.append(f"Drop constant columns; they carry no information: {sp.join(constant)}.")
|
|
134
|
+
if n_dup:
|
|
135
|
+
advice.append(f"Check the {sp.plural(n_dup, 'duplicate row')}; drop them if they are repeated records, not real repeats.")
|
|
136
|
+
if high_card:
|
|
137
|
+
advice.append(f"For high-cardinality columns such as {sp.join(high_card[:3])}, prefer frequency or target encoding over one-hot encoding.")
|
|
138
|
+
|
|
139
|
+
gloss = {
|
|
140
|
+
"identifier-like": (
|
|
141
|
+
f"A column is identifier-like when at least {sp.pct(t['id_unique_ratio'])} of its values are unique and it is text, "
|
|
142
|
+
"or whole numbers that count up or fill a range, such as a row ID. It names rows rather than describing them."),
|
|
143
|
+
"nearly constant": (
|
|
144
|
+
f"A column is nearly constant when one value fills {sp.pct(t['near_constant_share'])} or more of its non-missing rows."),
|
|
145
|
+
"high cardinality": (f"A text or category column with more than {t['high_cardinality']} distinct values."),
|
|
146
|
+
"duplicate rows": "Rows identical to an earlier row in every column.",
|
|
147
|
+
"missing values": (
|
|
148
|
+
f"Bands used per column: below {sp.pct(t['missing']['low'])} low, up to {sp.pct(t['missing']['high'])} moderate, above that high."),
|
|
149
|
+
}
|
|
150
|
+
if target is not None:
|
|
151
|
+
gloss["class balance"] = (
|
|
152
|
+
f"Balance is judged by the smallest class: below {sp.pct(t['imbalance'])} imbalanced, "
|
|
153
|
+
f"below {sp.pct(t['severe_imbalance'])} severely imbalanced.")
|
|
154
|
+
|
|
155
|
+
return build("overview", "dataset", facts, L, title="Dataset overview", level=level, glossary=gloss,
|
|
156
|
+
advice=advice or ["Nothing in the overview needs fixing."],
|
|
157
|
+
extras={"columns": cols, "duplicates": df[dup_mask]})
|