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,40 @@
|
|
|
1
|
+
"""speechplotlib: screen-reader-friendly descriptions of data science charts.
|
|
2
|
+
|
|
3
|
+
import speechplotlib as spl
|
|
4
|
+
df.spl.overview()
|
|
5
|
+
h = df.spl.hist("price") # reads the description
|
|
6
|
+
h.skewness # every number is kept on the result
|
|
7
|
+
h.detail(); h.explain("skewness"); h.advice()
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from . import accessor as _accessor # noqa: F401 registers df.spl and series.spl
|
|
11
|
+
from .analyzers import (bar, box, corr, ecdf, elbow, hist, importance, kde, line, overview, pca, pie, qq,
|
|
12
|
+
regression, residuals, roc, scatter, violin)
|
|
13
|
+
from .config import config
|
|
14
|
+
from .result import Result
|
|
15
|
+
from .session import session
|
|
16
|
+
from .var import HapticVar, var
|
|
17
|
+
|
|
18
|
+
__version__ = "0.1.0"
|
|
19
|
+
__author__ = "Sugumar S"
|
|
20
|
+
__email__ = "ssugumar2001@gmail.com"
|
|
21
|
+
__license__ = "MIT"
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def get(name: str):
|
|
25
|
+
"""Bring back a saved result, for example ``spl.get("hist:price")``."""
|
|
26
|
+
return session.get(name)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def __getattr__(attr):
|
|
30
|
+
if attr == "last":
|
|
31
|
+
return session.last
|
|
32
|
+
raise AttributeError(f"module 'speechplotlib' has no attribute {attr!r}")
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
__all__ = [
|
|
36
|
+
"overview", "hist", "kde", "box", "violin", "qq", "ecdf",
|
|
37
|
+
"scatter", "regression", "corr", "bar", "pie",
|
|
38
|
+
"line", "elbow", "pca", "importance", "roc", "residuals",
|
|
39
|
+
"var", "HapticVar", "Result", "config", "session", "get", "last",
|
|
40
|
+
]
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
"""``df.spl`` and ``series.spl``: the same calls as the ``spl`` functions, read like ``df.plot``."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import pandas as pd
|
|
6
|
+
|
|
7
|
+
from . import analyzers
|
|
8
|
+
from .var import HapticVar
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
@pd.api.extensions.register_dataframe_accessor("spl")
|
|
12
|
+
class DataFrameSpeech:
|
|
13
|
+
"""Describe charts of this DataFrame: ``df.spl.hist("price")``."""
|
|
14
|
+
|
|
15
|
+
def __init__(self, df: pd.DataFrame) -> None:
|
|
16
|
+
self._df = df
|
|
17
|
+
|
|
18
|
+
# dataset
|
|
19
|
+
def overview(self, target=None, **kw):
|
|
20
|
+
return analyzers.overview(self._df, target=target, **kw)
|
|
21
|
+
|
|
22
|
+
# distribution
|
|
23
|
+
def hist(self, column=None, **kw):
|
|
24
|
+
return analyzers.hist(self._df, column, **kw)
|
|
25
|
+
|
|
26
|
+
def kde(self, column=None, **kw):
|
|
27
|
+
return analyzers.kde(self._df, column, **kw)
|
|
28
|
+
|
|
29
|
+
def box(self, column=None, by=None, **kw):
|
|
30
|
+
return analyzers.box(self._df, column, by=by, **kw)
|
|
31
|
+
|
|
32
|
+
def violin(self, column=None, by=None, **kw):
|
|
33
|
+
return analyzers.violin(self._df, column, by=by, **kw)
|
|
34
|
+
|
|
35
|
+
def qq(self, column=None, **kw):
|
|
36
|
+
return analyzers.qq(self._df, column, **kw)
|
|
37
|
+
|
|
38
|
+
def ecdf(self, column=None, **kw):
|
|
39
|
+
return analyzers.ecdf(self._df, column, **kw)
|
|
40
|
+
|
|
41
|
+
# relationship
|
|
42
|
+
def scatter(self, x, y, **kw):
|
|
43
|
+
return analyzers.scatter(self._df, x, y, **kw)
|
|
44
|
+
|
|
45
|
+
def regression(self, x, y, **kw):
|
|
46
|
+
return analyzers.regression(self._df, x, y, **kw)
|
|
47
|
+
|
|
48
|
+
def corr(self, target=None, method="pearson", **kw):
|
|
49
|
+
return analyzers.corr(self._df, target=target, method=method, **kw)
|
|
50
|
+
|
|
51
|
+
# categories
|
|
52
|
+
def bar(self, column, values=None, agg="sum", **kw):
|
|
53
|
+
return analyzers.bar(self._df, column, values=values, agg=agg, **kw)
|
|
54
|
+
|
|
55
|
+
def pie(self, column, values=None, agg="sum", **kw):
|
|
56
|
+
return analyzers.pie(self._df, column, values=values, agg=agg, **kw)
|
|
57
|
+
|
|
58
|
+
# trend
|
|
59
|
+
def line(self, y, x=None, **kw):
|
|
60
|
+
return analyzers.line(self._df, y, x=x, **kw)
|
|
61
|
+
|
|
62
|
+
# haptic variables
|
|
63
|
+
def var(self, column) -> HapticVar:
|
|
64
|
+
return HapticVar(self._df, column)
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
@pd.api.extensions.register_series_accessor("spl")
|
|
68
|
+
class SeriesSpeech:
|
|
69
|
+
"""Describe charts of this Series: ``df["price"].spl.hist()``."""
|
|
70
|
+
|
|
71
|
+
def __init__(self, s: pd.Series) -> None:
|
|
72
|
+
self._s = s
|
|
73
|
+
|
|
74
|
+
def hist(self, **kw):
|
|
75
|
+
return analyzers.hist(self._s, **kw)
|
|
76
|
+
|
|
77
|
+
def kde(self, **kw):
|
|
78
|
+
return analyzers.kde(self._s, **kw)
|
|
79
|
+
|
|
80
|
+
def box(self, **kw):
|
|
81
|
+
return analyzers.box(self._s, **kw)
|
|
82
|
+
|
|
83
|
+
def violin(self, **kw):
|
|
84
|
+
return analyzers.violin(self._s, **kw)
|
|
85
|
+
|
|
86
|
+
def qq(self, **kw):
|
|
87
|
+
return analyzers.qq(self._s, **kw)
|
|
88
|
+
|
|
89
|
+
def ecdf(self, **kw):
|
|
90
|
+
return analyzers.ecdf(self._s, **kw)
|
|
91
|
+
|
|
92
|
+
def bar(self, **kw):
|
|
93
|
+
return analyzers.bar(self._s, **kw)
|
|
94
|
+
|
|
95
|
+
def pie(self, **kw):
|
|
96
|
+
return analyzers.pie(self._s, **kw)
|
|
97
|
+
|
|
98
|
+
def line(self, x=None, **kw):
|
|
99
|
+
return analyzers.line(self._s, x=x, **kw)
|
|
100
|
+
|
|
101
|
+
def var(self) -> HapticVar:
|
|
102
|
+
return HapticVar(self._s)
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
from .categorical import bar, pie
|
|
2
|
+
from .distribution import box, ecdf, hist, kde, qq, violin
|
|
3
|
+
from .model import elbow, importance, pca, residuals, roc
|
|
4
|
+
from .overview import overview
|
|
5
|
+
from .relationship import corr, regression, scatter
|
|
6
|
+
from .trend import line
|
|
7
|
+
|
|
8
|
+
__all__ = [
|
|
9
|
+
"overview", "hist", "kde", "box", "violin", "qq", "ecdf",
|
|
10
|
+
"scatter", "regression", "corr", "bar", "pie",
|
|
11
|
+
"line", "elbow", "pca", "importance", "roc", "residuals",
|
|
12
|
+
]
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
"""Bring user input into a clean numeric Series and record what was dropped."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
|
|
7
|
+
import numpy as np
|
|
8
|
+
import pandas as pd
|
|
9
|
+
|
|
10
|
+
from .. import speech as sp
|
|
11
|
+
from ..errors import SpeechKeyError
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
@dataclass
|
|
15
|
+
class NumericInput:
|
|
16
|
+
values: np.ndarray # finite values only, original order
|
|
17
|
+
series: pd.Series # finite values with the original index
|
|
18
|
+
name: str
|
|
19
|
+
n_total: int
|
|
20
|
+
n_missing: int # NaN, None and infinite
|
|
21
|
+
n_infinite: int
|
|
22
|
+
frame: pd.DataFrame | None
|
|
23
|
+
|
|
24
|
+
@property
|
|
25
|
+
def n(self) -> int:
|
|
26
|
+
return len(self.values)
|
|
27
|
+
|
|
28
|
+
def missing_phrase(self) -> str:
|
|
29
|
+
if self.n_missing == 0:
|
|
30
|
+
return "none missing"
|
|
31
|
+
text = f"{sp.integer(self.n_missing)} missing, {sp.pct(self.n_missing / self.n_total)}"
|
|
32
|
+
if self.n_infinite:
|
|
33
|
+
text += f", including {sp.integer(self.n_infinite)} infinite"
|
|
34
|
+
return text
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _pick_column(data: pd.DataFrame, column):
|
|
38
|
+
if column is None:
|
|
39
|
+
if data.shape[1] == 1:
|
|
40
|
+
return data.columns[0]
|
|
41
|
+
cols = ", ".join(map(str, data.columns[:10]))
|
|
42
|
+
more = "" if data.shape[1] <= 10 else f" and {data.shape[1] - 10} more"
|
|
43
|
+
raise ValueError(f"Pass the column to describe. This DataFrame has {data.shape[1]} columns: {cols}{more}.")
|
|
44
|
+
if column not in data.columns:
|
|
45
|
+
raise SpeechKeyError(f"No column named {column!r}.")
|
|
46
|
+
return column
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def numeric(data, column=None, name: str | None = None) -> NumericInput:
|
|
50
|
+
frame = None
|
|
51
|
+
if isinstance(data, pd.DataFrame):
|
|
52
|
+
column = _pick_column(data, column)
|
|
53
|
+
s = data[column]
|
|
54
|
+
frame = data
|
|
55
|
+
elif isinstance(data, pd.Series):
|
|
56
|
+
s = data
|
|
57
|
+
else:
|
|
58
|
+
arr = np.asarray(data)
|
|
59
|
+
if arr.ndim > 1:
|
|
60
|
+
arr = arr.ravel()
|
|
61
|
+
s = pd.Series(arr)
|
|
62
|
+
label = name or (str(s.name) if s.name is not None else "values")
|
|
63
|
+
|
|
64
|
+
if pd.api.types.is_bool_dtype(s):
|
|
65
|
+
s = s.astype(float)
|
|
66
|
+
if not pd.api.types.is_numeric_dtype(s):
|
|
67
|
+
converted = pd.to_numeric(s, errors="coerce")
|
|
68
|
+
if converted.notna().sum() < s.notna().sum():
|
|
69
|
+
raise TypeError(
|
|
70
|
+
f"{label} is not numeric. It holds text or categories; "
|
|
71
|
+
"describe it with bar or pie instead."
|
|
72
|
+
)
|
|
73
|
+
s = converted
|
|
74
|
+
s = s.astype(float)
|
|
75
|
+
n_total = len(s)
|
|
76
|
+
infinite = np.isinf(s.to_numpy())
|
|
77
|
+
n_inf = int(infinite.sum())
|
|
78
|
+
clean = s[~infinite].dropna()
|
|
79
|
+
return NumericInput(
|
|
80
|
+
values=clean.to_numpy(),
|
|
81
|
+
series=clean,
|
|
82
|
+
name=label,
|
|
83
|
+
n_total=n_total,
|
|
84
|
+
n_missing=n_total - len(clean),
|
|
85
|
+
n_infinite=n_inf,
|
|
86
|
+
frame=frame,
|
|
87
|
+
)
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def frame_and_group(data, column, by):
|
|
91
|
+
"""Return (frame, value column, group column) for grouped charts."""
|
|
92
|
+
if not isinstance(data, pd.DataFrame):
|
|
93
|
+
raise TypeError("Grouping with by= needs a DataFrame and a column name.")
|
|
94
|
+
column = _pick_column(data, column)
|
|
95
|
+
if by not in data.columns:
|
|
96
|
+
raise SpeechKeyError(f"No column named {by!r} to group by.")
|
|
97
|
+
return data, column, by
|
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
"""Shared statistics for one numeric variable. Numbers only, no words."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import math
|
|
6
|
+
|
|
7
|
+
import numpy as np
|
|
8
|
+
from scipy import signal, stats
|
|
9
|
+
|
|
10
|
+
from ..config import config
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def _f(x) -> float:
|
|
14
|
+
return float(x) if x is not None else float("nan")
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def summary(x: np.ndarray) -> dict:
|
|
18
|
+
"""Centre, spread, shape and Tukey fences of a finite 1-D array."""
|
|
19
|
+
t = config.thresholds
|
|
20
|
+
n = len(x)
|
|
21
|
+
out: dict = {"n": n}
|
|
22
|
+
if n == 0:
|
|
23
|
+
nan = float("nan")
|
|
24
|
+
out.update(dict.fromkeys(
|
|
25
|
+
["mean", "median", "std", "min", "max", "q1", "q3", "iqr", "p5", "p95",
|
|
26
|
+
"skewness", "kurtosis", "lower_fence", "upper_fence", "whisker_low", "whisker_high"], nan))
|
|
27
|
+
out.update(n_outliers=0, n_low_outliers=0, n_high_outliers=0, n_extreme=0, constant=False)
|
|
28
|
+
return out
|
|
29
|
+
q1, med, q3 = np.percentile(x, [25, 50, 75])
|
|
30
|
+
p5, p95 = np.percentile(x, [5, 95])
|
|
31
|
+
std = float(np.std(x, ddof=1)) if n > 1 else float("nan")
|
|
32
|
+
constant = bool(np.all(x == x[0]))
|
|
33
|
+
iqr = q3 - q1
|
|
34
|
+
k = t["outlier_iqr"]
|
|
35
|
+
ke = t["extreme_iqr"]
|
|
36
|
+
lo, hi = q1 - k * iqr, q3 + k * iqr
|
|
37
|
+
low = x < lo
|
|
38
|
+
high = x > hi
|
|
39
|
+
extreme = (x < q1 - ke * iqr) | (x > q3 + ke * iqr)
|
|
40
|
+
inside = x[(x >= lo) & (x <= hi)]
|
|
41
|
+
skew = float(stats.skew(x, bias=False)) if n > 2 and not constant else float("nan")
|
|
42
|
+
kurt = float(stats.kurtosis(x, fisher=True, bias=False)) if n > 3 and not constant else float("nan")
|
|
43
|
+
out.update(
|
|
44
|
+
mean=float(np.mean(x)),
|
|
45
|
+
median=float(med),
|
|
46
|
+
std=std,
|
|
47
|
+
min=float(np.min(x)),
|
|
48
|
+
max=float(np.max(x)),
|
|
49
|
+
q1=float(q1),
|
|
50
|
+
q3=float(q3),
|
|
51
|
+
iqr=float(iqr),
|
|
52
|
+
p5=float(p5),
|
|
53
|
+
p95=float(p95),
|
|
54
|
+
skewness=skew,
|
|
55
|
+
kurtosis=kurt,
|
|
56
|
+
lower_fence=float(lo),
|
|
57
|
+
upper_fence=float(hi),
|
|
58
|
+
whisker_low=float(inside.min()) if len(inside) else float("nan"),
|
|
59
|
+
whisker_high=float(inside.max()) if len(inside) else float("nan"),
|
|
60
|
+
n_outliers=int(low.sum() + high.sum()),
|
|
61
|
+
n_low_outliers=int(low.sum()),
|
|
62
|
+
n_high_outliers=int(high.sum()),
|
|
63
|
+
n_extreme=int(extreme.sum()),
|
|
64
|
+
constant=constant,
|
|
65
|
+
)
|
|
66
|
+
return out
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def outlier_mask(x: np.ndarray, s: dict) -> np.ndarray:
|
|
70
|
+
return (x < s["lower_fence"]) | (x > s["upper_fence"])
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def density_peaks(x: np.ndarray) -> dict:
|
|
74
|
+
"""Peaks of a Gaussian KDE (Scott's rule), highest first.
|
|
75
|
+
|
|
76
|
+
The grid runs three bandwidths past the data on each side, so a peak at the
|
|
77
|
+
edge of the data, as in an exponential shape, is still found.
|
|
78
|
+
"""
|
|
79
|
+
n = len(x)
|
|
80
|
+
if n < 5 or np.all(x == x[0]):
|
|
81
|
+
return {"peaks": [], "peak_heights": [], "flat": False, "flatness": float("nan"),
|
|
82
|
+
"bandwidth": float("nan"), "grid": None, "density": None}
|
|
83
|
+
kde = stats.gaussian_kde(x)
|
|
84
|
+
bw = float(kde.factor * np.std(x, ddof=1))
|
|
85
|
+
lo, hi = x.min() - 3 * bw, x.max() + 3 * bw
|
|
86
|
+
grid = np.linspace(lo, hi, 1024)
|
|
87
|
+
dens = kde(grid)
|
|
88
|
+
q1, q3 = np.percentile(x, [25, 75])
|
|
89
|
+
middle = dens[(grid >= q1) & (grid <= q3)]
|
|
90
|
+
flatness = float(middle.min() / dens.max()) if len(middle) else 0.0
|
|
91
|
+
prom = config.thresholds["peak_prominence"] * dens.max()
|
|
92
|
+
idx, _ = signal.find_peaks(dens, prominence=prom)
|
|
93
|
+
if len(idx) == 0:
|
|
94
|
+
idx = np.array([int(np.argmax(dens))])
|
|
95
|
+
# Flat: light tails (as a uniform shape has) and no real drop across the middle half.
|
|
96
|
+
kurt = float(stats.kurtosis(x, fisher=True, bias=False))
|
|
97
|
+
# Small ripples on a flat top can pass the prominence test, so they do not block this;
|
|
98
|
+
# two real modes leave a deep valley inside the middle half and fail the flatness test.
|
|
99
|
+
if kurt < config.thresholds["kurtosis"]["light"] and flatness >= config.thresholds["flat_ratio"]:
|
|
100
|
+
return {"peaks": [], "peak_heights": [], "flat": True, "flatness": flatness,
|
|
101
|
+
"bandwidth": bw, "grid": grid, "density": dens}
|
|
102
|
+
order = idx[np.argsort(-dens[idx])]
|
|
103
|
+
return {
|
|
104
|
+
"peaks": [float(grid[i]) for i in order],
|
|
105
|
+
"peak_heights": [float(dens[i] / dens.max()) for i in order],
|
|
106
|
+
"flat": False,
|
|
107
|
+
"flatness": flatness,
|
|
108
|
+
"bandwidth": bw,
|
|
109
|
+
"grid": grid,
|
|
110
|
+
"density": dens,
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def normality(x: np.ndarray) -> dict:
|
|
115
|
+
"""Shapiro-Wilk up to ``shapiro_max_n`` values, D'Agostino-Pearson above."""
|
|
116
|
+
n = len(x)
|
|
117
|
+
if n < 3 or np.all(x == x[0]):
|
|
118
|
+
return {"normality_test": None, "normality_p": float("nan")}
|
|
119
|
+
if n <= config.thresholds["shapiro_max_n"]:
|
|
120
|
+
p = float(stats.shapiro(x).pvalue)
|
|
121
|
+
name = "Shapiro-Wilk"
|
|
122
|
+
else:
|
|
123
|
+
p = float(stats.normaltest(x).pvalue)
|
|
124
|
+
name = "D'Agostino-Pearson"
|
|
125
|
+
return {"normality_test": name, "normality_p": p}
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def qq_tails(x: np.ndarray) -> dict:
|
|
129
|
+
"""Probability plot against the normal, with the mean gap in each tail in SD units."""
|
|
130
|
+
n = len(x)
|
|
131
|
+
if n < 3 or np.all(x == x[0]):
|
|
132
|
+
nan = float("nan")
|
|
133
|
+
return {"qq_r": nan, "qq_slope": nan, "qq_intercept": nan, "low_tail_gap": nan, "high_tail_gap": nan}
|
|
134
|
+
(osm, osr), (slope, intercept, r) = stats.probplot(x, dist="norm")
|
|
135
|
+
resid = osr - (slope * osm + intercept)
|
|
136
|
+
sd = float(np.std(x, ddof=1))
|
|
137
|
+
k = max(1, math.ceil(config.thresholds["qq_tail_share"] * n))
|
|
138
|
+
return {
|
|
139
|
+
"qq_r": float(r),
|
|
140
|
+
"qq_slope": float(slope),
|
|
141
|
+
"qq_intercept": float(intercept),
|
|
142
|
+
"low_tail_gap": float(np.mean(resid[:k]) / sd),
|
|
143
|
+
"high_tail_gap": float(np.mean(resid[-k:]) / sd),
|
|
144
|
+
"_osm": osm,
|
|
145
|
+
"_osr": osr,
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def transform_skew(x: np.ndarray, skew: float) -> tuple[str, float] | None:
|
|
150
|
+
"""The skewness after the usual fixing transform, when it helps."""
|
|
151
|
+
if math.isnan(skew) or len(x) < 3:
|
|
152
|
+
return None
|
|
153
|
+
try:
|
|
154
|
+
if skew > 0 and x.min() > 0:
|
|
155
|
+
name, y = "a log transform", np.log(x)
|
|
156
|
+
elif skew > 0 and x.min() >= 0:
|
|
157
|
+
name, y = "a log1p transform, log of 1 plus the value,", np.log1p(x)
|
|
158
|
+
else:
|
|
159
|
+
name, y = "a Yeo-Johnson power transform", stats.yeojohnson(x)[0]
|
|
160
|
+
new = float(stats.skew(y, bias=False))
|
|
161
|
+
except Exception:
|
|
162
|
+
return None
|
|
163
|
+
if math.isnan(new) or abs(new) >= abs(skew):
|
|
164
|
+
return None
|
|
165
|
+
return name, new
|
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
"""Sentences, glossary entries and advice shared by the distribution charts."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import math
|
|
6
|
+
|
|
7
|
+
from .. import rules
|
|
8
|
+
from .. import speech as sp
|
|
9
|
+
from ..config import config
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def shape_sentence(s: dict, peaks: list[float] | None = None) -> str:
|
|
13
|
+
if s["constant"]:
|
|
14
|
+
return sp.sentence(f"every value is {sp.num(s['min'])}")
|
|
15
|
+
shape = rules.skew_words(s["skewness"])
|
|
16
|
+
if peaks is not None and len(peaks) >= 2:
|
|
17
|
+
shape = f"{rules.modality(len(peaks))}, {shape}"
|
|
18
|
+
return sp.sentence(f"{shape}, skewness {sp.num(s['skewness'])}")
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def outlier_sentence(s: dict, values=None) -> str:
|
|
22
|
+
"""For example: ``61 high outliers above 340,000; largest 755,000.``"""
|
|
23
|
+
lo_n, hi_n = s["n_low_outliers"], s["n_high_outliers"]
|
|
24
|
+
if lo_n == 0 and hi_n == 0:
|
|
25
|
+
return "No outliers by the 1.5 IQR rule."
|
|
26
|
+
parts = []
|
|
27
|
+
if hi_n and not lo_n:
|
|
28
|
+
text = f"{sp.plural(hi_n, 'high outlier')} above {sp.num(s['upper_fence'])}"
|
|
29
|
+
if values is not None:
|
|
30
|
+
text += f"; largest {sp.num(values.max())}"
|
|
31
|
+
return sp.sentence(text)
|
|
32
|
+
if lo_n and not hi_n:
|
|
33
|
+
text = f"{sp.plural(lo_n, 'low outlier')} below {sp.num(s['lower_fence'])}"
|
|
34
|
+
if values is not None:
|
|
35
|
+
text += f"; smallest {sp.num(values.min())}"
|
|
36
|
+
return sp.sentence(text)
|
|
37
|
+
parts.append(f"{sp.plural(lo_n, 'low outlier')} below {sp.num(s['lower_fence'])}")
|
|
38
|
+
parts.append(f"{sp.integer(hi_n)} high above {sp.num(s['upper_fence'])}")
|
|
39
|
+
return sp.sentence("; ".join(parts))
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def peaks_sentence(peaks: list[float], flat: bool = False) -> str:
|
|
43
|
+
if flat:
|
|
44
|
+
return "Flat, no single peak: values are spread evenly across the middle."
|
|
45
|
+
if not peaks:
|
|
46
|
+
return "No clear peak."
|
|
47
|
+
if len(peaks) == 1:
|
|
48
|
+
return f"One peak near {sp.num(peaks[0])}."
|
|
49
|
+
if len(peaks) == 2:
|
|
50
|
+
return f"Bimodal: main peak near {sp.num(peaks[0])}, smaller peak near {sp.num(peaks[1])}."
|
|
51
|
+
named = sp.capped([sp.num(p) for p in peaks], where=".peaks")
|
|
52
|
+
return f"Multimodal, {len(peaks)} peaks, highest first: near {named}."
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def tails_sentence(s: dict) -> str:
|
|
56
|
+
if math.isnan(s["kurtosis"]):
|
|
57
|
+
return ""
|
|
58
|
+
return sp.sentence(f"{rules.kurtosis_words(s['kurtosis'])}, excess kurtosis {sp.num(s['kurtosis'])}")
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def normality_sentence(nt: dict, n: int) -> str:
|
|
62
|
+
if nt["normality_test"] is None:
|
|
63
|
+
return ""
|
|
64
|
+
text = f"{nt['normality_test']} {sp.pvalue(nt['normality_p'])}: {rules.normal_verdict(nt['normality_p'])}."
|
|
65
|
+
if n > config.thresholds["shapiro_max_n"] and nt["normality_p"] < config.thresholds["normality_alpha"]:
|
|
66
|
+
text += " With this many values, tests flag even small departures; judge by skewness and kurtosis too."
|
|
67
|
+
return text
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def small_sample_sentence(n: int) -> str:
|
|
71
|
+
if 0 < n < config.thresholds["small_sample"]:
|
|
72
|
+
return f"Small sample, {sp.plural(n, 'value')}, so the shape is uncertain."
|
|
73
|
+
return ""
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
# ----- glossary --------------------------------------------------------------
|
|
77
|
+
|
|
78
|
+
def glossary(s: dict, extra: dict | None = None) -> dict[str, str]:
|
|
79
|
+
t = config.thresholds
|
|
80
|
+
sk, ku = t["skewness"], t["kurtosis"]
|
|
81
|
+
g = {
|
|
82
|
+
"skewness": (
|
|
83
|
+
"Skewness measures how lopsided the values are. 0 means symmetric. Positive means a longer "
|
|
84
|
+
"tail to the right, toward high values; negative means a longer tail to the left. "
|
|
85
|
+
f"Bands used: size below {sp.num(sk['moderate'])} is roughly symmetric, "
|
|
86
|
+
f"{sp.num(sk['moderate'])} to {sp.num(sk['high'])} moderately skewed, "
|
|
87
|
+
f"{sp.num(sk['high'])} or more highly skewed. This is the bias-corrected sample skewness, "
|
|
88
|
+
"the same as pandas skew. "
|
|
89
|
+
f"This result: {sp.num(s['skewness'])}, {rules.skew_words(s['skewness'])}."
|
|
90
|
+
),
|
|
91
|
+
"kurtosis": (
|
|
92
|
+
"Excess kurtosis compares how heavy the tails are with a normal distribution, which scores 0. "
|
|
93
|
+
"Positive means more extreme values than a normal distribution; negative means fewer. "
|
|
94
|
+
f"Bands used: below minus {sp.num(abs(ku['light']))} light tails, up to {sp.num(ku['heavy'])} "
|
|
95
|
+
f"close to normal, above {sp.num(ku['heavy'])} heavy, above {sp.num(ku['very_heavy'])} very heavy. "
|
|
96
|
+
f"This result: {sp.num(s['kurtosis'])}, {rules.kurtosis_words(s['kurtosis'])}."
|
|
97
|
+
),
|
|
98
|
+
"median": (
|
|
99
|
+
"The median is the middle value: half the values are below it and half above. "
|
|
100
|
+
"Unlike the mean, it is not pulled by outliers or a long tail. "
|
|
101
|
+
f"This result: {sp.num(s['median'])}, against a mean of {sp.num(s['mean'])}."
|
|
102
|
+
),
|
|
103
|
+
"mean": (
|
|
104
|
+
"The mean is the average: the sum divided by the count. A long tail pulls it toward the tail. "
|
|
105
|
+
f"This result: {sp.num(s['mean'])}."
|
|
106
|
+
),
|
|
107
|
+
"standard deviation": (
|
|
108
|
+
"The standard deviation is the typical distance of values from the mean, in the same unit as "
|
|
109
|
+
f"the data. This result: {sp.num(s['std'])}."
|
|
110
|
+
),
|
|
111
|
+
"quartiles": (
|
|
112
|
+
"Quartiles cut the sorted values into four equal parts. The first quartile has 25% of values "
|
|
113
|
+
"below it, the third quartile 75%. The middle half of the values lies between them. "
|
|
114
|
+
f"This result: first quartile {sp.num(s['q1'])}, third quartile {sp.num(s['q3'])}."
|
|
115
|
+
),
|
|
116
|
+
"iqr": (
|
|
117
|
+
"The interquartile range, IQR, is the third quartile minus the first: the width of the middle "
|
|
118
|
+
f"half of the values. This result: {sp.num(s['iqr'])}."
|
|
119
|
+
),
|
|
120
|
+
"outliers": (
|
|
121
|
+
f"Outliers here use Tukey's rule: values more than {sp.num(t['outlier_iqr'])} IQR below the first "
|
|
122
|
+
f"quartile or above the third. Beyond {sp.num(t['extreme_iqr'])} IQR they are called extreme. "
|
|
123
|
+
f"This result: fences at {sp.num(s['lower_fence'])} and {sp.num(s['upper_fence'])}, "
|
|
124
|
+
f"{sp.plural(s['n_outliers'], 'outlier')}, {sp.integer(s['n_extreme'])} extreme. "
|
|
125
|
+
"The outliers attribute holds the rows."
|
|
126
|
+
),
|
|
127
|
+
"peaks": (
|
|
128
|
+
"Peaks are the high points of a smoothed density curve, a kernel density estimate with Scott's "
|
|
129
|
+
f"bandwidth. A peak counts when it rises at least {sp.pct(t['peak_prominence'])} of the highest "
|
|
130
|
+
"peak above its surroundings. One peak is unimodal, two bimodal, more multimodal."
|
|
131
|
+
),
|
|
132
|
+
"normality test": (
|
|
133
|
+
f"Shapiro-Wilk is used up to {sp.integer(t['shapiro_max_n'])} values, D'Agostino-Pearson above. "
|
|
134
|
+
f"A p-value below {sp.num(t['normality_alpha'])} means the data departs from a normal distribution. "
|
|
135
|
+
"With large samples, tiny departures give small p-values, so read it with skewness and kurtosis."
|
|
136
|
+
),
|
|
137
|
+
}
|
|
138
|
+
if extra:
|
|
139
|
+
g.update(extra)
|
|
140
|
+
return g
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
# ----- advice ----------------------------------------------------------------
|
|
144
|
+
|
|
145
|
+
def numeric_advice(x, s: dict, n_missing: int, n_total: int, peaks=None) -> list[str]:
|
|
146
|
+
from ._stats import transform_skew
|
|
147
|
+
|
|
148
|
+
out: list[str] = []
|
|
149
|
+
if s["n"] == 0:
|
|
150
|
+
return ["No values to work with."]
|
|
151
|
+
if s["constant"]:
|
|
152
|
+
return ["Every value is the same, so this column carries no information for a model; it can be dropped."]
|
|
153
|
+
band = rules.skew_band(s["skewness"])
|
|
154
|
+
if band in ("moderate", "high"):
|
|
155
|
+
fix = transform_skew(x, s["skewness"])
|
|
156
|
+
if fix:
|
|
157
|
+
name, new = fix
|
|
158
|
+
out.append(f"Skewness {sp.num(s['skewness'])}: {name} brings it to {sp.num(new)}.")
|
|
159
|
+
else:
|
|
160
|
+
out.append(f"Skewness {sp.num(s['skewness'])}: a power transform may reduce it.")
|
|
161
|
+
if s["n_outliers"]:
|
|
162
|
+
caps = []
|
|
163
|
+
if s["n_low_outliers"]:
|
|
164
|
+
caps.append(sp.num(s["lower_fence"]))
|
|
165
|
+
if s["n_high_outliers"]:
|
|
166
|
+
caps.append(sp.num(s["upper_fence"]))
|
|
167
|
+
out.append(
|
|
168
|
+
f"{sp.plural(s['n_outliers'], 'outlier')}: check them before removing; they may be real. "
|
|
169
|
+
"Tree-based models are less sensitive to them. For linear models, consider capping at "
|
|
170
|
+
f"{sp.join(caps)}."
|
|
171
|
+
)
|
|
172
|
+
if n_missing:
|
|
173
|
+
share = n_missing / n_total
|
|
174
|
+
mband = rules.missing_band(share)
|
|
175
|
+
if band != "symmetric":
|
|
176
|
+
stat, why = "the median", ", since the data is skewed"
|
|
177
|
+
else:
|
|
178
|
+
stat, why = "the mean or median", ""
|
|
179
|
+
if mband == "low":
|
|
180
|
+
out.append(f"{sp.pct(share)} missing: filling the gaps with {stat} is usually enough{why}.")
|
|
181
|
+
elif mband == "moderate":
|
|
182
|
+
out.append(f"{sp.pct(share)} missing: fill the gaps with {stat}{why}, and add a column marking which rows were missing.")
|
|
183
|
+
else:
|
|
184
|
+
out.append(f"{sp.pct(share)} missing: consider dropping the column, or model the missingness itself.")
|
|
185
|
+
if peaks is not None and len(peaks) >= 2:
|
|
186
|
+
out.append(
|
|
187
|
+
"More than one peak can mean mixed groups. Look for a column that separates them, "
|
|
188
|
+
"then describe each group with by=."
|
|
189
|
+
)
|
|
190
|
+
if 0 < s["n"] < config.thresholds["small_sample"]:
|
|
191
|
+
out.append("With so few values, collect more data before trusting the shape.")
|
|
192
|
+
return out or ["Nothing stands out that needs fixing."]
|