-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathutils.py
More file actions
68 lines (48 loc) · 1.86 KB
/
Copy pathutils.py
File metadata and controls
68 lines (48 loc) · 1.86 KB
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
# Authors: Albert Thomas
# Alexandre Gramfort
# License: BSD (3-clause)
# Gaussian Mixture class inspired from scikit-learn GaussianMixture module to
# sample and compute density of a Gaussian mixture model.
import numpy as np
from scipy.stats import multivariate_normal
class GaussianMixture(object):
""" Gaussian mixture.
Parameters
----------
weights : array, shape (n_components, )
Weights of the Gaussian mixture components.
means : array, shape (n_components, n_features)
Means of the Gaussian mixture components.
covars : array, shape (n_components, n_features, n_features)
Covariances of the Gaussian mixture components.
random_state : int
Seed used by the random number generator.
"""
def __init__(self, weights, means, covars, random_state=42):
self.weights = weights
self.means = means
self.covars = covars
self.random_state = random_state
def sample(self, n_samples):
""" Generating samples from the Gaussian Mixture. """
weights = self.weights
means = self.means
covars = self.covars
random_state = self.random_state
rng = np.random.RandomState(random_state)
n_samples_comp = rng.multinomial(n_samples, weights)
X = np.vstack([
rng.multivariate_normal(mean, cov, int(sample))
for (mean, cov, sample) in zip(
means, covars, n_samples_comp)])
return X
def density(self, X):
""" Gaussian Mixture density of the samples X. """
weights = self.weights
means = self.means
covars = self.covars
n_samples, _ = X.shape
density = np.zeros(n_samples)
for (weight, mean, cov) in zip(weights, means, covars):
density += weight * multivariate_normal.pdf(X, mean, cov)
return density