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,413 @@
|
|
|
1
|
+
"""Relationship charts: scatter plot, regression line and correlation matrix."""
|
|
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
|
+
from ..errors import SpeechKeyError
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
# ----- input -------------------------------------------------------------------------
|
|
19
|
+
|
|
20
|
+
def _pair(data, x, y, x_name=None, y_name=None):
|
|
21
|
+
"""Two numeric columns, rows with a missing value in either dropped."""
|
|
22
|
+
if isinstance(data, pd.DataFrame):
|
|
23
|
+
for col in (x, y):
|
|
24
|
+
if col not in data.columns:
|
|
25
|
+
raise SpeechKeyError(f"No column named {col!r}.")
|
|
26
|
+
xs, ys = data[x], data[y]
|
|
27
|
+
x_name, y_name = x_name or str(x), y_name or str(y)
|
|
28
|
+
frame = data
|
|
29
|
+
else:
|
|
30
|
+
# spl.scatter(x_values, y_values)
|
|
31
|
+
xs, ys = pd.Series(np.asarray(data).ravel()), pd.Series(np.asarray(x).ravel())
|
|
32
|
+
if len(xs) != len(ys):
|
|
33
|
+
raise ValueError(f"x has {len(xs)} values and y has {len(ys)}; they must match.")
|
|
34
|
+
x_name = x_name or (str(data.name) if isinstance(data, pd.Series) and data.name is not None else "x")
|
|
35
|
+
y_name = y_name or (str(x.name) if isinstance(x, pd.Series) and x.name is not None else "y")
|
|
36
|
+
frame = None
|
|
37
|
+
for name, s in ((x_name, xs), (y_name, ys)):
|
|
38
|
+
if not pd.api.types.is_numeric_dtype(s) or pd.api.types.is_bool_dtype(s):
|
|
39
|
+
if pd.to_numeric(s, errors="coerce").notna().sum() < s.notna().sum():
|
|
40
|
+
raise TypeError(f"{name} is not numeric. For a category against a number, use box or violin with by=.")
|
|
41
|
+
xs = pd.to_numeric(xs, errors="coerce").astype(float).replace([np.inf, -np.inf], np.nan)
|
|
42
|
+
ys = pd.to_numeric(ys, errors="coerce").astype(float).replace([np.inf, -np.inf], np.nan)
|
|
43
|
+
keep = xs.notna() & ys.notna()
|
|
44
|
+
return {
|
|
45
|
+
"x": xs[keep].to_numpy(), "y": ys[keep].to_numpy(), "index": xs.index[keep],
|
|
46
|
+
"x_name": x_name, "y_name": y_name, "n_total": len(xs), "n_dropped": int((~keep).sum()),
|
|
47
|
+
"frame": frame,
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _dropped_phrase(p) -> str:
|
|
52
|
+
if p["n_dropped"] == 0:
|
|
53
|
+
return ""
|
|
54
|
+
return f", {sp.integer(p['n_dropped'])} dropped for missing values"
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
# ----- shared numbers ----------------------------------------------------------------
|
|
58
|
+
|
|
59
|
+
def _fit(x, y) -> dict:
|
|
60
|
+
"""Least-squares line, quadratic check and residual diagnostics for y on x."""
|
|
61
|
+
n = len(x)
|
|
62
|
+
lr = stats.linregress(x, y)
|
|
63
|
+
pred = lr.intercept + lr.slope * x
|
|
64
|
+
resid = y - pred
|
|
65
|
+
ss_tot = float(np.sum((y - y.mean()) ** 2))
|
|
66
|
+
r2 = float(lr.rvalue ** 2)
|
|
67
|
+
out = {"slope": float(lr.slope), "intercept": float(lr.intercept), "r2": r2,
|
|
68
|
+
"slope_p": float(lr.pvalue), "slope_stderr": float(lr.stderr)}
|
|
69
|
+
# Curve check: does a squared term add real R-squared?
|
|
70
|
+
if n >= 5 and np.ptp(x) > 0:
|
|
71
|
+
coef = np.polyfit(x, y, 2)
|
|
72
|
+
qpred = np.polyval(coef, x)
|
|
73
|
+
r2q = 1 - float(np.sum((y - qpred) ** 2)) / ss_tot if ss_tot > 0 else float("nan")
|
|
74
|
+
out.update(r2_quadratic=r2q, quadratic_coef=float(coef[0]))
|
|
75
|
+
else:
|
|
76
|
+
out.update(r2_quadratic=float("nan"), quadratic_coef=float("nan"))
|
|
77
|
+
# Residual spread against x (Breusch-Pagan, Koenker form: n times R-squared of e^2 on x).
|
|
78
|
+
if n >= 5 and np.ptp(x) > 0:
|
|
79
|
+
e2 = resid ** 2
|
|
80
|
+
r_e2 = np.corrcoef(x, e2)[0, 1] if np.std(e2) > 0 else 0.0
|
|
81
|
+
lm = n * r_e2 ** 2
|
|
82
|
+
out["bp_p"] = float(stats.chi2.sf(lm, 1))
|
|
83
|
+
out["spread_trend"] = float(stats.spearmanr(x, np.abs(resid))[0]) if np.std(resid) > 0 else 0.0
|
|
84
|
+
else:
|
|
85
|
+
out["bp_p"] = float("nan")
|
|
86
|
+
out["spread_trend"] = float("nan")
|
|
87
|
+
sd = float(np.std(resid, ddof=2)) if n > 2 else float("nan")
|
|
88
|
+
z = resid / sd if sd and sd > 0 else np.zeros(n)
|
|
89
|
+
out["residual_sd"] = sd
|
|
90
|
+
out["_resid"] = resid
|
|
91
|
+
out["_z"] = z
|
|
92
|
+
# Cook's distance for one predictor.
|
|
93
|
+
if n > 2 and np.ptp(x) > 0 and sd > 0:
|
|
94
|
+
sxx = np.sum((x - x.mean()) ** 2)
|
|
95
|
+
h = 1 / n + (x - x.mean()) ** 2 / sxx
|
|
96
|
+
mse = np.sum(resid ** 2) / (n - 2)
|
|
97
|
+
out["_cooks"] = (resid ** 2 / (2 * mse)) * h / (1 - h) ** 2
|
|
98
|
+
else:
|
|
99
|
+
out["_cooks"] = np.zeros(n)
|
|
100
|
+
return out
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def _apart_points(p, f, limit=None):
|
|
104
|
+
"""Points far from the line, largest gap first."""
|
|
105
|
+
zlim = config.thresholds["residual_z"]
|
|
106
|
+
idx = np.where(np.abs(f["_z"]) > zlim)[0]
|
|
107
|
+
idx = idx[np.argsort(-np.abs(f["_z"][idx]))]
|
|
108
|
+
return idx
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def _point(p, i) -> str:
|
|
112
|
+
return f"{p['x_name']} {sp.num(p['x'][i])} with {p['y_name']} {sp.num(p['y'][i])}"
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def _relationship_sentence(r, r_p, rho) -> str:
|
|
116
|
+
band = rules.correlation_band(r)
|
|
117
|
+
if band == "undefined":
|
|
118
|
+
return "Relationship undefined: one of the columns is constant."
|
|
119
|
+
if band == "very weak":
|
|
120
|
+
text = f"No clear linear relationship, Pearson r {sp.num(r)}, Spearman {sp.num(rho)}"
|
|
121
|
+
else:
|
|
122
|
+
text = f"{band} {rules.direction(r)} relationship, Pearson r {sp.num(r)}, Spearman {sp.num(rho)}"
|
|
123
|
+
if not math.isnan(r_p) and r_p >= config.thresholds["normality_alpha"]:
|
|
124
|
+
text += f"; not statistically significant, {sp.pvalue(r_p)}"
|
|
125
|
+
return sp.sentence(text)
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def _gap_sentence(r, rho) -> str:
|
|
129
|
+
gap = config.thresholds["correlation_gap"]
|
|
130
|
+
if math.isnan(r) or math.isnan(rho):
|
|
131
|
+
return ""
|
|
132
|
+
if abs(rho) - abs(r) > gap:
|
|
133
|
+
return ("Rank correlation is clearly stronger than Pearson: the relationship is steady in direction "
|
|
134
|
+
"but curved, or a few points pull the straight-line fit down.")
|
|
135
|
+
if abs(r) - abs(rho) > gap:
|
|
136
|
+
return "Pearson is clearly stronger than rank correlation: a few extreme points may be driving it."
|
|
137
|
+
return ""
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def _spread_sentence(p, f) -> str:
|
|
141
|
+
t = f.get("spread_trend", float("nan"))
|
|
142
|
+
if math.isnan(t) or math.isnan(f["bp_p"]) or f["bp_p"] >= config.thresholds["normality_alpha"]:
|
|
143
|
+
return ""
|
|
144
|
+
if t >= 0.2:
|
|
145
|
+
return f"Spread around the trend widens as {p['x_name']} grows."
|
|
146
|
+
if t <= -0.2:
|
|
147
|
+
return f"Spread around the trend narrows as {p['x_name']} grows."
|
|
148
|
+
return "Spread around the trend is uneven."
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def _curve_sentence(f) -> str:
|
|
152
|
+
gain = f["r2_quadratic"] - f["r2"]
|
|
153
|
+
if math.isnan(gain) or gain < config.thresholds["curve_r2_gain"]:
|
|
154
|
+
return ""
|
|
155
|
+
convex = f["quadratic_coef"] > 0
|
|
156
|
+
if f["slope"] < 0:
|
|
157
|
+
shape = "falling fast at first, then levelling off" if convex else "falling slowly at first, then faster"
|
|
158
|
+
else:
|
|
159
|
+
shape = "rising slowly at first, then faster" if convex else "rising fast at first, then levelling off"
|
|
160
|
+
return (f"A curve fits better than a straight line, {shape}: R-squared rises from {sp.num(f['r2'])} to "
|
|
161
|
+
f"{sp.num(f['r2_quadratic'])} with a squared term.")
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def _maybe_plot(res, plot, kind, **kw):
|
|
165
|
+
if plot:
|
|
166
|
+
from ..plotting import draw
|
|
167
|
+
|
|
168
|
+
res.figure = draw(kind, res.title, **kw)
|
|
169
|
+
return res
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
_REL_GLOSSARY = {
|
|
173
|
+
"pearson": ("Pearson's r measures how close the points are to a straight line, from minus 1 to 1. "
|
|
174
|
+
"0 means no straight-line relationship. It is sensitive to extreme points."),
|
|
175
|
+
"spearman": ("Spearman's rank correlation compares the order of the values instead of the values. It "
|
|
176
|
+
"measures whether one column tends to rise as the other rises, in a straight line or not, "
|
|
177
|
+
"and is less affected by extreme points."),
|
|
178
|
+
"correlation bands": ("Bands for the size of a correlation, Evans 1996: 0.8 or more very strong, 0.6 strong, "
|
|
179
|
+
"0.4 moderate, 0.2 weak, below 0.2 very weak. Change them in spl.config.thresholds."),
|
|
180
|
+
"p-value": ("The p-value is the chance of seeing a correlation at least this large if there were truly none. "
|
|
181
|
+
"Below 0.05 is called statistically significant. With many rows, tiny correlations can be significant."),
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
# ----- scatter -----------------------------------------------------------------------
|
|
186
|
+
|
|
187
|
+
def scatter(data, x=None, y=None, *, x_name=None, y_name=None, level=None, plot=False):
|
|
188
|
+
"""Describe a scatter plot of y against x.
|
|
189
|
+
|
|
190
|
+
``spl.scatter(df, "x_col", "y_col")`` or ``spl.scatter(x_values, y_values)``.
|
|
191
|
+
"""
|
|
192
|
+
p = _pair(data, x, y, x_name, y_name)
|
|
193
|
+
xv, yv = p["x"], p["y"]
|
|
194
|
+
n = len(xv)
|
|
195
|
+
head = f"Scatter of {p['y_name']} against {p['x_name']}, {sp.plural(n, 'point')}{_dropped_phrase(p)}."
|
|
196
|
+
if n < 3:
|
|
197
|
+
return build("scatter", f"{p['y_name']} vs {p['x_name']}", {"n": n}, [("brief", head), ("brief", "Too few points to describe.")], level=level)
|
|
198
|
+
constant = np.ptp(xv) == 0 or np.ptp(yv) == 0
|
|
199
|
+
if constant:
|
|
200
|
+
r = r_p = rho = rho_p = float("nan")
|
|
201
|
+
else:
|
|
202
|
+
pr = stats.pearsonr(xv, yv)
|
|
203
|
+
sr = stats.spearmanr(xv, yv)
|
|
204
|
+
r, r_p, rho, rho_p = float(pr[0]), float(pr[1]), float(sr[0]), float(sr[1]) # index form works on every SciPy version
|
|
205
|
+
f = _fit(xv, yv) if not constant else None
|
|
206
|
+
L = [("brief", head), ("brief", _relationship_sentence(r, r_p, rho))]
|
|
207
|
+
if f:
|
|
208
|
+
L.append(("brief", _gap_sentence(r, rho)))
|
|
209
|
+
L.append(("brief", _spread_sentence(p, f)))
|
|
210
|
+
apart = _apart_points(p, f)
|
|
211
|
+
if len(apart):
|
|
212
|
+
zlim = sp.num(config.thresholds["residual_z"])
|
|
213
|
+
if len(apart) <= config.max_items:
|
|
214
|
+
named = sp.join([_point(p, i) for i in apart])
|
|
215
|
+
L.append(("brief", f"{sp.plural(len(apart), 'point stands', 'points stand')} apart, more than {zlim} standard deviations from the trend: {named}."))
|
|
216
|
+
else:
|
|
217
|
+
far = sp.join([_point(p, i) for i in apart[: config.max_items]])
|
|
218
|
+
L.append(("brief", f"{sp.integer(len(apart))} points, {sp.pct(len(apart) / n)}, lie more than {zlim} standard deviations "
|
|
219
|
+
f"from the trend; farthest: {far}. See .apart for all."))
|
|
220
|
+
L.append(("brief", _curve_sentence(f)))
|
|
221
|
+
L.append(("standard", f"{p['x_name']} runs {sp.range_text(xv.min(), xv.max())}; {p['y_name']} runs {sp.range_text(yv.min(), yv.max())}."))
|
|
222
|
+
L.append(("full", f"Pearson {sp.pvalue(r_p)}; Spearman {sp.pvalue(rho_p)}."))
|
|
223
|
+
L.append(("full", f"Straight-line fit: slope {sp.num(f['slope'])}, R-squared {sp.num(f['r2'])}."))
|
|
224
|
+
L = [(lv, t) for lv, t in L if t]
|
|
225
|
+
facts = {"n": n, "n_dropped": p["n_dropped"], "pearson": r, "pearson_p": r_p, "spearman": rho,
|
|
226
|
+
"spearman_p": rho_p, "band": rules.correlation_band(r), "direction": rules.direction(r)}
|
|
227
|
+
extras = {}
|
|
228
|
+
if f:
|
|
229
|
+
facts.update({k: v for k, v in f.items() if not k.startswith("_")})
|
|
230
|
+
apart = _apart_points(p, f)
|
|
231
|
+
rows = p["index"][apart]
|
|
232
|
+
extras["apart"] = p["frame"].loc[rows] if p["frame"] is not None else pd.DataFrame(
|
|
233
|
+
{p["x_name"]: xv[apart], p["y_name"]: yv[apart]})
|
|
234
|
+
advice = []
|
|
235
|
+
if f and len(_apart_points(p, f)):
|
|
236
|
+
advice.append("Check the points that stand apart: errors, or a different kind of case. Refit without them to see how much they move the line.")
|
|
237
|
+
if f and _gap_sentence(r, rho):
|
|
238
|
+
advice.append("When Pearson and Spearman disagree, prefer Spearman for describing the link, and try a log transform of a skewed column.")
|
|
239
|
+
if f and _curve_sentence(f):
|
|
240
|
+
advice.append("The link is curved: a squared term, a log transform or a tree-based model will capture it better than a straight line.")
|
|
241
|
+
res = build("scatter", f"{p['y_name']} vs {p['x_name']}", facts, L,
|
|
242
|
+
title=f"Scatter of {p['y_name']} against {p['x_name']}", level=level,
|
|
243
|
+
glossary=_REL_GLOSSARY, advice=advice or ["Nothing in this relationship needs fixing."], extras=extras)
|
|
244
|
+
return _maybe_plot(res, plot, "scatter", x=xv, y=yv, x_name=p["x_name"], y_name=p["y_name"])
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
# ----- regression --------------------------------------------------------------------
|
|
248
|
+
|
|
249
|
+
def regression(data, x=None, y=None, *, x_name=None, y_name=None, level=None, plot=False):
|
|
250
|
+
"""Describe a straight-line regression of y on x: slope, fit, and what the residuals show."""
|
|
251
|
+
p = _pair(data, x, y, x_name, y_name)
|
|
252
|
+
xv, yv = p["x"], p["y"]
|
|
253
|
+
n = len(xv)
|
|
254
|
+
name = f"{p['y_name']} on {p['x_name']}"
|
|
255
|
+
if n < 3 or np.ptp(xv) == 0:
|
|
256
|
+
return build("regression", name, {"n": n},
|
|
257
|
+
[("brief", f"Linear fit of {name}: needs at least 3 points and more than one value of {p['x_name']}.")], level=level)
|
|
258
|
+
f = _fit(xv, yv)
|
|
259
|
+
band = rules.r2_band(f["r2"])
|
|
260
|
+
sign = "plus" if f["slope"] >= 0 else "minus"
|
|
261
|
+
L = [
|
|
262
|
+
("brief", f"Linear fit of {name}, {sp.plural(n, 'point')}{_dropped_phrase(p)}."),
|
|
263
|
+
("brief", f"{p['y_name']} is about {sp.num(f['intercept'])} {sign} {sp.num(abs(f['slope']))} times {p['x_name']}."),
|
|
264
|
+
("brief", f"Slope {sp.num(f['slope'])}: each 1 unit more of {p['x_name']} goes with {sp.num(abs(f['slope']))} "
|
|
265
|
+
f"{'more' if f['slope'] >= 0 else 'less'} {p['y_name']}."),
|
|
266
|
+
("brief", f"R-squared {sp.num(f['r2'])}, {band} fit: the line explains {sp.pct(f['r2'])} of the variation in {p['y_name']}."),
|
|
267
|
+
]
|
|
268
|
+
if f["slope_p"] >= config.thresholds["normality_alpha"]:
|
|
269
|
+
L.append(("brief", f"The slope is not statistically significant, {sp.pvalue(f['slope_p'])}."))
|
|
270
|
+
if not math.isnan(f["bp_p"]) and f["bp_p"] < config.thresholds["normality_alpha"]:
|
|
271
|
+
direction = "grows" if f["spread_trend"] > 0 else "shrinks"
|
|
272
|
+
L.append(("brief", f"Residual spread {direction} with {p['x_name']}, Breusch-Pagan {sp.pvalue(f['bp_p'])}: heteroscedastic."))
|
|
273
|
+
else:
|
|
274
|
+
L.append(("brief", f"Residual spread is steady, Breusch-Pagan {sp.pvalue(f['bp_p'])}."))
|
|
275
|
+
L.append(("standard", _curve_sentence(f)))
|
|
276
|
+
apart = _apart_points(p, f)
|
|
277
|
+
if len(apart):
|
|
278
|
+
L.append(("standard", f"{sp.plural(len(apart), 'residual')} beyond {sp.num(config.thresholds['residual_z'])} standard deviations: "
|
|
279
|
+
f"{sp.capped([_point(p, i) for i in apart], where='.apart')}."))
|
|
280
|
+
cooks = f["_cooks"]
|
|
281
|
+
influential = np.where(cooks > 4 / n)[0]
|
|
282
|
+
if len(influential):
|
|
283
|
+
top = influential[np.argsort(-cooks[influential])]
|
|
284
|
+
L.append(("standard", f"{sp.plural(len(influential), 'influential point')} by Cook's distance above 4 over n; strongest: "
|
|
285
|
+
f"{sp.capped([_point(p, i) for i in top], where='.influential')}."))
|
|
286
|
+
L.append(("full", f"Slope standard error {sp.num(f['slope_stderr'])}, {sp.pvalue(f['slope_p'])}. Residual standard deviation {sp.num(f['residual_sd'])}."))
|
|
287
|
+
resid = f["_resid"]
|
|
288
|
+
if 3 <= n <= config.thresholds["shapiro_max_n"] and np.std(resid) > 0:
|
|
289
|
+
sp_p = float(stats.shapiro(resid).pvalue)
|
|
290
|
+
L.append(("full", f"Residuals, Shapiro-Wilk {sp.pvalue(sp_p)}: {rules.normal_verdict(sp_p)}."))
|
|
291
|
+
L = [(lv, t) for lv, t in L if t]
|
|
292
|
+
facts = {"n": n, "n_dropped": p["n_dropped"], **{k: v for k, v in f.items() if not k.startswith("_")},
|
|
293
|
+
"fit": band, "n_influential": int(len(influential))}
|
|
294
|
+
frame_rows = lambda idx: (p["frame"].loc[p["index"][idx]] if p["frame"] is not None
|
|
295
|
+
else pd.DataFrame({p["x_name"]: xv[idx], p["y_name"]: yv[idx]}))
|
|
296
|
+
advice = []
|
|
297
|
+
if facts["bp_p"] < config.thresholds["normality_alpha"]:
|
|
298
|
+
advice.append(f"Uneven residual spread: try a log transform of {p['y_name']}, or use robust standard errors before trusting p-values.")
|
|
299
|
+
if _curve_sentence(f):
|
|
300
|
+
advice.append(f"The relationship is curved: add a squared term of {p['x_name']}, or transform it.")
|
|
301
|
+
if len(influential):
|
|
302
|
+
advice.append("Refit without the most influential points and compare the slope; if it moves a lot, report both.")
|
|
303
|
+
if band == "weak":
|
|
304
|
+
advice.append(f"A weak fit: {p['x_name']} alone explains little of {p['y_name']}. Add other predictors.")
|
|
305
|
+
gloss = {
|
|
306
|
+
"slope": f"The slope is how much {p['y_name']} changes, on average, for each 1 unit more of {p['x_name']}.",
|
|
307
|
+
"r-squared": ("R-squared is the share of the variation in the outcome that the line explains, from 0 to 1. "
|
|
308
|
+
f"Bands used: below {sp.num(config.thresholds['r2']['moderate'])} weak, below "
|
|
309
|
+
f"{sp.num(config.thresholds['r2']['strong'])} moderate, above that strong. What counts as good depends on the field."),
|
|
310
|
+
"heteroscedastic": ("Heteroscedastic means the residual spread is not the same everywhere, for example wider "
|
|
311
|
+
"for large values. The Breusch-Pagan test checks this; p below 0.05 means uneven spread."),
|
|
312
|
+
"cook's distance": ("Cook's distance measures how much the fitted line would move if one point were removed. "
|
|
313
|
+
"Points above 4 divided by the number of points are called influential."),
|
|
314
|
+
**_REL_GLOSSARY,
|
|
315
|
+
}
|
|
316
|
+
res = build("regression", name, facts, L, title=f"Linear fit of {name}", level=level, glossary=gloss,
|
|
317
|
+
advice=advice or ["The straight-line fit shows no warning signs."],
|
|
318
|
+
extras={"apart": frame_rows(apart), "influential": frame_rows(influential),
|
|
319
|
+
"residuals": pd.Series(resid, index=p["index"], name="residual")})
|
|
320
|
+
return _maybe_plot(res, plot, "regression", x=xv, y=yv, slope=f["slope"], intercept=f["intercept"],
|
|
321
|
+
x_name=p["x_name"], y_name=p["y_name"])
|
|
322
|
+
|
|
323
|
+
|
|
324
|
+
# ----- correlation matrix ------------------------------------------------------------
|
|
325
|
+
|
|
326
|
+
def corr(df, *, method="pearson", target=None, columns=None, level=None, plot=False):
|
|
327
|
+
"""Describe a correlation matrix (heatmap) of the numeric columns of a DataFrame."""
|
|
328
|
+
if not isinstance(df, pd.DataFrame):
|
|
329
|
+
raise TypeError("corr needs a pandas DataFrame.")
|
|
330
|
+
if method not in ("pearson", "spearman", "kendall"):
|
|
331
|
+
raise ValueError("method must be pearson, spearman or kendall.")
|
|
332
|
+
data = df[columns] if columns is not None else df
|
|
333
|
+
num = data.select_dtypes(include="number").select_dtypes(exclude="bool")
|
|
334
|
+
if target is not None and target not in num.columns:
|
|
335
|
+
raise SpeechKeyError(f"{target!r} is not a numeric column of this DataFrame.")
|
|
336
|
+
constant = [c for c in num.columns if num[c].nunique(dropna=True) <= 1]
|
|
337
|
+
num = num.drop(columns=constant)
|
|
338
|
+
if num.shape[1] < 2:
|
|
339
|
+
return build("corr", "matrix", {"n_columns": num.shape[1]},
|
|
340
|
+
[("brief", "A correlation matrix needs at least two numeric columns that are not constant.")], level=level)
|
|
341
|
+
m = num.corr(method=method)
|
|
342
|
+
cols = list(m.columns)
|
|
343
|
+
rows = []
|
|
344
|
+
for i, a in enumerate(cols):
|
|
345
|
+
for b in cols[i + 1:]:
|
|
346
|
+
r = float(m.loc[a, b])
|
|
347
|
+
rows.append({"a": a, "b": b, "r": r, "abs": abs(r), "band": rules.correlation_band(r)})
|
|
348
|
+
pairs = pd.DataFrame(rows).sort_values("abs", ascending=False).reset_index(drop=True)
|
|
349
|
+
t = config.thresholds
|
|
350
|
+
label = method.capitalize()
|
|
351
|
+
|
|
352
|
+
def pair_text(row):
|
|
353
|
+
return f"{row['a']} and {row['b']} {sp.num(row['r'])}"
|
|
354
|
+
|
|
355
|
+
L = [("brief", f"Correlation matrix, {label}, {sp.plural(len(cols), 'numeric column')}, {sp.plural(len(pairs), 'pair')}.")]
|
|
356
|
+
strong = pairs[pairs["abs"] >= 0.6]
|
|
357
|
+
if target is None:
|
|
358
|
+
if len(strong):
|
|
359
|
+
very = int((pairs["abs"] >= 0.8).sum())
|
|
360
|
+
lead = f"{sp.plural(len(strong), 'pair')} strong or very strong, {sp.integer(very)} of them very strong"
|
|
361
|
+
L.append(("brief", f"{lead}: {sp.capped([pair_text(r) for _, r in strong.iterrows()], where='.pairs')}."))
|
|
362
|
+
else:
|
|
363
|
+
top = pairs.iloc[0]
|
|
364
|
+
L.append(("brief", f"No pair is strong; the largest is {pair_text(top)}, {top['band']}."))
|
|
365
|
+
neg = pairs[pairs["r"] < 0]
|
|
366
|
+
if len(neg) and neg.iloc[0]["abs"] >= 0.4:
|
|
367
|
+
L.append(("brief", f"Strongest negative: {pair_text(neg.iloc[0])}, {neg.iloc[0]['band']}."))
|
|
368
|
+
elif len(neg) == 0 or neg.iloc[0]["abs"] < 0.2:
|
|
369
|
+
L.append(("brief", "No notable negative pairs."))
|
|
370
|
+
else:
|
|
371
|
+
with_t = m[target].drop(target).sort_values(key=np.abs, ascending=False)
|
|
372
|
+
named = sp.capped([f"{k} {sp.num(v)}" for k, v in with_t.items()], where=".with_target")
|
|
373
|
+
L.append(("brief", f"Strongest with {target}: {named}."))
|
|
374
|
+
L.append(("brief", f"Weakest with {target}: {with_t.index[-1]} {sp.num(with_t.iloc[-1])}."))
|
|
375
|
+
others = pairs[(pairs["a"] != target) & (pairs["b"] != target)]
|
|
376
|
+
multi_t = others[others["abs"] >= t["multicollinearity"]]
|
|
377
|
+
if len(multi_t):
|
|
378
|
+
L.append(("brief", f"Multicollinear predictors, at least {sp.num(t['multicollinearity'])}: "
|
|
379
|
+
f"{sp.capped([pair_text(r) for _, r in multi_t.iterrows()], where='.multicollinear')}."))
|
|
380
|
+
counts = pairs["band"].value_counts()
|
|
381
|
+
order = ["very strong", "strong", "moderate", "weak", "very weak"]
|
|
382
|
+
L.append(("standard", "Pairs by band: " + sp.join([f"{sp.integer(counts.get(b, 0))} {b}" for b in order]) + "."))
|
|
383
|
+
multi = pairs[pairs["abs"] >= t["multicollinearity"]]
|
|
384
|
+
if target is None and len(multi):
|
|
385
|
+
L.append(("standard", f"Possible multicollinearity, {sp.num(t['multicollinearity'])} or more: "
|
|
386
|
+
f"{sp.capped([pair_text(r) for _, r in multi.iterrows()], where='.multicollinear')}."))
|
|
387
|
+
if constant:
|
|
388
|
+
L.append(("standard", f"Left out because constant: {sp.join(constant)}."))
|
|
389
|
+
shown = pairs.head(45)
|
|
390
|
+
L.append(("full", "All pairs, largest first: " + "; ".join(pair_text(r) for _, r in shown.iterrows())
|
|
391
|
+
+ ("." if len(pairs) <= 45 else f"; and {len(pairs) - 45} more, see .pairs.")))
|
|
392
|
+
facts = {"method": method, "n_columns": len(cols), "n_pairs": len(pairs), "constant_left_out": constant,
|
|
393
|
+
"strongest_pair": (pairs.iloc[0]["a"], pairs.iloc[0]["b"], float(pairs.iloc[0]["r"]))}
|
|
394
|
+
extras = {"matrix": m, "pairs": pairs.drop(columns="abs"), "multicollinear": multi.drop(columns="abs"),
|
|
395
|
+
"pair": lambda a, b: float(m.loc[a, b])}
|
|
396
|
+
if target is not None:
|
|
397
|
+
with_t = m[target].drop(target).sort_values(key=np.abs, ascending=False)
|
|
398
|
+
extras["with_target"] = with_t
|
|
399
|
+
facts["target"] = target
|
|
400
|
+
advice = []
|
|
401
|
+
if len(multi):
|
|
402
|
+
advice.append("Multicollinear pairs: keep one of each pair, combine them, or use ridge regression or PCA, "
|
|
403
|
+
"so coefficients stay stable. Tree models mind this less.")
|
|
404
|
+
if target is not None:
|
|
405
|
+
weak = [k for k, v in m[target].drop(target).items() if abs(v) < 0.2]
|
|
406
|
+
if weak:
|
|
407
|
+
advice.append(f"Very weak correlation with {target} for {sp.capped(weak)}. Correlation sees only straight-line "
|
|
408
|
+
"links, so check them with a tree model's feature importance before dropping them.")
|
|
409
|
+
if method == "pearson":
|
|
410
|
+
advice.append("For skewed columns or curved links, compare with method='spearman'.")
|
|
411
|
+
res = build("corr", target or "matrix", facts, L, title=f"Correlation matrix, {label}", level=level,
|
|
412
|
+
glossary=_REL_GLOSSARY, advice=advice, extras=extras)
|
|
413
|
+
return _maybe_plot(res, plot, "corr", matrix=m)
|