statsinference 0.1.4__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.
- statsinference/__init__.py +18 -0
- statsinference/_distributions.py +214 -0
- statsinference/_fit.py +485 -0
- statsinference/_plots.py +190 -0
- statsinference/inference.py +413 -0
- statsinference-0.1.4.dist-info/METADATA +129 -0
- statsinference-0.1.4.dist-info/RECORD +9 -0
- statsinference-0.1.4.dist-info/WHEEL +4 -0
- statsinference-0.1.4.dist-info/licenses/LICENSE +32 -0
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
"""
|
|
2
|
+
statsinference - fit univariate distributions by maximum likelihood, pick the
|
|
3
|
+
best one by AIC/BIC, plot fitdistrplus-style diagnostics, and simulate.
|
|
4
|
+
|
|
5
|
+
>>> import numpy as np
|
|
6
|
+
>>> from statsinference import StatsInference
|
|
7
|
+
>>> x = np.random.default_rng(1).gamma(2, 1.5, size=300)
|
|
8
|
+
>>> si = StatsInference(x).select(criterion="aic")
|
|
9
|
+
>>> si.best_dist, si.estimate
|
|
10
|
+
>>> si.summary(); si.plot(); si.plot_compare(top=3)
|
|
11
|
+
>>> sims = si.simulate(1000, seed=123)
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from ._distributions import SUPPORTED
|
|
15
|
+
from .inference import StatsInference
|
|
16
|
+
|
|
17
|
+
__all__ = ["StatsInference", "SUPPORTED"]
|
|
18
|
+
__version__ = "0.1.4"
|
|
@@ -0,0 +1,214 @@
|
|
|
1
|
+
"""Supported distributions: names, parameters, bounds and starting values."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import numpy as np
|
|
6
|
+
from scipy import integrate, optimize, stats
|
|
7
|
+
|
|
8
|
+
_TINY = 1e-10
|
|
9
|
+
_INF = np.inf
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def _iqr(x):
|
|
13
|
+
q75, q25 = np.percentile(x, [75, 25])
|
|
14
|
+
return q75 - q25
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _start_weibull(x):
|
|
18
|
+
lx = np.log(x)
|
|
19
|
+
shape = 1.2 / np.sqrt(np.var(lx, ddof=1))
|
|
20
|
+
return {"shape": shape, "scale": float(np.exp(np.mean(lx) + 0.572 / shape))}
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _start_beta(x):
|
|
24
|
+
m, v = np.mean(x), np.var(x, ddof=1)
|
|
25
|
+
common = m * (1 - m) / v - 1
|
|
26
|
+
return {"shape1": m * common, "shape2": (1 - m) * common}
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _start_f(x):
|
|
30
|
+
m = np.mean(x)
|
|
31
|
+
df2 = 2 * m / (m - 1) if m > 1.05 else 20.0
|
|
32
|
+
return {"df1": 5.0, "df2": float(df2)}
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _start_nbinom(x):
|
|
36
|
+
m, v = np.mean(x), np.var(x, ddof=1)
|
|
37
|
+
return {"size": m**2 / (v - m) if v > m else 100.0, "mu": m}
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
_DISTS: dict[str, dict] = {
|
|
41
|
+
"normal": dict(
|
|
42
|
+
params=("mean", "sd"),
|
|
43
|
+
lower=(-_INF, _TINY),
|
|
44
|
+
make=lambda mean, sd: stats.norm(mean, sd),
|
|
45
|
+
start=lambda x: {"mean": np.mean(x), "sd": np.std(x)},
|
|
46
|
+
),
|
|
47
|
+
"lognormal": dict(
|
|
48
|
+
params=("meanlog", "sdlog"),
|
|
49
|
+
lower=(-_INF, _TINY),
|
|
50
|
+
make=lambda meanlog, sdlog: stats.lognorm(sdlog, scale=np.exp(meanlog)),
|
|
51
|
+
start=lambda x: {
|
|
52
|
+
"meanlog": np.mean(np.log(x)),
|
|
53
|
+
"sdlog": np.std(np.log(x)),
|
|
54
|
+
},
|
|
55
|
+
),
|
|
56
|
+
"gamma": dict(
|
|
57
|
+
params=("shape", "rate"),
|
|
58
|
+
lower=(_TINY, _TINY),
|
|
59
|
+
make=lambda shape, rate: stats.gamma(shape, scale=1 / rate),
|
|
60
|
+
start=lambda x: {
|
|
61
|
+
"shape": np.mean(x) ** 2 / np.var(x, ddof=1),
|
|
62
|
+
"rate": np.mean(x) / np.var(x, ddof=1),
|
|
63
|
+
},
|
|
64
|
+
),
|
|
65
|
+
"weibull": dict(
|
|
66
|
+
params=("shape", "scale"),
|
|
67
|
+
lower=(_TINY, _TINY),
|
|
68
|
+
make=lambda shape, scale: stats.weibull_min(shape, scale=scale),
|
|
69
|
+
start=_start_weibull,
|
|
70
|
+
),
|
|
71
|
+
"exponential": dict(
|
|
72
|
+
params=("rate",),
|
|
73
|
+
lower=(_TINY,),
|
|
74
|
+
make=lambda rate: stats.expon(scale=1 / rate),
|
|
75
|
+
start=lambda x: {"rate": 1 / np.mean(x)},
|
|
76
|
+
),
|
|
77
|
+
"beta": dict(
|
|
78
|
+
params=("shape1", "shape2"),
|
|
79
|
+
lower=(_TINY, _TINY),
|
|
80
|
+
make=lambda shape1, shape2: stats.beta(shape1, shape2),
|
|
81
|
+
start=_start_beta,
|
|
82
|
+
),
|
|
83
|
+
"cauchy": dict(
|
|
84
|
+
params=("location", "scale"),
|
|
85
|
+
lower=(-_INF, _TINY),
|
|
86
|
+
make=lambda location, scale: stats.cauchy(location, scale),
|
|
87
|
+
start=lambda x: {"location": np.median(x), "scale": _iqr(x) / 2},
|
|
88
|
+
),
|
|
89
|
+
"logistic": dict(
|
|
90
|
+
params=("location", "scale"),
|
|
91
|
+
lower=(-_INF, _TINY),
|
|
92
|
+
make=lambda location, scale: stats.logistic(location, scale),
|
|
93
|
+
start=lambda x: {
|
|
94
|
+
"location": np.mean(x),
|
|
95
|
+
"scale": np.std(x) * np.sqrt(3) / np.pi,
|
|
96
|
+
},
|
|
97
|
+
),
|
|
98
|
+
"chi-squared": dict(
|
|
99
|
+
params=("df",),
|
|
100
|
+
lower=(_TINY,),
|
|
101
|
+
make=lambda df: stats.chi2(df),
|
|
102
|
+
start=lambda x: {"df": np.mean(x)},
|
|
103
|
+
),
|
|
104
|
+
"f": dict(
|
|
105
|
+
params=("df1", "df2"),
|
|
106
|
+
lower=(_TINY, _TINY),
|
|
107
|
+
make=lambda df1, df2: stats.f(df1, df2),
|
|
108
|
+
start=_start_f,
|
|
109
|
+
),
|
|
110
|
+
"t": dict( # location-scale t, as `mydt` in the R version
|
|
111
|
+
params=("m", "s", "df"),
|
|
112
|
+
lower=(-_INF, _TINY, _TINY),
|
|
113
|
+
make=lambda m, s, df: stats.t(df, loc=m, scale=s),
|
|
114
|
+
start=lambda x: {"m": np.median(x), "s": _iqr(x) / 2, "df": 10.0},
|
|
115
|
+
),
|
|
116
|
+
"poisson": dict(
|
|
117
|
+
params=("lambda",),
|
|
118
|
+
lower=(_TINY,),
|
|
119
|
+
make=lambda **p: stats.poisson(p["lambda"]),
|
|
120
|
+
start=lambda x: {"lambda": np.mean(x)},
|
|
121
|
+
discrete=True,
|
|
122
|
+
),
|
|
123
|
+
"geometric": dict( # R convention: number of failures, support 0, 1, ...
|
|
124
|
+
params=("prob",),
|
|
125
|
+
lower=(_TINY,),
|
|
126
|
+
upper=(1 - _TINY,),
|
|
127
|
+
make=lambda prob: stats.geom(prob, loc=-1),
|
|
128
|
+
start=lambda x: {"prob": 1 / (1 + np.mean(x))},
|
|
129
|
+
discrete=True,
|
|
130
|
+
),
|
|
131
|
+
"negative binomial": dict( # (size, mu) parametrisation, as MASS
|
|
132
|
+
params=("size", "mu"),
|
|
133
|
+
lower=(_TINY, _TINY),
|
|
134
|
+
make=lambda size, mu: stats.nbinom(size, size / (size + mu)),
|
|
135
|
+
start=_start_nbinom,
|
|
136
|
+
discrete=True,
|
|
137
|
+
),
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
_ALIASES = {
|
|
141
|
+
"norm": "normal",
|
|
142
|
+
"gaussian": "normal",
|
|
143
|
+
"log-normal": "lognormal",
|
|
144
|
+
"lnorm": "lognormal",
|
|
145
|
+
"exp": "exponential",
|
|
146
|
+
"chisq": "chi-squared",
|
|
147
|
+
"chi2": "chi-squared",
|
|
148
|
+
"chi-square": "chi-squared",
|
|
149
|
+
"student": "t",
|
|
150
|
+
"pois": "poisson",
|
|
151
|
+
"geom": "geometric",
|
|
152
|
+
"nbinom": "negative binomial",
|
|
153
|
+
"negative-binomial": "negative binomial",
|
|
154
|
+
"logis": "logistic",
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
SUPPORTED = tuple(sorted(_DISTS))
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
# Adapter so a plain density function behaves like a frozen scipy dist.
|
|
161
|
+
class _CallableDist:
|
|
162
|
+
"""Wraps a user density f(x, **params[, log=]) with numeric cdf/ppf."""
|
|
163
|
+
|
|
164
|
+
def __init__(self, f, params, has_log, cdf=None, discrete=False):
|
|
165
|
+
self.f, self.params, self.has_log, self._cdf = f, params, has_log, cdf
|
|
166
|
+
self.discrete = discrete
|
|
167
|
+
|
|
168
|
+
def logpdf(self, x):
|
|
169
|
+
x = np.asarray(x, float)
|
|
170
|
+
if self.has_log:
|
|
171
|
+
return np.asarray(self.f(x, **self.params, log=True), float)
|
|
172
|
+
with np.errstate(divide="ignore"):
|
|
173
|
+
return np.log(np.asarray(self.f(x, **self.params), float))
|
|
174
|
+
|
|
175
|
+
def pdf(self, x):
|
|
176
|
+
x = np.asarray(x, float)
|
|
177
|
+
if self.has_log:
|
|
178
|
+
return np.asarray(self.f(x, **self.params, log=False), float)
|
|
179
|
+
return np.asarray(self.f(x, **self.params), float)
|
|
180
|
+
|
|
181
|
+
def cdf(self, q):
|
|
182
|
+
q = np.atleast_1d(np.asarray(q, float))
|
|
183
|
+
if self._cdf is not None:
|
|
184
|
+
return np.asarray(self._cdf(q, **self.params), float)
|
|
185
|
+
|
|
186
|
+
def dens(t):
|
|
187
|
+
return float(self.pdf(np.array([t]))[0])
|
|
188
|
+
|
|
189
|
+
out = np.empty_like(q)
|
|
190
|
+
for i, qi in enumerate(q):
|
|
191
|
+
out[i] = integrate.quad(dens, -_INF, qi, limit=200)[0]
|
|
192
|
+
return np.clip(out, 0, 1)
|
|
193
|
+
|
|
194
|
+
def ppf(self, p):
|
|
195
|
+
p = np.atleast_1d(np.asarray(p, float))
|
|
196
|
+
out = np.empty_like(p)
|
|
197
|
+
for i, pi in enumerate(p):
|
|
198
|
+
lo, hi = -1.0, 1.0
|
|
199
|
+
while self.cdf(lo)[0] > pi:
|
|
200
|
+
lo *= 2
|
|
201
|
+
while self.cdf(hi)[0] < pi:
|
|
202
|
+
hi *= 2
|
|
203
|
+
out[i] = optimize.brentq(lambda t: self.cdf(t)[0] - pi, lo, hi)
|
|
204
|
+
return out
|
|
205
|
+
|
|
206
|
+
def rvs(self, size=None, random_state=None):
|
|
207
|
+
"""Inverse-CDF sampling (continuous densities only; can be slow)."""
|
|
208
|
+
if self.discrete:
|
|
209
|
+
raise NotImplementedError(
|
|
210
|
+
"simulation from a custom discrete density is not supported"
|
|
211
|
+
)
|
|
212
|
+
rng = np.random.default_rng(random_state)
|
|
213
|
+
u = rng.uniform(size=size)
|
|
214
|
+
return self.ppf(np.ravel(u)).reshape(np.shape(u))
|