DASPy-toolbox 1.0.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.
- DASPy_toolbox-1.0.0.dist-info/LICENSE.txt +1 -0
- DASPy_toolbox-1.0.0.dist-info/METADATA +85 -0
- DASPy_toolbox-1.0.0.dist-info/RECORD +49 -0
- DASPy_toolbox-1.0.0.dist-info/WHEEL +5 -0
- DASPy_toolbox-1.0.0.dist-info/entry_points.txt +2 -0
- DASPy_toolbox-1.0.0.dist-info/top_level.txt +1 -0
- daspy/__init__.py +4 -0
- daspy/advanced_tools/__init__.py +0 -0
- daspy/advanced_tools/channel.py +354 -0
- daspy/advanced_tools/decomposition.py +165 -0
- daspy/advanced_tools/denoising.py +276 -0
- daspy/advanced_tools/fdct.py +789 -0
- daspy/advanced_tools/strain2vel.py +245 -0
- daspy/basic_tools/__init__.py +0 -0
- daspy/basic_tools/filter.py +257 -0
- daspy/basic_tools/freqattributes.py +117 -0
- daspy/basic_tools/preprocessing.py +238 -0
- daspy/basic_tools/visualization.py +186 -0
- daspy/core/__init__.py +4 -0
- daspy/core/collection.py +279 -0
- daspy/core/dasdatetime.py +72 -0
- daspy/core/example.pkl +0 -0
- daspy/core/make_example.py +32 -0
- daspy/core/read.py +544 -0
- daspy/core/section.py +1319 -0
- daspy/core/write.py +282 -0
- daspy/seismic_detection/__init__.py +1 -0
- daspy/seismic_detection/calc_travel_time.py +23 -0
- daspy/seismic_detection/core.py +119 -0
- daspy/seismic_detection/detection.py +12 -0
- daspy/seismic_detection/gamma/__init__.py +13 -0
- daspy/seismic_detection/gamma/_base.py +549 -0
- daspy/seismic_detection/gamma/_bayesian_mixture.py +875 -0
- daspy/seismic_detection/gamma/_gaussian_mixture.py +866 -0
- daspy/seismic_detection/gamma/app.py +192 -0
- daspy/seismic_detection/gamma/seismic_ops.py +478 -0
- daspy/seismic_detection/gamma/utils.py +512 -0
- daspy/seismic_detection/location.py +266 -0
- daspy/seismic_detection/magnitude.py +43 -0
- daspy/seismic_detection/phase_picking.py +67 -0
- daspy/structure_imaging/__init__.py +0 -0
- daspy/structure_imaging/ambient_noise.py +4 -0
- daspy/structure_imaging/dispersion.py +27 -0
- daspy/structure_imaging/fault_zone.py +59 -0
- daspy/structure_imaging/inversion.py +6 -0
- daspy/traffic_monitoring/JamDetection.py +6 -0
- daspy/traffic_monitoring/SpeedMeasurement.py +6 -0
- daspy/traffic_monitoring/VehicleDetection.py +6 -0
- daspy/traffic_monitoring/__init__.py +0 -0
|
@@ -0,0 +1,875 @@
|
|
|
1
|
+
"""Bayesian Gaussian Mixture Model."""
|
|
2
|
+
# Author: Wei Xue <xuewei4d@gmail.com>
|
|
3
|
+
# Thierry Guillemot <thierry.guillemot.work@gmail.com>
|
|
4
|
+
# License: BSD 3 clause
|
|
5
|
+
|
|
6
|
+
import math
|
|
7
|
+
|
|
8
|
+
import numpy as np
|
|
9
|
+
from scipy.special import betaln, digamma, gammaln
|
|
10
|
+
from sklearn.utils import check_array
|
|
11
|
+
from sklearn.utils.validation import _deprecate_positional_args
|
|
12
|
+
|
|
13
|
+
from ._base import BaseMixture, _check_shape
|
|
14
|
+
from ._gaussian_mixture import (
|
|
15
|
+
_check_precision_matrix,
|
|
16
|
+
_check_precision_positivity,
|
|
17
|
+
_compute_log_det_cholesky,
|
|
18
|
+
_compute_precision_cholesky,
|
|
19
|
+
_estimate_gaussian_parameters,
|
|
20
|
+
_estimate_log_gaussian_prob,
|
|
21
|
+
)
|
|
22
|
+
from .seismic_ops import *
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _log_dirichlet_norm(dirichlet_concentration):
|
|
26
|
+
"""Compute the log of the Dirichlet distribution normalization term.
|
|
27
|
+
|
|
28
|
+
Parameters
|
|
29
|
+
----------
|
|
30
|
+
dirichlet_concentration : array-like, shape (n_samples,)
|
|
31
|
+
The parameters values of the Dirichlet distribution.
|
|
32
|
+
|
|
33
|
+
Returns
|
|
34
|
+
-------
|
|
35
|
+
log_dirichlet_norm : float
|
|
36
|
+
The log normalization of the Dirichlet distribution.
|
|
37
|
+
"""
|
|
38
|
+
return (gammaln(np.sum(dirichlet_concentration)) -
|
|
39
|
+
np.sum(gammaln(dirichlet_concentration)))
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _log_wishart_norm(degrees_of_freedom, log_det_precisions_chol, n_features):
|
|
43
|
+
"""Compute the log of the Wishart distribution normalization term.
|
|
44
|
+
|
|
45
|
+
Parameters
|
|
46
|
+
----------
|
|
47
|
+
degrees_of_freedom : array-like, shape (n_components,)
|
|
48
|
+
The number of degrees of freedom on the covariance Wishart
|
|
49
|
+
distributions.
|
|
50
|
+
|
|
51
|
+
log_det_precision_chol : array-like, shape (n_components,)
|
|
52
|
+
The determinant of the precision matrix for each component.
|
|
53
|
+
|
|
54
|
+
n_features : int
|
|
55
|
+
The number of features.
|
|
56
|
+
|
|
57
|
+
Return
|
|
58
|
+
------
|
|
59
|
+
log_wishart_norm : array-like, shape (n_components,)
|
|
60
|
+
The log normalization of the Wishart distribution.
|
|
61
|
+
"""
|
|
62
|
+
# To simplify the computation we have removed the np.log(np.pi) term
|
|
63
|
+
return -(degrees_of_freedom * log_det_precisions_chol +
|
|
64
|
+
degrees_of_freedom * n_features * .5 * math.log(2.) +
|
|
65
|
+
np.sum(gammaln(.5 * (degrees_of_freedom -
|
|
66
|
+
np.arange(n_features)[:, np.newaxis])), 0))
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
class BayesianGaussianMixture(BaseMixture):
|
|
70
|
+
"""Variational Bayesian estimation of a Gaussian mixture.
|
|
71
|
+
|
|
72
|
+
This class allows to infer an approximate posterior distribution over the
|
|
73
|
+
parameters of a Gaussian mixture distribution. The effective number of
|
|
74
|
+
components can be inferred from the data.
|
|
75
|
+
|
|
76
|
+
This class implements two types of prior for the weights distribution: a
|
|
77
|
+
finite mixture model with Dirichlet distribution and an infinite mixture
|
|
78
|
+
model with the Dirichlet Process. In practice Dirichlet Process inference
|
|
79
|
+
algorithm is approximated and uses a truncated distribution with a fixed
|
|
80
|
+
maximum number of components (called the Stick-breaking representation).
|
|
81
|
+
The number of components actually used almost always depends on the data.
|
|
82
|
+
|
|
83
|
+
.. versionadded:: 0.18
|
|
84
|
+
|
|
85
|
+
Read more in the :ref:`User Guide <bgmm>`.
|
|
86
|
+
|
|
87
|
+
Parameters
|
|
88
|
+
----------
|
|
89
|
+
n_components : int, defaults to 1.
|
|
90
|
+
The number of mixture components. Depending on the data and the value
|
|
91
|
+
of the `weight_concentration_prior` the model can decide to not use
|
|
92
|
+
all the components by setting some component `weights_` to values very
|
|
93
|
+
close to zero. The number of effective components is therefore smaller
|
|
94
|
+
than n_components.
|
|
95
|
+
|
|
96
|
+
covariance_type : {'full', 'tied', 'diag', 'spherical'}, defaults to 'full'
|
|
97
|
+
String describing the type of covariance parameters to use.
|
|
98
|
+
Must be one of::
|
|
99
|
+
|
|
100
|
+
'full' (each component has its own general covariance matrix),
|
|
101
|
+
'tied' (all components share the same general covariance matrix),
|
|
102
|
+
'diag' (each component has its own diagonal covariance matrix),
|
|
103
|
+
'spherical' (each component has its own single variance).
|
|
104
|
+
|
|
105
|
+
tol : float, defaults to 1e-3.
|
|
106
|
+
The convergence threshold. EM iterations will stop when the
|
|
107
|
+
lower bound average gain on the likelihood (of the training data with
|
|
108
|
+
respect to the model) is below this threshold.
|
|
109
|
+
|
|
110
|
+
reg_covar : float, defaults to 1e-6.
|
|
111
|
+
Non-negative regularization added to the diagonal of covariance.
|
|
112
|
+
Allows to assure that the covariance matrices are all positive.
|
|
113
|
+
|
|
114
|
+
max_iter : int, defaults to 100.
|
|
115
|
+
The number of EM iterations to perform.
|
|
116
|
+
|
|
117
|
+
n_init : int, defaults to 1.
|
|
118
|
+
The number of initializations to perform. The result with the highest
|
|
119
|
+
lower bound value on the likelihood is kept.
|
|
120
|
+
|
|
121
|
+
init_params : {'kmeans', 'random'}, defaults to 'kmeans'.
|
|
122
|
+
The method used to initialize the weights, the means and the
|
|
123
|
+
covariances.
|
|
124
|
+
Must be one of::
|
|
125
|
+
|
|
126
|
+
'kmeans' : responsibilities are initialized using kmeans.
|
|
127
|
+
'random' : responsibilities are initialized randomly.
|
|
128
|
+
|
|
129
|
+
weight_concentration_prior_type : str, defaults to 'dirichlet_process'.
|
|
130
|
+
String describing the type of the weight concentration prior.
|
|
131
|
+
Must be one of::
|
|
132
|
+
|
|
133
|
+
'dirichlet_process' (using the Stick-breaking representation),
|
|
134
|
+
'dirichlet_distribution' (can favor more uniform weights).
|
|
135
|
+
|
|
136
|
+
weight_concentration_prior : float | None, optional.
|
|
137
|
+
The dirichlet concentration of each component on the weight
|
|
138
|
+
distribution (Dirichlet). This is commonly called gamma in the
|
|
139
|
+
literature. The higher concentration puts more mass in
|
|
140
|
+
the center and will lead to more components being active, while a lower
|
|
141
|
+
concentration parameter will lead to more mass at the edge of the
|
|
142
|
+
mixture weights simplex. The value of the parameter must be greater
|
|
143
|
+
than 0. If it is None, it's set to ``1. / n_components``.
|
|
144
|
+
|
|
145
|
+
mean_precision_prior : float | None, optional.
|
|
146
|
+
The precision prior on the mean distribution (Gaussian).
|
|
147
|
+
Controls the extent of where means can be placed. Larger
|
|
148
|
+
values concentrate the cluster means around `mean_prior`.
|
|
149
|
+
The value of the parameter must be greater than 0.
|
|
150
|
+
If it is None, it is set to 1.
|
|
151
|
+
|
|
152
|
+
mean_prior : array-like, shape (n_features,), optional
|
|
153
|
+
The prior on the mean distribution (Gaussian).
|
|
154
|
+
If it is None, it is set to the mean of X.
|
|
155
|
+
|
|
156
|
+
degrees_of_freedom_prior : float | None, optional.
|
|
157
|
+
The prior of the number of degrees of freedom on the covariance
|
|
158
|
+
distributions (Wishart). If it is None, it's set to `n_features`.
|
|
159
|
+
|
|
160
|
+
covariance_prior : float or array-like, optional
|
|
161
|
+
The prior on the covariance distribution (Wishart).
|
|
162
|
+
If it is None, the emiprical covariance prior is initialized using the
|
|
163
|
+
covariance of X. The shape depends on `covariance_type`::
|
|
164
|
+
|
|
165
|
+
(n_features, n_features) if 'full',
|
|
166
|
+
(n_features, n_features) if 'tied',
|
|
167
|
+
(n_features) if 'diag',
|
|
168
|
+
float if 'spherical'
|
|
169
|
+
|
|
170
|
+
random_state : int, RandomState instance or None, optional (default=None)
|
|
171
|
+
Controls the random seed given to the method chosen to initialize the
|
|
172
|
+
parameters (see `init_params`).
|
|
173
|
+
In addition, it controls the generation of random samples from the
|
|
174
|
+
fitted distribution (see the method `sample`).
|
|
175
|
+
Pass an int for reproducible output across multiple function calls.
|
|
176
|
+
See :term:`Glossary <random_state>`.
|
|
177
|
+
|
|
178
|
+
warm_start : bool, default to False.
|
|
179
|
+
If 'warm_start' is True, the solution of the last fitting is used as
|
|
180
|
+
initialization for the next call of fit(). This can speed up
|
|
181
|
+
convergence when fit is called several times on similar problems.
|
|
182
|
+
See :term:`the Glossary <warm_start>`.
|
|
183
|
+
|
|
184
|
+
verbose : int, default to 0.
|
|
185
|
+
Enable verbose output. If 1 then it prints the current
|
|
186
|
+
initialization and each iteration step. If greater than 1 then
|
|
187
|
+
it prints also the log probability and the time needed
|
|
188
|
+
for each step.
|
|
189
|
+
|
|
190
|
+
verbose_interval : int, default to 10.
|
|
191
|
+
Number of iteration done before the next print.
|
|
192
|
+
|
|
193
|
+
Attributes
|
|
194
|
+
----------
|
|
195
|
+
weights_ : array-like, shape (n_components,)
|
|
196
|
+
The weights of each mixture components.
|
|
197
|
+
|
|
198
|
+
means_ : array-like, shape (n_components, n_features)
|
|
199
|
+
The mean of each mixture component.
|
|
200
|
+
|
|
201
|
+
covariances_ : array-like
|
|
202
|
+
The covariance of each mixture component.
|
|
203
|
+
The shape depends on `covariance_type`::
|
|
204
|
+
|
|
205
|
+
(n_components,) if 'spherical',
|
|
206
|
+
(n_features, n_features) if 'tied',
|
|
207
|
+
(n_components, n_features) if 'diag',
|
|
208
|
+
(n_components, n_features, n_features) if 'full'
|
|
209
|
+
|
|
210
|
+
precisions_ : array-like
|
|
211
|
+
The precision matrices for each component in the mixture. A precision
|
|
212
|
+
matrix is the inverse of a covariance matrix. A covariance matrix is
|
|
213
|
+
symmetric positive definite so the mixture of Gaussian can be
|
|
214
|
+
equivalently parameterized by the precision matrices. Storing the
|
|
215
|
+
precision matrices instead of the covariance matrices makes it more
|
|
216
|
+
efficient to compute the log-likelihood of new samples at test time.
|
|
217
|
+
The shape depends on ``covariance_type``::
|
|
218
|
+
|
|
219
|
+
(n_components,) if 'spherical',
|
|
220
|
+
(n_features, n_features) if 'tied',
|
|
221
|
+
(n_components, n_features) if 'diag',
|
|
222
|
+
(n_components, n_features, n_features) if 'full'
|
|
223
|
+
|
|
224
|
+
precisions_cholesky_ : array-like
|
|
225
|
+
The cholesky decomposition of the precision matrices of each mixture
|
|
226
|
+
component. A precision matrix is the inverse of a covariance matrix.
|
|
227
|
+
A covariance matrix is symmetric positive definite so the mixture of
|
|
228
|
+
Gaussian can be equivalently parameterized by the precision matrices.
|
|
229
|
+
Storing the precision matrices instead of the covariance matrices makes
|
|
230
|
+
it more efficient to compute the log-likelihood of new samples at test
|
|
231
|
+
time. The shape depends on ``covariance_type``::
|
|
232
|
+
|
|
233
|
+
(n_components,) if 'spherical',
|
|
234
|
+
(n_features, n_features) if 'tied',
|
|
235
|
+
(n_components, n_features) if 'diag',
|
|
236
|
+
(n_components, n_features, n_features) if 'full'
|
|
237
|
+
|
|
238
|
+
converged_ : bool
|
|
239
|
+
True when convergence was reached in fit(), False otherwise.
|
|
240
|
+
|
|
241
|
+
n_iter_ : int
|
|
242
|
+
Number of step used by the best fit of inference to reach the
|
|
243
|
+
convergence.
|
|
244
|
+
|
|
245
|
+
lower_bound_ : float
|
|
246
|
+
Lower bound value on the likelihood (of the training data with
|
|
247
|
+
respect to the model) of the best fit of inference.
|
|
248
|
+
|
|
249
|
+
weight_concentration_prior_ : tuple or float
|
|
250
|
+
The dirichlet concentration of each component on the weight
|
|
251
|
+
distribution (Dirichlet). The type depends on
|
|
252
|
+
``weight_concentration_prior_type``::
|
|
253
|
+
|
|
254
|
+
(float, float) if 'dirichlet_process' (Beta parameters),
|
|
255
|
+
float if 'dirichlet_distribution' (Dirichlet parameters).
|
|
256
|
+
|
|
257
|
+
The higher concentration puts more mass in
|
|
258
|
+
the center and will lead to more components being active, while a lower
|
|
259
|
+
concentration parameter will lead to more mass at the edge of the
|
|
260
|
+
simplex.
|
|
261
|
+
|
|
262
|
+
weight_concentration_ : array-like, shape (n_components,)
|
|
263
|
+
The dirichlet concentration of each component on the weight
|
|
264
|
+
distribution (Dirichlet).
|
|
265
|
+
|
|
266
|
+
mean_precision_prior_ : float
|
|
267
|
+
The precision prior on the mean distribution (Gaussian).
|
|
268
|
+
Controls the extent of where means can be placed.
|
|
269
|
+
Larger values concentrate the cluster means around `mean_prior`.
|
|
270
|
+
If mean_precision_prior is set to None, `mean_precision_prior_` is set
|
|
271
|
+
to 1.
|
|
272
|
+
|
|
273
|
+
mean_precision_ : array-like, shape (n_components,)
|
|
274
|
+
The precision of each components on the mean distribution (Gaussian).
|
|
275
|
+
|
|
276
|
+
mean_prior_ : array-like, shape (n_features,)
|
|
277
|
+
The prior on the mean distribution (Gaussian).
|
|
278
|
+
|
|
279
|
+
degrees_of_freedom_prior_ : float
|
|
280
|
+
The prior of the number of degrees of freedom on the covariance
|
|
281
|
+
distributions (Wishart).
|
|
282
|
+
|
|
283
|
+
degrees_of_freedom_ : array-like, shape (n_components,)
|
|
284
|
+
The number of degrees of freedom of each components in the model.
|
|
285
|
+
|
|
286
|
+
covariance_prior_ : float or array-like
|
|
287
|
+
The prior on the covariance distribution (Wishart).
|
|
288
|
+
The shape depends on `covariance_type`::
|
|
289
|
+
|
|
290
|
+
(n_features, n_features) if 'full',
|
|
291
|
+
(n_features, n_features) if 'tied',
|
|
292
|
+
(n_features) if 'diag',
|
|
293
|
+
float if 'spherical'
|
|
294
|
+
|
|
295
|
+
See Also
|
|
296
|
+
--------
|
|
297
|
+
GaussianMixture : Finite Gaussian mixture fit with EM.
|
|
298
|
+
|
|
299
|
+
References
|
|
300
|
+
----------
|
|
301
|
+
|
|
302
|
+
.. [1] `Bishop, Christopher M. (2006). "Pattern recognition and machine
|
|
303
|
+
learning". Vol. 4 No. 4. New York: Springer.
|
|
304
|
+
<https://www.springer.com/kr/book/9780387310732>`_
|
|
305
|
+
|
|
306
|
+
.. [2] `Hagai Attias. (2000). "A Variational Bayesian Framework for
|
|
307
|
+
Graphical Models". In Advances in Neural Information Processing
|
|
308
|
+
Systems 12.
|
|
309
|
+
<http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.36.2841&rep=rep1&type=pdf>`_
|
|
310
|
+
|
|
311
|
+
.. [3] `Blei, David M. and Michael I. Jordan. (2006). "Variational
|
|
312
|
+
inference for Dirichlet process mixtures". Bayesian analysis 1.1
|
|
313
|
+
<https://www.cs.princeton.edu/courses/archive/fall11/cos597C/reading/BleiJordan2005.pdf>`_
|
|
314
|
+
"""
|
|
315
|
+
@_deprecate_positional_args
|
|
316
|
+
def __init__(self, *, n_components=1, covariance_type='full', tol=1e-3,
|
|
317
|
+
reg_covar=1e-6, max_iter=100, n_init=1, init_params='kmeans',
|
|
318
|
+
weight_concentration_prior_type='dirichlet_process',
|
|
319
|
+
weight_concentration_prior=None,
|
|
320
|
+
mean_precision_prior=None, mean_prior=None,
|
|
321
|
+
degrees_of_freedom_prior=None, covariance_prior=None,
|
|
322
|
+
random_state=None, warm_start=False, verbose=0,
|
|
323
|
+
station_locs=None, phase_type=None, phase_weight=None, centers_init=None,
|
|
324
|
+
vel={"p":6.0, "s":6.0/1.75}, eikonal=None,
|
|
325
|
+
dummy_comp=False, dummy_prob=0.01, dummy_quantile=0.1,
|
|
326
|
+
loss_type="l1", bounds=None, max_covar=None,
|
|
327
|
+
verbose_interval=10):
|
|
328
|
+
super().__init__(
|
|
329
|
+
n_components=n_components, tol=tol, reg_covar=reg_covar,
|
|
330
|
+
max_iter=max_iter, n_init=n_init, init_params=init_params,
|
|
331
|
+
random_state=random_state, warm_start=warm_start,
|
|
332
|
+
dummy_comp=dummy_comp, dummy_prob=dummy_prob, dummy_quantile=dummy_quantile,
|
|
333
|
+
verbose=verbose, verbose_interval=verbose_interval)
|
|
334
|
+
|
|
335
|
+
self.covariance_type = covariance_type
|
|
336
|
+
self.weight_concentration_prior_type = weight_concentration_prior_type
|
|
337
|
+
self.weight_concentration_prior = weight_concentration_prior
|
|
338
|
+
self.mean_precision_prior = mean_precision_prior
|
|
339
|
+
self.mean_prior = mean_prior
|
|
340
|
+
self.degrees_of_freedom_prior = degrees_of_freedom_prior
|
|
341
|
+
self.covariance_prior = covariance_prior
|
|
342
|
+
self.centers_init = centers_init
|
|
343
|
+
if station_locs is None:
|
|
344
|
+
raise("Missing: station_locs")
|
|
345
|
+
if phase_type is None:
|
|
346
|
+
raise("Missing: phase_type")
|
|
347
|
+
if phase_weight is None:
|
|
348
|
+
phase_weight = np.ones([len(phase_type),1])
|
|
349
|
+
self.vel = vel
|
|
350
|
+
self.station_locs = station_locs
|
|
351
|
+
self.phase_type = np.squeeze(phase_type)
|
|
352
|
+
self.phase_weight = np.squeeze(phase_weight)
|
|
353
|
+
self.loss_type = loss_type
|
|
354
|
+
self.bounds = bounds
|
|
355
|
+
self.max_covar = max_covar
|
|
356
|
+
self.eikonal = eikonal
|
|
357
|
+
|
|
358
|
+
def _check_parameters(self, X):
|
|
359
|
+
"""Check that the parameters are well defined.
|
|
360
|
+
|
|
361
|
+
Parameters
|
|
362
|
+
----------
|
|
363
|
+
X : array-like, shape (n_samples, n_features)
|
|
364
|
+
"""
|
|
365
|
+
if self.covariance_type not in ['spherical', 'tied', 'diag', 'full']:
|
|
366
|
+
raise ValueError("Invalid value for 'covariance_type': %s "
|
|
367
|
+
"'covariance_type' should be in "
|
|
368
|
+
"['spherical', 'tied', 'diag', 'full']"
|
|
369
|
+
% self.covariance_type)
|
|
370
|
+
|
|
371
|
+
if (self.weight_concentration_prior_type not in
|
|
372
|
+
['dirichlet_process', 'dirichlet_distribution']):
|
|
373
|
+
raise ValueError(
|
|
374
|
+
"Invalid value for 'weight_concentration_prior_type': %s "
|
|
375
|
+
"'weight_concentration_prior_type' should be in "
|
|
376
|
+
"['dirichlet_process', 'dirichlet_distribution']"
|
|
377
|
+
% self.weight_concentration_prior_type)
|
|
378
|
+
|
|
379
|
+
self._check_weights_parameters()
|
|
380
|
+
self._check_means_parameters(X)
|
|
381
|
+
self._check_precision_parameters(X)
|
|
382
|
+
self._checkcovariance_prior_parameter(X)
|
|
383
|
+
|
|
384
|
+
n_samples, n_features = X.shape
|
|
385
|
+
if n_features > 2:
|
|
386
|
+
raise ValueError(f"n_features = {n_features} > 2! Only support 2 features (time, amplitude)")
|
|
387
|
+
assert(self.covariance_type=='full')
|
|
388
|
+
assert(self.station_locs.shape[0] == n_samples)
|
|
389
|
+
assert(self.loss_type in ["l1", "l2"])
|
|
390
|
+
_check_shape(self.phase_type, (n_samples, ), 'phase_type')
|
|
391
|
+
_check_shape(self.phase_weight, (n_samples, ), 'phase_type')
|
|
392
|
+
if self.init_params == "centers":
|
|
393
|
+
assert(self.centers_init is not None)
|
|
394
|
+
|
|
395
|
+
def _check_weights_parameters(self):
|
|
396
|
+
"""Check the parameter of the Dirichlet distribution."""
|
|
397
|
+
if self.weight_concentration_prior is None:
|
|
398
|
+
self.weight_concentration_prior_ = 1. / self.n_components
|
|
399
|
+
elif self.weight_concentration_prior > 0.:
|
|
400
|
+
self.weight_concentration_prior_ = (
|
|
401
|
+
self.weight_concentration_prior)
|
|
402
|
+
else:
|
|
403
|
+
raise ValueError("The parameter 'weight_concentration_prior' "
|
|
404
|
+
"should be greater than 0., but got %.3f."
|
|
405
|
+
% self.weight_concentration_prior)
|
|
406
|
+
|
|
407
|
+
def _check_means_parameters(self, X):
|
|
408
|
+
"""Check the parameters of the Gaussian distribution.
|
|
409
|
+
|
|
410
|
+
Parameters
|
|
411
|
+
----------
|
|
412
|
+
X : array-like, shape (n_samples, n_features)
|
|
413
|
+
"""
|
|
414
|
+
_, n_features = X.shape
|
|
415
|
+
|
|
416
|
+
if self.mean_precision_prior is None:
|
|
417
|
+
self.mean_precision_prior_ = 1.
|
|
418
|
+
elif self.mean_precision_prior > 0.:
|
|
419
|
+
self.mean_precision_prior_ = self.mean_precision_prior
|
|
420
|
+
else:
|
|
421
|
+
raise ValueError("The parameter 'mean_precision_prior' should be "
|
|
422
|
+
"greater than 0., but got %.3f."
|
|
423
|
+
% self.mean_precision_prior)
|
|
424
|
+
|
|
425
|
+
if self.mean_prior is None:
|
|
426
|
+
self.mean_prior_ = X.mean(axis=0)
|
|
427
|
+
else:
|
|
428
|
+
self.mean_prior_ = check_array(self.mean_prior,
|
|
429
|
+
dtype=[np.float64, np.float32],
|
|
430
|
+
ensure_2d=False)
|
|
431
|
+
_check_shape(self.mean_prior_, (n_features, ), 'means')
|
|
432
|
+
|
|
433
|
+
def _check_precision_parameters(self, X):
|
|
434
|
+
"""Check the prior parameters of the precision distribution.
|
|
435
|
+
|
|
436
|
+
Parameters
|
|
437
|
+
----------
|
|
438
|
+
X : array-like, shape (n_samples, n_features)
|
|
439
|
+
"""
|
|
440
|
+
_, n_features = X.shape
|
|
441
|
+
|
|
442
|
+
if self.degrees_of_freedom_prior is None:
|
|
443
|
+
self.degrees_of_freedom_prior_ = n_features
|
|
444
|
+
elif self.degrees_of_freedom_prior > n_features - 1.:
|
|
445
|
+
self.degrees_of_freedom_prior_ = self.degrees_of_freedom_prior
|
|
446
|
+
else:
|
|
447
|
+
raise ValueError("The parameter 'degrees_of_freedom_prior' "
|
|
448
|
+
"should be greater than %d, but got %.3f."
|
|
449
|
+
% (n_features - 1, self.degrees_of_freedom_prior))
|
|
450
|
+
|
|
451
|
+
def _checkcovariance_prior_parameter(self, X):
|
|
452
|
+
"""Check the `covariance_prior_`.
|
|
453
|
+
|
|
454
|
+
Parameters
|
|
455
|
+
----------
|
|
456
|
+
X : array-like, shape (n_samples, n_features)
|
|
457
|
+
"""
|
|
458
|
+
_, n_features = X.shape
|
|
459
|
+
|
|
460
|
+
if self.covariance_prior is None:
|
|
461
|
+
self.covariance_prior_ = {
|
|
462
|
+
'full': np.atleast_2d(np.cov(X.T)),
|
|
463
|
+
'tied': np.atleast_2d(np.cov(X.T)),
|
|
464
|
+
'diag': np.var(X, axis=0, ddof=1),
|
|
465
|
+
'spherical': np.var(X, axis=0, ddof=1).mean()
|
|
466
|
+
}[self.covariance_type]
|
|
467
|
+
|
|
468
|
+
elif self.covariance_type in ['full', 'tied']:
|
|
469
|
+
self.covariance_prior_ = check_array(
|
|
470
|
+
self.covariance_prior, dtype=[np.float64, np.float32],
|
|
471
|
+
ensure_2d=False)
|
|
472
|
+
_check_shape(self.covariance_prior_, (n_features, n_features),
|
|
473
|
+
'%s covariance_prior' % self.covariance_type)
|
|
474
|
+
_check_precision_matrix(self.covariance_prior_,
|
|
475
|
+
self.covariance_type)
|
|
476
|
+
elif self.covariance_type == 'diag':
|
|
477
|
+
self.covariance_prior_ = check_array(
|
|
478
|
+
self.covariance_prior, dtype=[np.float64, np.float32],
|
|
479
|
+
ensure_2d=False)
|
|
480
|
+
_check_shape(self.covariance_prior_, (n_features,),
|
|
481
|
+
'%s covariance_prior' % self.covariance_type)
|
|
482
|
+
_check_precision_positivity(self.covariance_prior_,
|
|
483
|
+
self.covariance_type)
|
|
484
|
+
# spherical case
|
|
485
|
+
elif self.covariance_prior > 0.:
|
|
486
|
+
self.covariance_prior_ = self.covariance_prior
|
|
487
|
+
else:
|
|
488
|
+
raise ValueError("The parameter 'spherical covariance_prior' "
|
|
489
|
+
"should be greater than 0., but got %.3f."
|
|
490
|
+
% self.covariance_prior)
|
|
491
|
+
|
|
492
|
+
|
|
493
|
+
# def _initialize_centers(self, X, random_state):
|
|
494
|
+
|
|
495
|
+
# n_samples, n_features = X.shape
|
|
496
|
+
|
|
497
|
+
# means = np.zeros([self.n_components, n_samples, n_features])
|
|
498
|
+
# for i in range(len(self.centers_init)):
|
|
499
|
+
# if n_features == 1: #(time,)
|
|
500
|
+
# means[i, :, :] = calc_time(self.centers_init[i:i+1, :], self.station_locs, self.phase_type, vel=self.vel)
|
|
501
|
+
# elif n_features == 2: #(time, amp)
|
|
502
|
+
# means[i, :, 0:1] = calc_time(self.centers_init[i:i+1, :-1], self.station_locs, self.phase_type, vel=self.vel)
|
|
503
|
+
# means[i, :, 1:2] = X[:,1:2]
|
|
504
|
+
# self.centers_init[i, -1:] = calc_mag(X[:,1:2], self.centers_init[i:i+1,:-1], self.station_locs, np.ones((len(X),1)))
|
|
505
|
+
# # means[i, :, 1:2] = calc_amp(self.centers_init[i, -1:], self.centers_init[i:i+1, :-1], self.station_locs)
|
|
506
|
+
# else:
|
|
507
|
+
# raise ValueError(f"n_features = {n_features} > 2!")
|
|
508
|
+
|
|
509
|
+
# ## performance is not good
|
|
510
|
+
# # resp = np.zeros((n_samples, self.n_components))
|
|
511
|
+
# # dist = np.sum(np.abs(means - X), axis=-1).T # (n_components, n_samples, n_features) -> (n_samples, n_components)
|
|
512
|
+
# # resp[np.arange(n_samples), np.argmax(dist, axis=1)] = 1.0
|
|
513
|
+
|
|
514
|
+
# ## performance is ok
|
|
515
|
+
# # sigma = np.array([1.0,1.0])
|
|
516
|
+
# # sigma = np.sqrt(np.diag(self.covariance_prior))
|
|
517
|
+
# # prob = np.sum(1.0/sigma * np.exp( - (means - X) ** 2 / (2 * sigma**2)), axis=-1).T # (n_components, n_samples, n_features) -> (n_samples, n_components)
|
|
518
|
+
# # prob_sum = np.sum(prob, axis=1, keepdims=True)
|
|
519
|
+
# # prob_sum[prob_sum == 0] = 1.0
|
|
520
|
+
# # resp = prob / prob_sum
|
|
521
|
+
|
|
522
|
+
# dist = np.linalg.norm(means - X, axis=-1).T # (n_components, n_samples, n_features) -> (n_samples, n_components)
|
|
523
|
+
# resp = np.exp(-dist)
|
|
524
|
+
# resp_sum = resp.sum(axis=1, keepdims=True)
|
|
525
|
+
# resp_sum[resp_sum == 0] = 1.0
|
|
526
|
+
# resp = resp / resp_sum
|
|
527
|
+
|
|
528
|
+
# return resp
|
|
529
|
+
|
|
530
|
+
def _initialize(self, X, resp):
|
|
531
|
+
"""Initialization of the mixture parameters.
|
|
532
|
+
|
|
533
|
+
Parameters
|
|
534
|
+
----------
|
|
535
|
+
X : array-like, shape (n_samples, n_features)
|
|
536
|
+
|
|
537
|
+
resp : array-like, shape (n_samples, n_components)
|
|
538
|
+
"""
|
|
539
|
+
nk, xk, sk, centers = _estimate_gaussian_parameters(
|
|
540
|
+
X, resp, self.reg_covar, self.covariance_type,
|
|
541
|
+
self.station_locs, self.phase_type, vel=self.vel, loss_type=self.loss_type,
|
|
542
|
+
centers_prev=self.centers_init, bounds=self.bounds, eikonal=self.eikonal)
|
|
543
|
+
|
|
544
|
+
self._estimate_weights(nk)
|
|
545
|
+
self._estimate_means(nk, xk)
|
|
546
|
+
self._estimate_precisions(nk, xk, sk)
|
|
547
|
+
self.centers_ = centers
|
|
548
|
+
|
|
549
|
+
def _estimate_weights(self, nk):
|
|
550
|
+
"""Estimate the parameters of the Dirichlet distribution.
|
|
551
|
+
|
|
552
|
+
Parameters
|
|
553
|
+
----------
|
|
554
|
+
nk : array-like, shape (n_components,)
|
|
555
|
+
"""
|
|
556
|
+
if self.weight_concentration_prior_type == 'dirichlet_process':
|
|
557
|
+
# For dirichlet process weight_concentration will be a tuple
|
|
558
|
+
# containing the two parameters of the beta distribution
|
|
559
|
+
self.weight_concentration_ = (
|
|
560
|
+
1. + nk,
|
|
561
|
+
(self.weight_concentration_prior_ +
|
|
562
|
+
np.hstack((np.cumsum(nk[::-1])[-2::-1], 0))))
|
|
563
|
+
else:
|
|
564
|
+
# case Variationnal Gaussian mixture with dirichlet distribution
|
|
565
|
+
self.weight_concentration_ = self.weight_concentration_prior_ + nk
|
|
566
|
+
|
|
567
|
+
def _estimate_means(self, nk, xk):
|
|
568
|
+
"""Estimate the parameters of the Gaussian distribution.
|
|
569
|
+
|
|
570
|
+
Parameters
|
|
571
|
+
----------
|
|
572
|
+
nk : array-like, shape (n_components,)
|
|
573
|
+
|
|
574
|
+
xk : array-like, shape (n_components, n_features)
|
|
575
|
+
"""
|
|
576
|
+
# self.mean_precision_ = self.mean_precision_prior_ + nk
|
|
577
|
+
# self.means_ = ((self.mean_precision_prior_ * self.mean_prior_ +
|
|
578
|
+
# nk[:, np.newaxis, np.newaxis] * xk) /
|
|
579
|
+
# self.mean_precision_[:, np.newaxis, np.newaxis])
|
|
580
|
+
self.mean_precision_ = nk
|
|
581
|
+
self.means_ = xk
|
|
582
|
+
|
|
583
|
+
def _estimate_precisions(self, nk, xk, sk):
|
|
584
|
+
"""Estimate the precisions parameters of the precision distribution.
|
|
585
|
+
|
|
586
|
+
Parameters
|
|
587
|
+
----------
|
|
588
|
+
nk : array-like, shape (n_components,)
|
|
589
|
+
|
|
590
|
+
xk : array-like, shape (n_components, n_features)
|
|
591
|
+
|
|
592
|
+
sk : array-like
|
|
593
|
+
The shape depends of `covariance_type`:
|
|
594
|
+
'full' : (n_components, n_features, n_features)
|
|
595
|
+
'tied' : (n_features, n_features)
|
|
596
|
+
'diag' : (n_components, n_features)
|
|
597
|
+
'spherical' : (n_components,)
|
|
598
|
+
"""
|
|
599
|
+
{"full": self._estimate_wishart_full,
|
|
600
|
+
"tied": self._estimate_wishart_tied,
|
|
601
|
+
"diag": self._estimate_wishart_diag,
|
|
602
|
+
"spherical": self._estimate_wishart_spherical
|
|
603
|
+
}[self.covariance_type](nk, xk, sk)
|
|
604
|
+
|
|
605
|
+
self.precisions_cholesky_ = _compute_precision_cholesky(
|
|
606
|
+
self.covariances_, self.covariance_type, self.max_covar)
|
|
607
|
+
|
|
608
|
+
def _estimate_wishart_full(self, nk, xk, sk):
|
|
609
|
+
"""Estimate the full Wishart distribution parameters.
|
|
610
|
+
|
|
611
|
+
Parameters
|
|
612
|
+
----------
|
|
613
|
+
X : array-like, shape (n_samples, n_features)
|
|
614
|
+
|
|
615
|
+
nk : array-like, shape (n_components,)
|
|
616
|
+
|
|
617
|
+
xk : array-like, shape (n_components, n_features)
|
|
618
|
+
|
|
619
|
+
sk : array-like, shape (n_components, n_features, n_features)
|
|
620
|
+
"""
|
|
621
|
+
_, n_samples, n_features = xk.shape
|
|
622
|
+
|
|
623
|
+
# Warning : in some Bishop book, there is a typo on the formula 10.63
|
|
624
|
+
# `degrees_of_freedom_k = degrees_of_freedom_0 + Nk` is
|
|
625
|
+
# the correct formula
|
|
626
|
+
self.degrees_of_freedom_ = self.degrees_of_freedom_prior_ + nk
|
|
627
|
+
|
|
628
|
+
self.covariances_ = np.empty((self.n_components, n_features, n_features))
|
|
629
|
+
|
|
630
|
+
# for k in range(self.n_components):
|
|
631
|
+
# diff = xk[k] - self.mean_prior_
|
|
632
|
+
# self.covariances_[k] = (self.covariance_prior_ + nk[k] * sk[k] +
|
|
633
|
+
# nk[k] * self.mean_precision_prior_ /
|
|
634
|
+
# # self.mean_precision_[k] * np.outer(diff, diff))
|
|
635
|
+
# self.mean_precision_[k] * np.dot(diff.T, diff)/n_samples)
|
|
636
|
+
# print(f"{self.covariance_prior_.shape = }", f"{sk.shape = }", f"{nk.shape = }")
|
|
637
|
+
self.covariances_ = self.covariance_prior_[np.newaxis, :, :] + nk[:, np.newaxis, np.newaxis] * sk
|
|
638
|
+
|
|
639
|
+
# Contrary to the original bishop book, we normalize the covariances
|
|
640
|
+
self.covariances_ /= (
|
|
641
|
+
self.degrees_of_freedom_[:, np.newaxis, np.newaxis])
|
|
642
|
+
|
|
643
|
+
def _estimate_wishart_tied(self, nk, xk, sk):
|
|
644
|
+
"""Estimate the tied Wishart distribution parameters.
|
|
645
|
+
|
|
646
|
+
Parameters
|
|
647
|
+
----------
|
|
648
|
+
X : array-like, shape (n_samples, n_features)
|
|
649
|
+
|
|
650
|
+
nk : array-like, shape (n_components,)
|
|
651
|
+
|
|
652
|
+
xk : array-like, shape (n_components, n_features)
|
|
653
|
+
|
|
654
|
+
sk : array-like, shape (n_features, n_features)
|
|
655
|
+
"""
|
|
656
|
+
_, _, n_features = xk.shape
|
|
657
|
+
|
|
658
|
+
# Warning : in some Bishop book, there is a typo on the formula 10.63
|
|
659
|
+
# `degrees_of_freedom_k = degrees_of_freedom_0 + Nk`
|
|
660
|
+
# is the correct formula
|
|
661
|
+
self.degrees_of_freedom_ = (
|
|
662
|
+
self.degrees_of_freedom_prior_ + nk.sum() / self.n_components)
|
|
663
|
+
|
|
664
|
+
diff = xk - self.mean_prior_
|
|
665
|
+
self.covariances_ = (
|
|
666
|
+
self.covariance_prior_ + sk * nk.sum() / self.n_components +
|
|
667
|
+
self.mean_precision_prior_ / self.n_components * np.dot(
|
|
668
|
+
(nk / self.mean_precision_) * diff.T, diff))
|
|
669
|
+
|
|
670
|
+
# Contrary to the original bishop book, we normalize the covariances
|
|
671
|
+
self.covariances_ /= self.degrees_of_freedom_
|
|
672
|
+
|
|
673
|
+
raise # not implemented
|
|
674
|
+
|
|
675
|
+
def _estimate_wishart_diag(self, nk, xk, sk):
|
|
676
|
+
"""Estimate the diag Wishart distribution parameters.
|
|
677
|
+
|
|
678
|
+
Parameters
|
|
679
|
+
----------
|
|
680
|
+
X : array-like, shape (n_samples, n_features)
|
|
681
|
+
|
|
682
|
+
nk : array-like, shape (n_components,)
|
|
683
|
+
|
|
684
|
+
xk : array-like, shape (n_components, n_features)
|
|
685
|
+
|
|
686
|
+
sk : array-like, shape (n_components, n_features)
|
|
687
|
+
"""
|
|
688
|
+
_, _, n_features = xk.shape
|
|
689
|
+
|
|
690
|
+
# Warning : in some Bishop book, there is a typo on the formula 10.63
|
|
691
|
+
# `degrees_of_freedom_k = degrees_of_freedom_0 + Nk`
|
|
692
|
+
# is the correct formula
|
|
693
|
+
self.degrees_of_freedom_ = self.degrees_of_freedom_prior_ + nk
|
|
694
|
+
|
|
695
|
+
diff = xk - self.means_
|
|
696
|
+
self.covariances_ = (
|
|
697
|
+
self.covariance_prior_ + nk[:, np.newaxis] * (
|
|
698
|
+
sk + (self.mean_precision_prior_ /
|
|
699
|
+
self.mean_precision_)[:, np.newaxis] * np.square(diff)))
|
|
700
|
+
|
|
701
|
+
# Contrary to the original bishop book, we normalize the covariances
|
|
702
|
+
self.covariances_ /= self.degrees_of_freedom_[:, np.newaxis]
|
|
703
|
+
|
|
704
|
+
raise # not implemented
|
|
705
|
+
|
|
706
|
+
def _estimate_wishart_spherical(self, nk, xk, sk):
|
|
707
|
+
"""Estimate the spherical Wishart distribution parameters.
|
|
708
|
+
|
|
709
|
+
Parameters
|
|
710
|
+
----------
|
|
711
|
+
X : array-like, shape (n_samples, n_features)
|
|
712
|
+
|
|
713
|
+
nk : array-like, shape (n_components,)
|
|
714
|
+
|
|
715
|
+
xk : array-like, shape (n_components, n_features)
|
|
716
|
+
|
|
717
|
+
sk : array-like, shape (n_components,)
|
|
718
|
+
"""
|
|
719
|
+
_, _, n_features = xk.shape
|
|
720
|
+
|
|
721
|
+
# Warning : in some Bishop book, there is a typo on the formula 10.63
|
|
722
|
+
# `degrees_of_freedom_k = degrees_of_freedom_0 + Nk`
|
|
723
|
+
# is the correct formula
|
|
724
|
+
self.degrees_of_freedom_ = self.degrees_of_freedom_prior_ + nk
|
|
725
|
+
|
|
726
|
+
diff = xk - self.mean_prior_
|
|
727
|
+
self.covariances_ = (
|
|
728
|
+
self.covariance_prior_ + nk * (
|
|
729
|
+
sk + self.mean_precision_prior_ / self.mean_precision_ *
|
|
730
|
+
np.mean(np.square(diff), 1)))
|
|
731
|
+
|
|
732
|
+
# Contrary to the original bishop book, we normalize the covariances
|
|
733
|
+
self.covariances_ /= self.degrees_of_freedom_
|
|
734
|
+
|
|
735
|
+
raise # not implemented
|
|
736
|
+
|
|
737
|
+
def _m_step(self, X, log_resp):
|
|
738
|
+
"""M step.
|
|
739
|
+
|
|
740
|
+
Parameters
|
|
741
|
+
----------
|
|
742
|
+
X : array-like, shape (n_samples, n_features)
|
|
743
|
+
|
|
744
|
+
log_resp : array-like, shape (n_samples, n_components)
|
|
745
|
+
Logarithm of the posterior probabilities (or responsibilities) of
|
|
746
|
+
the point of each sample in X.
|
|
747
|
+
"""
|
|
748
|
+
n_samples, _ = X.shape
|
|
749
|
+
|
|
750
|
+
nk, xk, sk, self.centers_ = _estimate_gaussian_parameters(
|
|
751
|
+
X, np.exp(log_resp), self.reg_covar, self.covariance_type,
|
|
752
|
+
self.station_locs, self.phase_type, vel=self.vel, loss_type=self.loss_type,
|
|
753
|
+
centers_prev=self.centers_, bounds=self.bounds, eikonal=self.eikonal)
|
|
754
|
+
self._estimate_weights(nk)
|
|
755
|
+
self._estimate_means(nk, xk)
|
|
756
|
+
self._estimate_precisions(nk, xk, sk)
|
|
757
|
+
|
|
758
|
+
def _estimate_log_weights(self):
|
|
759
|
+
if self.weight_concentration_prior_type == 'dirichlet_process':
|
|
760
|
+
digamma_sum = digamma(self.weight_concentration_[0] +
|
|
761
|
+
self.weight_concentration_[1])
|
|
762
|
+
digamma_a = digamma(self.weight_concentration_[0])
|
|
763
|
+
digamma_b = digamma(self.weight_concentration_[1])
|
|
764
|
+
return (digamma_a - digamma_sum +
|
|
765
|
+
np.hstack((0, np.cumsum(digamma_b - digamma_sum)[:-1])))
|
|
766
|
+
else:
|
|
767
|
+
# case Variationnal Gaussian mixture with dirichlet distribution
|
|
768
|
+
return (digamma(self.weight_concentration_) -
|
|
769
|
+
digamma(np.sum(self.weight_concentration_)))
|
|
770
|
+
|
|
771
|
+
def _estimate_log_prob(self, X):
|
|
772
|
+
_, n_features = X.shape
|
|
773
|
+
# We remove `n_features * np.log(self.degrees_of_freedom_)` because
|
|
774
|
+
# the precision matrix is normalized
|
|
775
|
+
log_gauss = (_estimate_log_gaussian_prob(
|
|
776
|
+
X, self.means_, self.precisions_cholesky_, self.covariance_type) -
|
|
777
|
+
.5 * n_features * np.log(self.degrees_of_freedom_))
|
|
778
|
+
|
|
779
|
+
if self.dummy_comp:
|
|
780
|
+
# print(np.quantile(np.max(log_gauss[:,:-1], axis=1), self.dummy_quantile), np.log(self.dummy_prob))
|
|
781
|
+
log_gauss[:,-1] = min(np.quantile(np.max(log_gauss[:,:-1], axis=1), self.dummy_quantile), np.log(self.dummy_prob))
|
|
782
|
+
|
|
783
|
+
log_gauss += np.log(self.phase_weight)[:,np.newaxis]
|
|
784
|
+
|
|
785
|
+
log_lambda = n_features * np.log(2.) + np.sum(digamma(
|
|
786
|
+
.5 * (self.degrees_of_freedom_ -
|
|
787
|
+
np.arange(0, n_features)[:, np.newaxis])), 0)
|
|
788
|
+
|
|
789
|
+
return log_gauss + .5 * (log_lambda -
|
|
790
|
+
n_features / self.mean_precision_)
|
|
791
|
+
|
|
792
|
+
def _compute_lower_bound(self, log_resp, log_prob_norm):
|
|
793
|
+
"""Estimate the lower bound of the model.
|
|
794
|
+
|
|
795
|
+
The lower bound on the likelihood (of the training data with respect to
|
|
796
|
+
the model) is used to detect the convergence and has to decrease at
|
|
797
|
+
each iteration.
|
|
798
|
+
|
|
799
|
+
Parameters
|
|
800
|
+
----------
|
|
801
|
+
X : array-like, shape (n_samples, n_features)
|
|
802
|
+
|
|
803
|
+
log_resp : array, shape (n_samples, n_components)
|
|
804
|
+
Logarithm of the posterior probabilities (or responsibilities) of
|
|
805
|
+
the point of each sample in X.
|
|
806
|
+
|
|
807
|
+
log_prob_norm : float
|
|
808
|
+
Logarithm of the probability of each sample in X.
|
|
809
|
+
|
|
810
|
+
Returns
|
|
811
|
+
-------
|
|
812
|
+
lower_bound : float
|
|
813
|
+
"""
|
|
814
|
+
# Contrary to the original formula, we have done some simplification
|
|
815
|
+
# and removed all the constant terms.
|
|
816
|
+
n_features, = self.mean_prior_.shape
|
|
817
|
+
|
|
818
|
+
# We removed `.5 * n_features * np.log(self.degrees_of_freedom_)`
|
|
819
|
+
# because the precision matrix is normalized.
|
|
820
|
+
log_det_precisions_chol = (_compute_log_det_cholesky(
|
|
821
|
+
self.precisions_cholesky_, self.covariance_type, n_features) -
|
|
822
|
+
.5 * n_features * np.log(self.degrees_of_freedom_))
|
|
823
|
+
|
|
824
|
+
if self.covariance_type == 'tied':
|
|
825
|
+
log_wishart = self.n_components * np.float64(_log_wishart_norm(
|
|
826
|
+
self.degrees_of_freedom_, log_det_precisions_chol, n_features))
|
|
827
|
+
else:
|
|
828
|
+
log_wishart = np.sum(_log_wishart_norm(
|
|
829
|
+
self.degrees_of_freedom_, log_det_precisions_chol, n_features))
|
|
830
|
+
|
|
831
|
+
if self.weight_concentration_prior_type == 'dirichlet_process':
|
|
832
|
+
log_norm_weight = -np.sum(betaln(self.weight_concentration_[0],
|
|
833
|
+
self.weight_concentration_[1]))
|
|
834
|
+
else:
|
|
835
|
+
log_norm_weight = _log_dirichlet_norm(self.weight_concentration_)
|
|
836
|
+
|
|
837
|
+
return (-np.sum(np.exp(log_resp) * log_resp) -
|
|
838
|
+
log_wishart - log_norm_weight -
|
|
839
|
+
0.5 * n_features * np.sum(np.log(self.mean_precision_)))
|
|
840
|
+
|
|
841
|
+
def _get_parameters(self):
|
|
842
|
+
return (self.weight_concentration_,
|
|
843
|
+
self.mean_precision_, self.means_,
|
|
844
|
+
self.degrees_of_freedom_, self.covariances_,
|
|
845
|
+
self.precisions_cholesky_)
|
|
846
|
+
|
|
847
|
+
def _set_parameters(self, params):
|
|
848
|
+
(self.weight_concentration_, self.mean_precision_, self.means_,
|
|
849
|
+
self.degrees_of_freedom_, self.covariances_,
|
|
850
|
+
self.precisions_cholesky_) = params
|
|
851
|
+
|
|
852
|
+
# Weights computation
|
|
853
|
+
if self.weight_concentration_prior_type == "dirichlet_process":
|
|
854
|
+
weight_dirichlet_sum = (self.weight_concentration_[0] +
|
|
855
|
+
self.weight_concentration_[1])
|
|
856
|
+
tmp = self.weight_concentration_[1] / weight_dirichlet_sum
|
|
857
|
+
self.weights_ = (
|
|
858
|
+
self.weight_concentration_[0] / weight_dirichlet_sum *
|
|
859
|
+
np.hstack((1, np.cumprod(tmp[:-1]))))
|
|
860
|
+
self.weights_ /= np.sum(self.weights_)
|
|
861
|
+
else:
|
|
862
|
+
self. weights_ = (self.weight_concentration_ /
|
|
863
|
+
np.sum(self.weight_concentration_))
|
|
864
|
+
|
|
865
|
+
# Precisions matrices computation
|
|
866
|
+
if self.covariance_type == 'full':
|
|
867
|
+
self.precisions_ = np.array([
|
|
868
|
+
np.dot(prec_chol, prec_chol.T)
|
|
869
|
+
for prec_chol in self.precisions_cholesky_])
|
|
870
|
+
|
|
871
|
+
elif self.covariance_type == 'tied':
|
|
872
|
+
self.precisions_ = np.dot(self.precisions_cholesky_,
|
|
873
|
+
self.precisions_cholesky_.T)
|
|
874
|
+
else:
|
|
875
|
+
self.precisions_ = self.precisions_cholesky_ ** 2
|