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,866 @@
|
|
|
1
|
+
"""Gaussian Mixture Model."""
|
|
2
|
+
|
|
3
|
+
# Author: Wei Xue <xuewei4d@gmail.com>
|
|
4
|
+
# Modified by Thierry Guillemot <thierry.guillemot.work@gmail.com>
|
|
5
|
+
# License: BSD 3 clause
|
|
6
|
+
|
|
7
|
+
import numpy as np
|
|
8
|
+
from scipy import linalg
|
|
9
|
+
from sklearn.utils import check_array
|
|
10
|
+
from sklearn.utils.extmath import row_norms
|
|
11
|
+
from sklearn.utils.validation import _deprecate_positional_args
|
|
12
|
+
|
|
13
|
+
from .seismic_ops import *
|
|
14
|
+
from ._base import BaseMixture, _check_shape
|
|
15
|
+
|
|
16
|
+
###############################################################################
|
|
17
|
+
# Gaussian mixture shape checkers used by the GaussianMixture class
|
|
18
|
+
|
|
19
|
+
def _check_weights(weights, n_components):
|
|
20
|
+
"""Check the user provided 'weights'.
|
|
21
|
+
|
|
22
|
+
Parameters
|
|
23
|
+
----------
|
|
24
|
+
weights : array-like of shape (n_components,)
|
|
25
|
+
The proportions of components of each mixture.
|
|
26
|
+
|
|
27
|
+
n_components : int
|
|
28
|
+
Number of components.
|
|
29
|
+
|
|
30
|
+
Returns
|
|
31
|
+
-------
|
|
32
|
+
weights : array, shape (n_components,)
|
|
33
|
+
"""
|
|
34
|
+
weights = check_array(weights, dtype=[np.float64, np.float32],
|
|
35
|
+
ensure_2d=False)
|
|
36
|
+
_check_shape(weights, (n_components,), 'weights')
|
|
37
|
+
|
|
38
|
+
# check range
|
|
39
|
+
if (any(np.less(weights, 0.)) or
|
|
40
|
+
any(np.greater(weights, 1.))):
|
|
41
|
+
raise ValueError("The parameter 'weights' should be in the range "
|
|
42
|
+
"[0, 1], but got max value %.5f, min value %.5f"
|
|
43
|
+
% (np.min(weights), np.max(weights)))
|
|
44
|
+
|
|
45
|
+
# check normalization
|
|
46
|
+
if not np.allclose(np.abs(1. - np.sum(weights)), 0.):
|
|
47
|
+
raise ValueError("The parameter 'weights' should be normalized, "
|
|
48
|
+
"but got sum(weights) = %.5f" % np.sum(weights))
|
|
49
|
+
return weights
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _check_means(means, n_components, n_samples, n_features):
|
|
53
|
+
"""Validate the provided 'means'.
|
|
54
|
+
|
|
55
|
+
Parameters
|
|
56
|
+
----------
|
|
57
|
+
means : array-like of shape (n_components, n_features)
|
|
58
|
+
The centers of the current components.
|
|
59
|
+
|
|
60
|
+
n_components : int
|
|
61
|
+
Number of components.
|
|
62
|
+
|
|
63
|
+
n_features : int
|
|
64
|
+
Number of features.
|
|
65
|
+
|
|
66
|
+
Returns
|
|
67
|
+
-------
|
|
68
|
+
means : array, (n_components, n_features)
|
|
69
|
+
"""
|
|
70
|
+
means = check_array(means, dtype=[np.float64, np.float64, np.float32], ensure_2d=False)
|
|
71
|
+
_check_shape(means, (n_components, n_samples, n_features), 'means')
|
|
72
|
+
return means
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def _check_precision_positivity(precision, covariance_type):
|
|
76
|
+
"""Check a precision vector is positive-definite."""
|
|
77
|
+
if np.any(np.less_equal(precision, 0.0)):
|
|
78
|
+
raise ValueError("'%s precision' should be "
|
|
79
|
+
"positive" % covariance_type)
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def _check_precision_matrix(precision, covariance_type):
|
|
83
|
+
"""Check a precision matrix is symmetric and positive-definite."""
|
|
84
|
+
if not (np.allclose(precision, precision.T) and
|
|
85
|
+
np.all(linalg.eigvalsh(precision) > 0.)):
|
|
86
|
+
raise ValueError("'%s precision' should be symmetric, "
|
|
87
|
+
"positive-definite" % covariance_type)
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def _check_precisions_full(precisions, covariance_type):
|
|
91
|
+
"""Check the precision matrices are symmetric and positive-definite."""
|
|
92
|
+
for prec in precisions:
|
|
93
|
+
_check_precision_matrix(prec, covariance_type)
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def _check_precisions(precisions, covariance_type, n_components, n_features):
|
|
97
|
+
"""Validate user provided precisions.
|
|
98
|
+
|
|
99
|
+
Parameters
|
|
100
|
+
----------
|
|
101
|
+
precisions : array-like
|
|
102
|
+
'full' : shape of (n_components, n_features, n_features)
|
|
103
|
+
'tied' : shape of (n_features, n_features)
|
|
104
|
+
'diag' : shape of (n_components, n_features)
|
|
105
|
+
'spherical' : shape of (n_components,)
|
|
106
|
+
|
|
107
|
+
covariance_type : string
|
|
108
|
+
|
|
109
|
+
n_components : int
|
|
110
|
+
Number of components.
|
|
111
|
+
|
|
112
|
+
n_features : int
|
|
113
|
+
Number of features.
|
|
114
|
+
|
|
115
|
+
Returns
|
|
116
|
+
-------
|
|
117
|
+
precisions : array
|
|
118
|
+
"""
|
|
119
|
+
precisions = check_array(precisions, dtype=[np.float64, np.float32],
|
|
120
|
+
ensure_2d=False,
|
|
121
|
+
allow_nd=covariance_type == 'full')
|
|
122
|
+
|
|
123
|
+
precisions_shape = {'full': (n_components, n_features, n_features),
|
|
124
|
+
'tied': (n_features, n_features),
|
|
125
|
+
'diag': (n_components, n_features),
|
|
126
|
+
'spherical': (n_components,)}
|
|
127
|
+
_check_shape(precisions, precisions_shape[covariance_type],
|
|
128
|
+
'%s precision' % covariance_type)
|
|
129
|
+
|
|
130
|
+
_check_precisions = {'full': _check_precisions_full,
|
|
131
|
+
'tied': _check_precision_matrix,
|
|
132
|
+
'diag': _check_precision_positivity,
|
|
133
|
+
'spherical': _check_precision_positivity}
|
|
134
|
+
_check_precisions[covariance_type](precisions, covariance_type)
|
|
135
|
+
return precisions
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
###############################################################################
|
|
139
|
+
# Gaussian mixture parameters estimators (used by the M-Step)
|
|
140
|
+
|
|
141
|
+
def _estimate_gaussian_covariances_full(resp, X, nk, means, reg_covar):
|
|
142
|
+
"""Estimate the full covariance matrices.
|
|
143
|
+
|
|
144
|
+
Parameters
|
|
145
|
+
----------
|
|
146
|
+
resp : array-like of shape (n_samples, n_components)
|
|
147
|
+
|
|
148
|
+
X : array-like of shape (n_samples, n_features)
|
|
149
|
+
|
|
150
|
+
nk : array-like of shape (n_components,)
|
|
151
|
+
|
|
152
|
+
means : array-like of shape (n_components, n_features)
|
|
153
|
+
|
|
154
|
+
reg_covar : float
|
|
155
|
+
|
|
156
|
+
Returns
|
|
157
|
+
-------
|
|
158
|
+
covariances : array, shape (n_components, n_features, n_features)
|
|
159
|
+
The covariance matrix of the current components.
|
|
160
|
+
"""
|
|
161
|
+
n_components, _, n_features = means.shape
|
|
162
|
+
covariances = np.empty((n_components, n_features, n_features))
|
|
163
|
+
for k in range(n_components):
|
|
164
|
+
diff = X - means[k]
|
|
165
|
+
covariances[k] = np.dot(resp[:, k] * diff.T, diff) / nk[k]
|
|
166
|
+
covariances[k].flat[::n_features + 1] += reg_covar
|
|
167
|
+
return covariances
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def _estimate_gaussian_covariances_tied(resp, X, nk, means, reg_covar):
|
|
171
|
+
"""Estimate the tied covariance matrix.
|
|
172
|
+
|
|
173
|
+
Parameters
|
|
174
|
+
----------
|
|
175
|
+
resp : array-like of shape (n_samples, n_components)
|
|
176
|
+
|
|
177
|
+
X : array-like of shape (n_samples, n_features)
|
|
178
|
+
|
|
179
|
+
nk : array-like of shape (n_components,)
|
|
180
|
+
|
|
181
|
+
means : array-like of shape (n_components, n_features)
|
|
182
|
+
|
|
183
|
+
reg_covar : float
|
|
184
|
+
|
|
185
|
+
Returns
|
|
186
|
+
-------
|
|
187
|
+
covariance : array, shape (n_features, n_features)
|
|
188
|
+
The tied covariance matrix of the components.
|
|
189
|
+
"""
|
|
190
|
+
avg_X2 = np.dot(X.T, X)
|
|
191
|
+
avg_means2 = np.dot(nk * means.T, means)
|
|
192
|
+
covariance = avg_X2 - avg_means2
|
|
193
|
+
covariance /= nk.sum()
|
|
194
|
+
covariance.flat[::len(covariance) + 1] += reg_covar
|
|
195
|
+
return covariance
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def _estimate_gaussian_covariances_diag(resp, X, nk, means, reg_covar):
|
|
199
|
+
"""Estimate the diagonal covariance vectors.
|
|
200
|
+
|
|
201
|
+
Parameters
|
|
202
|
+
----------
|
|
203
|
+
responsibilities : array-like of shape (n_samples, n_components)
|
|
204
|
+
|
|
205
|
+
X : array-like of shape (n_samples, n_features)
|
|
206
|
+
|
|
207
|
+
nk : array-like of shape (n_components,)
|
|
208
|
+
|
|
209
|
+
means : array-like of shape (n_components, n_features)
|
|
210
|
+
|
|
211
|
+
reg_covar : float
|
|
212
|
+
|
|
213
|
+
Returns
|
|
214
|
+
-------
|
|
215
|
+
covariances : array, shape (n_components, n_features)
|
|
216
|
+
The covariance vector of the current components.
|
|
217
|
+
"""
|
|
218
|
+
avg_X2 = np.dot(resp.T, X * X) / nk[:, np.newaxis]
|
|
219
|
+
avg_means2 = means ** 2
|
|
220
|
+
avg_X_means = means * np.dot(resp.T, X) / nk[:, np.newaxis]
|
|
221
|
+
return avg_X2 - 2 * avg_X_means + avg_means2 + reg_covar
|
|
222
|
+
|
|
223
|
+
# n_components, _, n_features = means.shape
|
|
224
|
+
# covariances = np.empty((n_components, n_features))
|
|
225
|
+
# for k in range(n_components):
|
|
226
|
+
# diff = X - means[k]
|
|
227
|
+
# covariances[k] = np.diag(np.dot(resp[:, k] * diff.T, diff)) / nk[k]
|
|
228
|
+
# covariances[k] += reg_covar
|
|
229
|
+
# return covariances
|
|
230
|
+
|
|
231
|
+
def _estimate_gaussian_covariances_spherical(resp, X, nk, means, reg_covar):
|
|
232
|
+
"""Estimate the spherical variance values.
|
|
233
|
+
|
|
234
|
+
Parameters
|
|
235
|
+
----------
|
|
236
|
+
responsibilities : array-like of shape (n_samples, n_components)
|
|
237
|
+
|
|
238
|
+
X : array-like of shape (n_samples, n_features)
|
|
239
|
+
|
|
240
|
+
nk : array-like of shape (n_components,)
|
|
241
|
+
|
|
242
|
+
means : array-like of shape (n_components, n_features)
|
|
243
|
+
|
|
244
|
+
reg_covar : float
|
|
245
|
+
|
|
246
|
+
Returns
|
|
247
|
+
-------
|
|
248
|
+
variances : array, shape (n_components,)
|
|
249
|
+
The variance values of each components.
|
|
250
|
+
"""
|
|
251
|
+
return _estimate_gaussian_covariances_diag(resp, X, nk,
|
|
252
|
+
means, reg_covar).mean(1)
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
def _estimate_gaussian_parameters(X, resp, reg_covar, covariance_type, station_locs, phase_type,
|
|
259
|
+
vel={"p":6.0, "s":6.0/1.75}, loss_type="l2", centers_prev=None, bounds=None, eikonal=None):
|
|
260
|
+
"""Estimate the Gaussian distribution parameters.
|
|
261
|
+
|
|
262
|
+
Parameters
|
|
263
|
+
----------
|
|
264
|
+
X : array-like of shape (n_samples, n_features)
|
|
265
|
+
The input data array.
|
|
266
|
+
|
|
267
|
+
resp : array-like of shape (n_samples, n_components)
|
|
268
|
+
The responsibilities for each data sample in X.
|
|
269
|
+
|
|
270
|
+
reg_covar : float
|
|
271
|
+
The regularization added to the diagonal of the covariance matrices.
|
|
272
|
+
|
|
273
|
+
covariance_type : {'full', 'tied', 'diag', 'spherical'}
|
|
274
|
+
The type of precision matrices.
|
|
275
|
+
|
|
276
|
+
centers_prev: (stations(x, y, ...), time, amp, ...)
|
|
277
|
+
|
|
278
|
+
Returns
|
|
279
|
+
-------
|
|
280
|
+
nk : array-like of shape (n_components,)
|
|
281
|
+
The numbers of data samples in the current components.
|
|
282
|
+
|
|
283
|
+
means : array-like of shape (n_components, n_features)
|
|
284
|
+
The centers of the current components.
|
|
285
|
+
|
|
286
|
+
covariances : array-like
|
|
287
|
+
The covariance matrix of the current components.
|
|
288
|
+
The shape depends of the covariance_type.
|
|
289
|
+
"""
|
|
290
|
+
nk = resp.sum(axis=0) + 10 * np.finfo(resp.dtype).eps
|
|
291
|
+
# means = np.dot(resp.T, X) / nk[:, np.newaxis]
|
|
292
|
+
# means = np.tile(means, [X.shape[0],1,1]).transpose((1,0,2))
|
|
293
|
+
n_features = X.shape[1]
|
|
294
|
+
|
|
295
|
+
if centers_prev is None:
|
|
296
|
+
centers_prev = np.dot(resp.T, np.hstack([station_locs, X])) / nk[:, np.newaxis]
|
|
297
|
+
centers = np.zeros_like(centers_prev) #x, y, z, t, amp, ...
|
|
298
|
+
|
|
299
|
+
for i in range(len(centers_prev)):
|
|
300
|
+
if n_features == 1:
|
|
301
|
+
loc, loss = calc_loc(X[:,:1], phase_type, station_locs, resp[:, i:i+1], centers_prev[i:i+1, :], vel=vel, bounds=bounds, eikonal=eikonal)
|
|
302
|
+
centers[i:i+1, :] = loc
|
|
303
|
+
elif n_features == 2:
|
|
304
|
+
loc, loss = calc_loc(X[:,:1], phase_type, station_locs, resp[:, i:i+1], centers_prev[i:i+1, :-1], vel=vel, bounds=bounds, eikonal=eikonal)
|
|
305
|
+
centers[i:i+1, :-1] = loc
|
|
306
|
+
centers[i:i+1, -1:] = calc_mag(X[:,1:2], centers[i:i+1,:-1], station_locs, resp[:,i:i+1])
|
|
307
|
+
else:
|
|
308
|
+
raise ValueError(f"n_features = {n_features} > 2!")
|
|
309
|
+
|
|
310
|
+
means = np.zeros([resp.shape[1], X.shape[0], X.shape[1]])
|
|
311
|
+
for i in range(len(centers)):
|
|
312
|
+
if n_features == 1:
|
|
313
|
+
means[i, :, :] = calc_time(centers[i:i+1, :], station_locs, phase_type, vel=vel, eikonal=eikonal)
|
|
314
|
+
elif n_features == 2:
|
|
315
|
+
means[i, :, 0:1] = calc_time(centers[i:i+1, :-1], station_locs, phase_type, vel=vel, eikonal=eikonal)
|
|
316
|
+
means[i, :, 1:2] = calc_amp(centers[i:i+1, -1:], centers[i:i+1, :-1], station_locs)
|
|
317
|
+
else:
|
|
318
|
+
raise ValueError(f"n_features = {n_features} > 2!")
|
|
319
|
+
|
|
320
|
+
covariances = {"full": _estimate_gaussian_covariances_full,
|
|
321
|
+
"tied": _estimate_gaussian_covariances_tied,
|
|
322
|
+
"diag": _estimate_gaussian_covariances_diag,
|
|
323
|
+
"spherical": _estimate_gaussian_covariances_spherical
|
|
324
|
+
}[covariance_type](resp, X, nk, means, reg_covar)
|
|
325
|
+
|
|
326
|
+
return nk, means, covariances, centers
|
|
327
|
+
|
|
328
|
+
|
|
329
|
+
def _compute_precision_cholesky(covariances, covariance_type, max_covar=None):
|
|
330
|
+
"""Compute the Cholesky decomposition of the precisions.
|
|
331
|
+
|
|
332
|
+
Parameters
|
|
333
|
+
----------
|
|
334
|
+
covariances : array-like
|
|
335
|
+
The covariance matrix of the current components.
|
|
336
|
+
The shape depends of the covariance_type.
|
|
337
|
+
|
|
338
|
+
covariance_type : {'full', 'tied', 'diag', 'spherical'}
|
|
339
|
+
The type of precision matrices.
|
|
340
|
+
|
|
341
|
+
Returns
|
|
342
|
+
-------
|
|
343
|
+
precisions_cholesky : array-like
|
|
344
|
+
The cholesky decomposition of sample precisions of the current
|
|
345
|
+
components. The shape depends of the covariance_type.
|
|
346
|
+
"""
|
|
347
|
+
estimate_precision_error_message = (
|
|
348
|
+
"Fitting the mixture model failed because some components have "
|
|
349
|
+
"ill-defined empirical covariance (for instance caused by singleton "
|
|
350
|
+
"or collapsed samples). Try to decrease the number of components, "
|
|
351
|
+
"or increase reg_covar.")
|
|
352
|
+
|
|
353
|
+
if covariance_type == 'full':
|
|
354
|
+
n_components, n_features, _ = covariances.shape
|
|
355
|
+
precisions_chol = np.empty((n_components, n_features, n_features))
|
|
356
|
+
for k, covariance in enumerate(covariances):
|
|
357
|
+
try:
|
|
358
|
+
cov_chol = linalg.cholesky(covariance, lower=True)
|
|
359
|
+
except linalg.LinAlgError:
|
|
360
|
+
raise ValueError(estimate_precision_error_message)
|
|
361
|
+
precisions_chol[k] = linalg.solve_triangular(cov_chol,
|
|
362
|
+
np.eye(n_features),
|
|
363
|
+
lower=True).T
|
|
364
|
+
elif covariance_type == 'tied':
|
|
365
|
+
_, n_features = covariances.shape
|
|
366
|
+
try:
|
|
367
|
+
cov_chol = linalg.cholesky(covariances, lower=True)
|
|
368
|
+
except linalg.LinAlgError:
|
|
369
|
+
raise ValueError(estimate_precision_error_message)
|
|
370
|
+
precisions_chol = linalg.solve_triangular(cov_chol, np.eye(n_features),
|
|
371
|
+
lower=True).T
|
|
372
|
+
else:
|
|
373
|
+
if np.any(np.less_equal(covariances, 0.0)):
|
|
374
|
+
raise ValueError(estimate_precision_error_message)
|
|
375
|
+
precisions_chol = 1. / np.sqrt(covariances)
|
|
376
|
+
|
|
377
|
+
if max_covar is not None:
|
|
378
|
+
non_zero = (np.abs(precisions_chol) != 0.0)
|
|
379
|
+
precisions_chol[non_zero] = 1.0/(np.sqrt(max_covar) * np.tanh(1.0/precisions_chol[non_zero]/np.sqrt(max_covar)))
|
|
380
|
+
precisions_chol[~non_zero] = 1.0/np.sqrt(max_covar)
|
|
381
|
+
|
|
382
|
+
return precisions_chol
|
|
383
|
+
|
|
384
|
+
|
|
385
|
+
###############################################################################
|
|
386
|
+
# Gaussian mixture probability estimators
|
|
387
|
+
def _compute_log_det_cholesky(matrix_chol, covariance_type, n_features):
|
|
388
|
+
"""Compute the log-det of the cholesky decomposition of matrices.
|
|
389
|
+
|
|
390
|
+
Parameters
|
|
391
|
+
----------
|
|
392
|
+
matrix_chol : array-like
|
|
393
|
+
Cholesky decompositions of the matrices.
|
|
394
|
+
'full' : shape of (n_components, n_features, n_features)
|
|
395
|
+
'tied' : shape of (n_features, n_features)
|
|
396
|
+
'diag' : shape of (n_components, n_features)
|
|
397
|
+
'spherical' : shape of (n_components,)
|
|
398
|
+
|
|
399
|
+
covariance_type : {'full', 'tied', 'diag', 'spherical'}
|
|
400
|
+
|
|
401
|
+
n_features : int
|
|
402
|
+
Number of features.
|
|
403
|
+
|
|
404
|
+
Returns
|
|
405
|
+
-------
|
|
406
|
+
log_det_precision_chol : array-like of shape (n_components,)
|
|
407
|
+
The determinant of the precision matrix for each component.
|
|
408
|
+
"""
|
|
409
|
+
if covariance_type == 'full':
|
|
410
|
+
n_components, _, _ = matrix_chol.shape
|
|
411
|
+
log_det_chol = (np.sum(np.log(
|
|
412
|
+
matrix_chol.reshape(
|
|
413
|
+
n_components, -1)[:, ::n_features + 1]), 1))
|
|
414
|
+
|
|
415
|
+
elif covariance_type == 'tied':
|
|
416
|
+
log_det_chol = (np.sum(np.log(np.diag(matrix_chol))))
|
|
417
|
+
|
|
418
|
+
elif covariance_type == 'diag':
|
|
419
|
+
log_det_chol = (np.sum(np.log(matrix_chol), axis=1))
|
|
420
|
+
|
|
421
|
+
else:
|
|
422
|
+
log_det_chol = n_features * (np.log(matrix_chol))
|
|
423
|
+
|
|
424
|
+
return log_det_chol
|
|
425
|
+
|
|
426
|
+
|
|
427
|
+
def _estimate_log_gaussian_prob(X, means, precisions_chol, covariance_type):
|
|
428
|
+
"""Estimate the log Gaussian probability.
|
|
429
|
+
|
|
430
|
+
Parameters
|
|
431
|
+
----------
|
|
432
|
+
X : array-like of shape (n_samples, n_features)
|
|
433
|
+
|
|
434
|
+
means : array-like of shape (n_components, n_features)
|
|
435
|
+
|
|
436
|
+
precisions_chol : array-like
|
|
437
|
+
Cholesky decompositions of the precision matrices.
|
|
438
|
+
'full' : shape of (n_components, n_features, n_features)
|
|
439
|
+
'tied' : shape of (n_features, n_features)
|
|
440
|
+
'diag' : shape of (n_components, n_features)
|
|
441
|
+
'spherical' : shape of (n_components,)
|
|
442
|
+
|
|
443
|
+
covariance_type : {'full', 'tied', 'diag', 'spherical'}
|
|
444
|
+
|
|
445
|
+
Returns
|
|
446
|
+
-------
|
|
447
|
+
log_prob : array, shape (n_samples, n_components)
|
|
448
|
+
"""
|
|
449
|
+
n_samples, n_features = X.shape
|
|
450
|
+
n_components, _, _ = means.shape
|
|
451
|
+
# det(precision_chol) is half of det(precision)
|
|
452
|
+
log_det = _compute_log_det_cholesky(
|
|
453
|
+
precisions_chol, covariance_type, n_features)
|
|
454
|
+
|
|
455
|
+
if covariance_type == 'full':
|
|
456
|
+
log_prob = np.empty((n_samples, n_components))
|
|
457
|
+
for k, (mu, prec_chol) in enumerate(zip(means, precisions_chol)):
|
|
458
|
+
y = np.dot(X, prec_chol) - np.dot(mu, prec_chol)
|
|
459
|
+
log_prob[:, k] = np.sum(np.square(y), axis=1)
|
|
460
|
+
|
|
461
|
+
elif covariance_type == 'tied':
|
|
462
|
+
log_prob = np.empty((n_samples, n_components))
|
|
463
|
+
for k, mu in enumerate(means):
|
|
464
|
+
y = np.dot(X, precisions_chol) - np.dot(mu, precisions_chol)
|
|
465
|
+
log_prob[:, k] = np.sum(np.square(y), axis=1)
|
|
466
|
+
|
|
467
|
+
elif covariance_type == 'diag':
|
|
468
|
+
precisions = precisions_chol ** 2
|
|
469
|
+
log_prob = (np.sum((means ** 2 * precisions), 1) -
|
|
470
|
+
2. * np.dot(X, (means * precisions).T) +
|
|
471
|
+
np.dot(X ** 2, precisions.T))
|
|
472
|
+
# log_prob = np.empty((n_samples, n_components))
|
|
473
|
+
# for k, (mu, prec_chol) in enumerate(zip(means, precisions_chol)):
|
|
474
|
+
# y = np.dot(X, prec_chol) - np.dot(mu, prec_chol)
|
|
475
|
+
# log_prob[:, k] = np.square(y)
|
|
476
|
+
|
|
477
|
+
elif covariance_type == 'spherical':
|
|
478
|
+
precisions = precisions_chol ** 2
|
|
479
|
+
log_prob = (np.sum(means ** 2, 1) * precisions -
|
|
480
|
+
2 * np.dot(X, means.T * precisions) +
|
|
481
|
+
np.outer(row_norms(X, squared=True), precisions))
|
|
482
|
+
return -.5 * (n_features * np.log(2 * np.pi) + log_prob) + log_det
|
|
483
|
+
|
|
484
|
+
|
|
485
|
+
class GaussianMixture(BaseMixture):
|
|
486
|
+
"""Gaussian Mixture.
|
|
487
|
+
|
|
488
|
+
Representation of a Gaussian mixture model probability distribution.
|
|
489
|
+
This class allows to estimate the parameters of a Gaussian mixture
|
|
490
|
+
distribution.
|
|
491
|
+
|
|
492
|
+
Read more in the :ref:`User Guide <gmm>`.
|
|
493
|
+
|
|
494
|
+
.. versionadded:: 0.18
|
|
495
|
+
|
|
496
|
+
Parameters
|
|
497
|
+
----------
|
|
498
|
+
n_components : int, default=1
|
|
499
|
+
The number of mixture components.
|
|
500
|
+
|
|
501
|
+
covariance_type : {'full', 'tied', 'diag', 'spherical'}, default='full'
|
|
502
|
+
String describing the type of covariance parameters to use.
|
|
503
|
+
Must be one of:
|
|
504
|
+
|
|
505
|
+
'full'
|
|
506
|
+
each component has its own general covariance matrix
|
|
507
|
+
'tied'
|
|
508
|
+
all components share the same general covariance matrix
|
|
509
|
+
'diag'
|
|
510
|
+
each component has its own diagonal covariance matrix
|
|
511
|
+
'spherical'
|
|
512
|
+
each component has its own single variance
|
|
513
|
+
|
|
514
|
+
tol : float, default=1e-3
|
|
515
|
+
The convergence threshold. EM iterations will stop when the
|
|
516
|
+
lower bound average gain is below this threshold.
|
|
517
|
+
|
|
518
|
+
reg_covar : float, default=1e-6
|
|
519
|
+
Non-negative regularization added to the diagonal of covariance.
|
|
520
|
+
Allows to assure that the covariance matrices are all positive.
|
|
521
|
+
|
|
522
|
+
max_iter : int, default=100
|
|
523
|
+
The number of EM iterations to perform.
|
|
524
|
+
|
|
525
|
+
n_init : int, default=1
|
|
526
|
+
The number of initializations to perform. The best results are kept.
|
|
527
|
+
|
|
528
|
+
init_params : {'kmeans', 'random'}, default='kmeans'
|
|
529
|
+
The method used to initialize the weights, the means and the
|
|
530
|
+
precisions.
|
|
531
|
+
Must be one of::
|
|
532
|
+
|
|
533
|
+
'kmeans' : responsibilities are initialized using kmeans.
|
|
534
|
+
'random' : responsibilities are initialized randomly.
|
|
535
|
+
|
|
536
|
+
weights_init : array-like of shape (n_components, ), default=None
|
|
537
|
+
The user-provided initial weights.
|
|
538
|
+
If it is None, weights are initialized using the `init_params` method.
|
|
539
|
+
|
|
540
|
+
means_init : array-like of shape (n_components, n_features), default=None
|
|
541
|
+
The user-provided initial means,
|
|
542
|
+
If it is None, means are initialized using the `init_params` method.
|
|
543
|
+
|
|
544
|
+
precisions_init : array-like, default=None
|
|
545
|
+
The user-provided initial precisions (inverse of the covariance
|
|
546
|
+
matrices).
|
|
547
|
+
If it is None, precisions are initialized using the 'init_params'
|
|
548
|
+
method.
|
|
549
|
+
The shape depends on 'covariance_type'::
|
|
550
|
+
|
|
551
|
+
(n_components,) if 'spherical',
|
|
552
|
+
(n_features, n_features) if 'tied',
|
|
553
|
+
(n_components, n_features) if 'diag',
|
|
554
|
+
(n_components, n_features, n_features) if 'full'
|
|
555
|
+
|
|
556
|
+
random_state : int, RandomState instance or None, default=None
|
|
557
|
+
Controls the random seed given to the method chosen to initialize the
|
|
558
|
+
parameters (see `init_params`).
|
|
559
|
+
In addition, it controls the generation of random samples from the
|
|
560
|
+
fitted distribution (see the method `sample`).
|
|
561
|
+
Pass an int for reproducible output across multiple function calls.
|
|
562
|
+
See :term:`Glossary <random_state>`.
|
|
563
|
+
|
|
564
|
+
warm_start : bool, default=False
|
|
565
|
+
If 'warm_start' is True, the solution of the last fitting is used as
|
|
566
|
+
initialization for the next call of fit(). This can speed up
|
|
567
|
+
convergence when fit is called several times on similar problems.
|
|
568
|
+
In that case, 'n_init' is ignored and only a single initialization
|
|
569
|
+
occurs upon the first call.
|
|
570
|
+
See :term:`the Glossary <warm_start>`.
|
|
571
|
+
|
|
572
|
+
verbose : int, default=0
|
|
573
|
+
Enable verbose output. If 1 then it prints the current
|
|
574
|
+
initialization and each iteration step. If greater than 1 then
|
|
575
|
+
it prints also the log probability and the time needed
|
|
576
|
+
for each step.
|
|
577
|
+
|
|
578
|
+
verbose_interval : int, default=10
|
|
579
|
+
Number of iteration done before the next print.
|
|
580
|
+
|
|
581
|
+
Attributes
|
|
582
|
+
----------
|
|
583
|
+
weights_ : array-like of shape (n_components,)
|
|
584
|
+
The weights of each mixture components.
|
|
585
|
+
|
|
586
|
+
means_ : array-like of shape (n_components, n_features)
|
|
587
|
+
The mean of each mixture component.
|
|
588
|
+
|
|
589
|
+
covariances_ : array-like
|
|
590
|
+
The covariance of each mixture component.
|
|
591
|
+
The shape depends on `covariance_type`::
|
|
592
|
+
|
|
593
|
+
(n_components,) if 'spherical',
|
|
594
|
+
(n_features, n_features) if 'tied',
|
|
595
|
+
(n_components, n_features) if 'diag',
|
|
596
|
+
(n_components, n_features, n_features) if 'full'
|
|
597
|
+
|
|
598
|
+
precisions_ : array-like
|
|
599
|
+
The precision matrices for each component in the mixture. A precision
|
|
600
|
+
matrix is the inverse of a covariance matrix. A covariance matrix is
|
|
601
|
+
symmetric positive definite so the mixture of Gaussian can be
|
|
602
|
+
equivalently parameterized by the precision matrices. Storing the
|
|
603
|
+
precision matrices instead of the covariance matrices makes it more
|
|
604
|
+
efficient to compute the log-likelihood of new samples at test time.
|
|
605
|
+
The shape depends on `covariance_type`::
|
|
606
|
+
|
|
607
|
+
(n_components,) if 'spherical',
|
|
608
|
+
(n_features, n_features) if 'tied',
|
|
609
|
+
(n_components, n_features) if 'diag',
|
|
610
|
+
(n_components, n_features, n_features) if 'full'
|
|
611
|
+
|
|
612
|
+
precisions_cholesky_ : array-like
|
|
613
|
+
The cholesky decomposition of the precision matrices of each mixture
|
|
614
|
+
component. A precision matrix is the inverse of a covariance matrix.
|
|
615
|
+
A covariance matrix is symmetric positive definite so the mixture of
|
|
616
|
+
Gaussian can be equivalently parameterized by the precision matrices.
|
|
617
|
+
Storing the precision matrices instead of the covariance matrices makes
|
|
618
|
+
it more efficient to compute the log-likelihood of new samples at test
|
|
619
|
+
time. The shape depends on `covariance_type`::
|
|
620
|
+
|
|
621
|
+
(n_components,) if 'spherical',
|
|
622
|
+
(n_features, n_features) if 'tied',
|
|
623
|
+
(n_components, n_features) if 'diag',
|
|
624
|
+
(n_components, n_features, n_features) if 'full'
|
|
625
|
+
|
|
626
|
+
converged_ : bool
|
|
627
|
+
True when convergence was reached in fit(), False otherwise.
|
|
628
|
+
|
|
629
|
+
n_iter_ : int
|
|
630
|
+
Number of step used by the best fit of EM to reach the convergence.
|
|
631
|
+
|
|
632
|
+
lower_bound_ : float
|
|
633
|
+
Lower bound value on the log-likelihood (of the training data with
|
|
634
|
+
respect to the model) of the best fit of EM.
|
|
635
|
+
|
|
636
|
+
Examples
|
|
637
|
+
--------
|
|
638
|
+
>>> import numpy as np
|
|
639
|
+
>>> from sklearn.mixture import GaussianMixture
|
|
640
|
+
>>> X = np.array([[1, 2], [1, 4], [1, 0], [10, 2], [10, 4], [10, 0]])
|
|
641
|
+
>>> gm = GaussianMixture(n_components=2, random_state=0).fit(X)
|
|
642
|
+
>>> gm.means_
|
|
643
|
+
array([[10., 2.],
|
|
644
|
+
[ 1., 2.]])
|
|
645
|
+
>>> gm.predict([[0, 0], [12, 3]])
|
|
646
|
+
array([1, 0])
|
|
647
|
+
|
|
648
|
+
See Also
|
|
649
|
+
--------
|
|
650
|
+
BayesianGaussianMixture : Gaussian mixture model fit with a variational
|
|
651
|
+
inference.
|
|
652
|
+
"""
|
|
653
|
+
@_deprecate_positional_args
|
|
654
|
+
def __init__(self, n_components=1, *, covariance_type='full', tol=1e-3,
|
|
655
|
+
reg_covar=1e-6, max_iter=100, n_init=1, init_params='kmeans',
|
|
656
|
+
weights_init=None, means_init=None, precisions_init=None, centers_init=None,
|
|
657
|
+
random_state=None, warm_start=False,
|
|
658
|
+
station_locs=None, phase_type=None, phase_weight=None,
|
|
659
|
+
vel={"p":6.0, "s":6.0/1.75}, eikonal=None,
|
|
660
|
+
dummy_comp=False, dummy_prob=0.01, dummy_quantile=0.1,
|
|
661
|
+
loss_type="l1", bounds=None, max_covar=None,
|
|
662
|
+
verbose=0, verbose_interval=10):
|
|
663
|
+
super().__init__(
|
|
664
|
+
n_components=n_components, tol=tol, reg_covar=reg_covar,
|
|
665
|
+
max_iter=max_iter, n_init=n_init, init_params=init_params,
|
|
666
|
+
random_state=random_state, warm_start=warm_start,
|
|
667
|
+
dummy_comp=dummy_comp, dummy_prob=dummy_prob, dummy_quantile=dummy_quantile,
|
|
668
|
+
verbose=verbose, verbose_interval=verbose_interval)
|
|
669
|
+
|
|
670
|
+
self.covariance_type = covariance_type
|
|
671
|
+
self.weights_init = weights_init
|
|
672
|
+
self.means_init = means_init
|
|
673
|
+
self.precisions_init = precisions_init
|
|
674
|
+
self.centers_init = centers_init
|
|
675
|
+
if station_locs is None:
|
|
676
|
+
raise("Missing: station_locs")
|
|
677
|
+
if phase_type is None:
|
|
678
|
+
raise("Missing: phase_type")
|
|
679
|
+
if phase_weight is None:
|
|
680
|
+
phase_weight = np.ones([len(phase_type),1])
|
|
681
|
+
self.vel = vel
|
|
682
|
+
self.station_locs = station_locs
|
|
683
|
+
self.phase_type = np.squeeze(phase_type)
|
|
684
|
+
self.phase_weight = np.squeeze(phase_weight)
|
|
685
|
+
self.loss_type = loss_type
|
|
686
|
+
self.bounds = bounds
|
|
687
|
+
self.max_covar = max_covar
|
|
688
|
+
self.eikonal = eikonal
|
|
689
|
+
|
|
690
|
+
def _check_parameters(self, X):
|
|
691
|
+
"""Check the Gaussian mixture parameters are well defined."""
|
|
692
|
+
n_samples, n_features = X.shape
|
|
693
|
+
if self.covariance_type not in ['spherical', 'tied', 'diag', 'full']:
|
|
694
|
+
raise ValueError("Invalid value for 'covariance_type': %s "
|
|
695
|
+
"'covariance_type' should be in "
|
|
696
|
+
"['spherical', 'tied', 'diag', 'full']"
|
|
697
|
+
% self.covariance_type)
|
|
698
|
+
|
|
699
|
+
if self.weights_init is not None:
|
|
700
|
+
self.weights_init = _check_weights(self.weights_init,
|
|
701
|
+
self.n_components)
|
|
702
|
+
|
|
703
|
+
if self.means_init is not None:
|
|
704
|
+
self.means_init = _check_means(self.means_init,
|
|
705
|
+
self.n_components, n_features)
|
|
706
|
+
|
|
707
|
+
if self.precisions_init is not None:
|
|
708
|
+
self.precisions_init = _check_precisions(self.precisions_init,
|
|
709
|
+
self.covariance_type,
|
|
710
|
+
self.n_components,
|
|
711
|
+
n_features)
|
|
712
|
+
|
|
713
|
+
if n_features > 2:
|
|
714
|
+
raise ValueError(f"n_features = {n_features} > 2! Only support 2 features (time, amplitude)")
|
|
715
|
+
assert(self.covariance_type=='full')
|
|
716
|
+
assert(self.station_locs.shape[0] == n_samples)
|
|
717
|
+
assert(self.loss_type in ["l1", "l2"])
|
|
718
|
+
_check_shape(self.phase_type, (n_samples, ), 'phase_type')
|
|
719
|
+
_check_shape(self.phase_weight, (n_samples, ), 'phase_type')
|
|
720
|
+
if self.init_params == "centers":
|
|
721
|
+
assert(self.centers_init is not None)
|
|
722
|
+
# if self.centers_init is not None:
|
|
723
|
+
# _check_shape(self.centers_init, (self.n_components, self.station_locs.shape[1] + n_features), 'centers_init')
|
|
724
|
+
|
|
725
|
+
|
|
726
|
+
def _initialize(self, X, resp):
|
|
727
|
+
"""Initialization of the Gaussian mixture parameters.
|
|
728
|
+
|
|
729
|
+
Parameters
|
|
730
|
+
----------
|
|
731
|
+
X : array-like of shape (n_samples, n_features)
|
|
732
|
+
|
|
733
|
+
resp : array-like of shape (n_samples, n_components)
|
|
734
|
+
"""
|
|
735
|
+
n_samples, _ = X.shape
|
|
736
|
+
|
|
737
|
+
weights, means, covariances, centers = _estimate_gaussian_parameters(
|
|
738
|
+
X, resp, self.reg_covar, self.covariance_type,
|
|
739
|
+
self.station_locs, self.phase_type, vel=self.vel, loss_type=self.loss_type,
|
|
740
|
+
centers_prev=self.centers_init, bounds=self.bounds, eikonal=self.eikonal)
|
|
741
|
+
weights /= n_samples
|
|
742
|
+
|
|
743
|
+
# self.weights_ = (weights if self.weights_init is None else self.weights_init)
|
|
744
|
+
# self.means_ = (means if self.means_init is None else self.means_init)
|
|
745
|
+
# self.centers_ = (centers if self.centers_init is None else self.centers_init)
|
|
746
|
+
self.weights_ = weights
|
|
747
|
+
self.means_ = means
|
|
748
|
+
self.centers_ = centers
|
|
749
|
+
|
|
750
|
+
if self.precisions_init is None:
|
|
751
|
+
self.covariances_ = covariances
|
|
752
|
+
self.precisions_cholesky_ = _compute_precision_cholesky(
|
|
753
|
+
covariances, self.covariance_type, self.max_covar)
|
|
754
|
+
elif self.covariance_type == 'full':
|
|
755
|
+
self.precisions_cholesky_ = np.array(
|
|
756
|
+
[linalg.cholesky(prec_init, lower=True)
|
|
757
|
+
for prec_init in self.precisions_init])
|
|
758
|
+
elif self.covariance_type == 'tied':
|
|
759
|
+
self.precisions_cholesky_ = linalg.cholesky(self.precisions_init,
|
|
760
|
+
lower=True)
|
|
761
|
+
else:
|
|
762
|
+
self.precisions_cholesky_ = self.precisions_init
|
|
763
|
+
|
|
764
|
+
def _m_step(self, X, log_resp):
|
|
765
|
+
"""M step.
|
|
766
|
+
|
|
767
|
+
Parameters
|
|
768
|
+
----------
|
|
769
|
+
X : array-like of shape (n_samples, n_features)
|
|
770
|
+
|
|
771
|
+
log_resp : array-like of shape (n_samples, n_components)
|
|
772
|
+
Logarithm of the posterior probabilities (or responsibilities) of
|
|
773
|
+
the point of each sample in X.
|
|
774
|
+
"""
|
|
775
|
+
n_samples, _ = X.shape
|
|
776
|
+
self.weights_, self.means_, self.covariances_, self.centers_ = (
|
|
777
|
+
_estimate_gaussian_parameters(
|
|
778
|
+
X, np.exp(log_resp), self.reg_covar, self.covariance_type,
|
|
779
|
+
self.station_locs, self.phase_type, vel=self.vel, loss_type=self.loss_type,
|
|
780
|
+
centers_prev=self.centers_, bounds=self.bounds, eikonal=self.eikonal))
|
|
781
|
+
self.weights_ /= n_samples
|
|
782
|
+
self.precisions_cholesky_ = _compute_precision_cholesky(
|
|
783
|
+
self.covariances_, self.covariance_type, self.max_covar)
|
|
784
|
+
|
|
785
|
+
def _estimate_log_prob(self, X):
|
|
786
|
+
prob = _estimate_log_gaussian_prob(X, self.means_, self.precisions_cholesky_, self.covariance_type)
|
|
787
|
+
if self.dummy_comp:
|
|
788
|
+
# print(np.quantile(np.max(prob[:,:-1], axis=1), self.dummy_quantile), np.log(self.dummy_prob))
|
|
789
|
+
prob[:,-1] = min(np.quantile(np.max(prob[:,:-1], axis=1), self.dummy_quantile), np.log(self.dummy_prob))
|
|
790
|
+
return prob + np.log(self.phase_weight)[:,np.newaxis]
|
|
791
|
+
|
|
792
|
+
def _estimate_log_weights(self):
|
|
793
|
+
if self.dummy_comp:
|
|
794
|
+
score = 0.1 #1.0/len(self.weights_)
|
|
795
|
+
if self.weights_[-1] >= score:
|
|
796
|
+
self.weights_[:-1] /= np.sum(self.weights_[:-1]) / (1-score)
|
|
797
|
+
self.weights_[-1] = score
|
|
798
|
+
return np.log(self.weights_)
|
|
799
|
+
|
|
800
|
+
def _compute_lower_bound(self, _, log_prob_norm):
|
|
801
|
+
return log_prob_norm
|
|
802
|
+
|
|
803
|
+
def _get_parameters(self):
|
|
804
|
+
return (self.weights_, self.means_, self.covariances_,
|
|
805
|
+
self.precisions_cholesky_)
|
|
806
|
+
|
|
807
|
+
def _set_parameters(self, params):
|
|
808
|
+
(self.weights_, self.means_, self.covariances_,
|
|
809
|
+
self.precisions_cholesky_) = params
|
|
810
|
+
|
|
811
|
+
# Attributes computation
|
|
812
|
+
_, _, n_features = self.means_.shape
|
|
813
|
+
|
|
814
|
+
if self.covariance_type == 'full':
|
|
815
|
+
self.precisions_ = np.empty(self.precisions_cholesky_.shape)
|
|
816
|
+
for k, prec_chol in enumerate(self.precisions_cholesky_):
|
|
817
|
+
self.precisions_[k] = np.dot(prec_chol, prec_chol.T)
|
|
818
|
+
|
|
819
|
+
elif self.covariance_type == 'tied':
|
|
820
|
+
self.precisions_ = np.dot(self.precisions_cholesky_,
|
|
821
|
+
self.precisions_cholesky_.T)
|
|
822
|
+
else:
|
|
823
|
+
self.precisions_ = self.precisions_cholesky_ ** 2
|
|
824
|
+
|
|
825
|
+
def _n_parameters(self):
|
|
826
|
+
"""Return the number of free parameters in the model."""
|
|
827
|
+
_, _, n_features = self.means_.shape
|
|
828
|
+
if self.covariance_type == 'full':
|
|
829
|
+
cov_params = self.n_components * n_features * (n_features + 1) / 2.
|
|
830
|
+
elif self.covariance_type == 'diag':
|
|
831
|
+
cov_params = self.n_components * n_features
|
|
832
|
+
elif self.covariance_type == 'tied':
|
|
833
|
+
cov_params = n_features * (n_features + 1) / 2.
|
|
834
|
+
elif self.covariance_type == 'spherical':
|
|
835
|
+
cov_params = self.n_components
|
|
836
|
+
mean_params = n_features * self.n_components
|
|
837
|
+
return int(cov_params + mean_params + self.n_components - 1)
|
|
838
|
+
|
|
839
|
+
def bic(self, X):
|
|
840
|
+
"""Bayesian information criterion for the current model on the input X.
|
|
841
|
+
|
|
842
|
+
Parameters
|
|
843
|
+
----------
|
|
844
|
+
X : array of shape (n_samples, n_dimensions)
|
|
845
|
+
|
|
846
|
+
Returns
|
|
847
|
+
-------
|
|
848
|
+
bic : float
|
|
849
|
+
The lower the better.
|
|
850
|
+
"""
|
|
851
|
+
return (-2 * self.score(X) * X.shape[0] +
|
|
852
|
+
self._n_parameters() * np.log(X.shape[0]))
|
|
853
|
+
|
|
854
|
+
def aic(self, X):
|
|
855
|
+
"""Akaike information criterion for the current model on the input X.
|
|
856
|
+
|
|
857
|
+
Parameters
|
|
858
|
+
----------
|
|
859
|
+
X : array of shape (n_samples, n_dimensions)
|
|
860
|
+
|
|
861
|
+
Returns
|
|
862
|
+
-------
|
|
863
|
+
aic : float
|
|
864
|
+
The lower the better.
|
|
865
|
+
"""
|
|
866
|
+
return -2 * self.score(X) * X.shape[0] + 2 * self._n_parameters()
|