-
Notifications
You must be signed in to change notification settings - Fork 239
/
beta_distributions.py
347 lines (291 loc) · 11.9 KB
/
beta_distributions.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
"""Statistical Manifold of beta distributions with the Fisher metric."""
from scipy.integrate import odeint
from scipy.integrate import solve_bvp
from scipy.stats import beta
import geomstats.backend as gs
import geomstats.errors
from geomstats.geometry.embedded_manifold import EmbeddedManifold
from geomstats.geometry.euclidean import Euclidean
from geomstats.geometry.riemannian_metric import RiemannianMetric
from geomstats.geometry.symmetric_matrices import SymmetricMatrices
N_STEPS = 100
EPSILON = 1e-6
class BetaDistributions(EmbeddedManifold):
r"""Class for the manifold of beta distributions.
This is :math: Beta = `R_+^* \times R_+^*`.
Attributes
----------
dim : int
Dimension of the manifold of beta distributions.
embedding_manifold : Manifold
Embedding manifold.
"""
def __init__(self):
super(BetaDistributions, self).__init__(
dim=2, embedding_manifold=Euclidean(dim=2))
self.metric = BetaMetric()
def belongs(self, point):
"""Evaluate if a point belongs to the manifold of beta distributions.
The statistical manifold of beta distributions is the upper right
quadrant of the euclidean 2-plane.
Parameters
----------
point : array-like, shape=[..., 2]
Point to be checked.
Returns
-------
belongs : array-like, shape=[...,]
Boolean indicating whether point represents a beta distribution.
"""
point_dim = point.shape[-1]
belongs = point_dim == self.dim
belongs = gs.logical_and(
belongs, gs.all(gs.greater(point, 0.), axis=-1))
return belongs
@staticmethod
def random_uniform(n_samples=1, bound=5.):
"""Sample parameters of beta distributions.
The uniform distribution on [0, bound]^2 is used.
Parameters
----------
n_samples : int
Number of samples.
Optional, default: 1.
bound : float
Side of the square where the beta parameters are sampled.
Optional, default: 5.
Returns
-------
samples : array-like, shape=[..., 2]
Sample of points representing beta distributions.
"""
size = (2,) if n_samples == 1 else (n_samples, 2)
return bound * gs.random.rand(*size)
def sample(self, point, n_samples=1):
"""Sample from the beta distribution.
Sample from the beta distribution with parameters provided by point.
Parameters
----------
point : array-like, shape=[..., 2]
Point representing a beta distribution.
n_samples : int
Number of points to sample with each pair of parameters in point.
Optional, default: 1.
Returns
-------
samples : array-like, shape=[..., n_samples]
Sample from beta distributions.
"""
geomstats.errors.check_belongs(point, self)
point = gs.to_ndarray(point, to_ndim=2)
samples = []
for param_a, param_b in point:
samples.append(gs.array(
beta.rvs(param_a, param_b, size=n_samples)))
return samples[0] if len(point) == 1 else gs.stack(samples)
@staticmethod
def maximum_likelihood_fit(data, loc=0, scale=1):
"""Estimate parameters from samples.
This a wrapper around scipy's maximum likelihood estimator to
estimate the parameters of a beta distribution from samples.
Parameters
----------
data : array-like, shape=[..., n_samples]
Data to estimate parameters from. Arrays of
different length may be passed.
loc : float
Location parameter of the distribution to estimate parameters
from. It is kept fixed during optimization.
Optional, default: 0.
scale : float
Scale parameter of the distribution to estimate parameters
from. It is kept fixed during optimization.
Optional, default: 1.
Returns
-------
parameter : array-like, shape=[..., 2]
Estimate of parameter obtained by maximum likelihood.
"""
data = gs.cast(data, gs.float32)
data = gs.to_ndarray(
gs.where(data == 1., 1. - EPSILON, data), to_ndim=2)
parameters = []
for sample in data:
param_a, param_b, _, _ = beta.fit(sample, floc=loc, fscale=scale)
parameters.append(gs.array([param_a, param_b]))
return parameters[0] if len(data) == 1 else gs.stack(parameters)
class BetaMetric(RiemannianMetric):
"""Class for the Fisher information metric on beta distributions."""
def __init__(self):
super(BetaMetric, self).__init__(dim=2)
@staticmethod
def metric_det(param_a, param_b):
"""Compute the determinant of the metric.
Parameters
----------
param_a : array-like, shape=[...,]
First parameter of the beta distribution.
param_b : array-like, shape=[...,]
Second parameter of the beta distribution.
Returns
-------
metric_det : array-like, shape=[...,]
Determinant of the metric.
"""
metric_det = gs.polygamma(1, param_a) * gs.polygamma(1, param_b) - \
gs.polygamma(1, param_a + param_b) * (gs.polygamma(1, param_a) +
gs.polygamma(1, param_b))
return metric_det
def inner_product_matrix(self, base_point):
"""Compute inner-product matrix at the tangent space at base point.
Parameters
----------
base_point : array-like, shape=[..., 2]
Base point.
Returns
-------
mat : array-like, shape=[..., 2, 2]
Inner-product matrix.
"""
param_a = base_point[..., 0]
param_b = base_point[..., 1]
polygamma_ab = gs.polygamma(1, param_a + param_b)
polygamma_a = gs.polygamma(1, param_a)
polygamma_b = gs.polygamma(1, param_b)
vector = gs.stack(
[polygamma_a - polygamma_ab,
- polygamma_ab,
polygamma_b - polygamma_ab], axis=-1)
return SymmetricMatrices.from_vector(vector)
def christoffels(self, base_point):
"""Compute the Christoffel symbols.
Compute the Christoffel symbols of the Fisher information metric on
Beta.
Parameters
----------
base_point : array-like, shape=[..., 2]
Base point.
Returns
-------
christoffels : array-like, shape=[..., 2, 2, 2]
Christoffel symbols.
"""
def coefficients(param_a, param_b):
metric_det = 2 * self.metric_det(param_a, param_b)
poly_2_ab = gs.polygamma(2, param_a + param_b)
poly_1_ab = gs.polygamma(1, param_a + param_b)
poly_1_b = gs.polygamma(1, param_b)
c1 = (gs.polygamma(2, param_a) *
(poly_1_b - poly_1_ab) - poly_1_b * poly_2_ab) / metric_det
c2 = - poly_1_b * poly_2_ab / metric_det
c3 = (gs.polygamma(2, param_b) * poly_1_ab - poly_1_b *
poly_2_ab) / metric_det
return c1, c2, c3
point_a, point_b = base_point[..., 0], base_point[..., 1]
c4, c5, c6 = coefficients(point_b, point_a)
vector_0 = gs.stack(coefficients(point_a, point_b), axis=-1)
vector_1 = gs.stack([c6, c5, c4], axis=-1)
gamma_0 = SymmetricMatrices.from_vector(vector_0)
gamma_1 = SymmetricMatrices.from_vector(vector_1)
return gs.stack([gamma_0, gamma_1], axis=-3)
def exp(self, tangent_vec, base_point, n_steps=N_STEPS):
"""Exponential map associated to the Fisher information metric.
Exponential map at base_point of tangent_vec computed by integration
of the geodesic equation (initial value problem), using the
christoffel symbols.
Parameters
----------
tangent_vec : array-like, shape=[..., dim]
Tangent vector.
base_point : array-like, shape=[..., dim]
Base point.
n_steps : int
Number of steps for integration.
Optional, default: N_STEPS.
Returns
-------
exp : array-like, shape=[..., dim]
Riemannian exponential.
"""
base_point = gs.to_ndarray(base_point, to_ndim=2)
tangent_vec = gs.to_ndarray(tangent_vec, to_ndim=2)
def ivp(state, _):
"""Reformat the initial value problem geodesic ODE."""
position, velocity = state[:2], state[2:]
eq = self.geodesic_equation(velocity=velocity, position=position)
return gs.hstack([velocity, eq])
times = gs.linspace(0, 1, n_steps + 1)
exp = []
for point, vec in zip(base_point, tangent_vec):
initial_state = gs.hstack([point, vec])
geodesic = odeint(
ivp, initial_state, times, (), rtol=1e-6)
exp.append(geodesic[-1, :2])
return exp[0] if len(base_point) == 1 else gs.stack(exp)
def log(self, point, base_point, n_steps=N_STEPS):
"""Compute logarithm map associated to the Fisher information metric.
Solve the boundary value problem associated to the geodesic ordinary
differential equation (ODE) using the Christoffel symbols.
Parameters
----------
point : array-like, shape=[..., dim]
Point.
base_point : array-like, shape=[..., dim]
Base point.
n_steps : int
Number of steps for integration.
Optional, default: N_STEPS.
Returns
-------
tangent_vec : array-like, shape=[..., dim]
Initial velocity of the geodesic starting at base_point and
reaching point at time 1.
"""
stop_time = 1.
t = gs.linspace(0, stop_time, n_steps)
point = gs.to_ndarray(point, to_ndim=2)
base_point = gs.to_ndarray(base_point, to_ndim=2)
def initialize(end_point, start_point):
a0, b0 = start_point
a1, b1 = end_point
lin_init = gs.zeros([2 * self.dim, n_steps])
lin_init[0, :] = gs.linspace(a0, a1, n_steps)
lin_init[1, :] = gs.linspace(b0, b1, n_steps)
lin_init[2, :-1] = (lin_init[0, 1:] - lin_init[0, :-1]) * n_steps
lin_init[3, :-1] = (lin_init[1, 1:] - lin_init[1, :-1]) * n_steps
lin_init[2, -1] = lin_init[2, -2]
lin_init[3, -1] = lin_init[3, -2]
return lin_init
def bvp(_, state):
"""Reformat the boundary value problem geodesic ODE.
Parameters
----------
state : array-like, shape[4,]
Vector of the state variables: y = [a,b,u,v]
_ : unused
Any (time).
"""
position, velocity = state[:2].T, state[2:].T
eq = self.geodesic_equation(
velocity=velocity, position=position)
return gs.vstack((velocity.T, eq.T))
def boundary_cond(
state_a, state_b, point_0_a, point_0_b, point_1_a, point_1_b):
return gs.array(
[state_a[0] - point_0_a,
state_a[1] - point_0_b,
state_b[0] - point_1_a,
state_b[1] - point_1_b])
log = []
for bp, pt in zip(base_point, point):
geodesic_init = initialize(pt, bp)
base_point_a, base_point_b = bp
point_a, point_b = pt
def bc(y0, y1):
return boundary_cond(
y0, y1, base_point_a, base_point_b, point_a, point_b)
solution = solve_bvp(bvp, bc, t, geodesic_init)
geodesic = solution.sol(t)
geodesic = geodesic[:2, :]
log.append(n_steps * (geodesic[:, 1] - geodesic[:, 0]))
return log[0] if len(base_point) == 1 else gs.stack(log)