-
Notifications
You must be signed in to change notification settings - Fork 119
/
Copy pathdpmixture.py
508 lines (398 loc) · 16.4 KB
/
dpmixture.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
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
import numpy as np
from scipy.special import psi, gammaln
from scipy.misc import logsumexp
from sklearn.base import BaseEstimator
from sklearn.utils.extmath import safe_sparse_dot
from sklearn.utils.validation import check_is_fitted
from scipy.sparse import isspmatrix
from sklearn.utils import check_array
def _e_log_beta(c0,d0,c,d):
''' Calculates expectation of log pdf of beta distributed parameter'''
log_C = gammaln(c0 + d0) - gammaln(c0) - gammaln(d0)
psi_cd = psi(c+d)
log_mu = (c0 - 1) * ( psi(c) - psi_cd )
log_i_mu = (d0 - 1) * ( psi(d) - psi_cd )
return np.sum(log_C + log_mu + log_i_mu)
def _gamma_entropy(c0,d0,c,d):
''' Calculates negtive entropy of gamma distribution'''
return c0*np.log(d0) - gammaln(c0) + (c0 - 1)*( psi(c) - np.log(d)) - d0*c/d
def _check_shape_sign(x,shape,shape_message, sign_message):
''' Checks shape and sign of input, raises error'''
if x.shape != shape:
raise ValueError(shape_message)
if np.sum( x < 0 ) > 0:
raise ValueError(sign_message)
def _get_classes(X):
'''Finds number of unique elements in matrix'''
if isspmatrix(X):
v = X.data
if len(v) < X.shape[0]*X.shape[1]:
v = np.hstack((v,np.zeros(1)))
V = np.unique(v)
else:
V = np.unique(X)
return V
class BernoulliMixture(object):
def _init_params(self, X):
'''
Initialise parameters of Bernoulli Mixture Model
'''
# check user defined parameters for prior, if not provided generate your own
shape = (X.shape[1], self.n_components)
shape_message = ('Parameters for prior of success probabilities should have shape '
'{0}').format(shape)
sign_message = 'Parameters of beta distribution can not be negative'
# parameter for success probs
if 'a' in self.init_params:
c= self.init_params['a']
_check_shape_sign(c,shape,shape_message,sign_message)
else:
c = np.random.random([X.shape[1],self.n_components]) * self.a
# parameters for fail probs
if 'b' in self.init_params:
d = self.init_params['b']
_check_shape_sign(d,shape,shape_message,sign_message)
else:
d = np.random.random([X.shape[1],self.n_components]) * self.b
c_init, d_init = np.copy(c), np.copy(d)
return {'c':c,'d':d,'c_init':c_init,'d_init':d_init}
def _check_X(self,X):
'''
Checks validity of inputs for Bernoulli Mixture Model
'''
X = check_array(X, accept_sparse = ['csr'])
classes_ = _get_classes(X)
n = len(classes_)
# check that there are only two categories in data
if n != 2:
raise ValueError(('There are {0} categorical values in data, '
'should be only 2'.format(n)))
# check that input data consists of only 0s and 1s
if not 0 in classes_ or not 1 in classes_:
raise ValueError(('Input data for Mixture of Bernoullis should consist'
'of zeros and ones, observed classes are {0}').format(classes_))
try:
check_is_fitted(self, 'means_')
except:
self.classes_ = classes_
return X
class PoissonMixture(object):
def _init_params(self,X):
shape = (X.shape[1], self.n_components)
shape_message = ('Parameters for prior of poisson should have shape'
'{0}').format(shape)
sign_message = 'Parameters of gamma distribution can not be negative'
# parameter for success probs
if 'c' in self.init_params:
c = self.init_params['c']
_check_shape_sign(c,shape,shape_message,sign_message)
else:
c = np.random.random([X.shape[1],self.n_components]) * self.c
# parameters for fail probs
if 'd' in self.init_params:
d = self.init_params['d']
_check_shape_sign(d,shape,shape_message,sign_message)
else:
d = np.random.random([X.shape[1],self.n_components]) * self.d
c_init, d_init = np.copy(c), np.copy(d)
return {'c':c,'d':d,'c_init':c_init,'d_init':d_init}
def _check_X(self,X):
X = check_array(X)
if np.sum(X < 0) > 0:
raise ValueError('Negative data points are not allowed in Poisson Mixture')
if np.sum( X - np.floor(X) ) > 0:
raise ValueError('Non integer data points are not allowed in Poisson Mixture')
return X
class DPExponentialMixture(BaseEstimator):
'''
Base class for Dirichlet Process Mixture (conjugate exponential family)
'''
def __init__(self,n_components,alpha,n_iter,tol,n_init):
self.n_components = n_components
self.alpha = alpha
self.n_iter = n_iter
self.tol = tol
self.scores_ = [np.NINF]
self.n_init = n_init
def _update_sbp(self, resps, Nk):
'''
Update parameters of stick breaking represenation of Dirichlet Process
'''
a = 1 + Nk
qz_cum = np.sum(resps,axis = 1, keepdims = True) - np.cumsum(resps,1)
b = self.alpha + np.sum(qz_cum,0)
return a,b
def _update_resps(self,log_pr_x,a,b):
'''
Update log of responsibilities
'''
psi_ab = psi(a+b)
psi_b_ab = psi(b) - psi_ab
pz_cum = np.cumsum(psi(b) - psi_ab) - psi_b_ab
log_resps = log_pr_x + psi(a) - psi_ab + pz_cum
log_like = np.copy(log_resps) # = E q_v,q_theta [ logP(X|Z,Theta) + logP(Z|V) ]
log_resps -= logsumexp(log_resps, axis = 1, keepdims = True)
resps = np.exp(log_resps) # = q(Z) - approximating dist of latent var
# compute part of lower bound that includes mixing latent variable
# E q_z [ E q_v,q_theta [ logP(X,Z|V,Theta) - log q(Z) ]]
delta_ll = np.sum(resps*log_like) - np.sum(resps*log_resps)
return np.exp(log_resps), delta_ll
def _fit_single_init(self,X):
'''
Fit Dirichlet Process Mixture Model for Exponential Family Distribution
'''
# initialise parameters
params = self._init_params(X)
# parameters of beta distribution in stick breaking process
a = np.ones(self.n_components)
b = self.alpha * np.ones(self.n_components)
a0,b0 = np.copy(a), np.copy(b)
scores = [np.NINF]
for i in xrange(self.n_iter):
log_pr_x = self._log_prob_x(X,params)
# compute q(Z) - approximation of posterior for latent variable
resps, delta_ll = self._update_resps(log_pr_x,a,b)
Nk = np.sum(resps,0)
# compute lower bound
e_logPV = _e_log_beta(a0,b0,a,b)
e_logQV = _e_log_beta(a,b,a,b)
# lower bound for difference between prior and approx dist of
# stick breaking process
lower_bound_sbp = e_logPV - e_logQV
last_score = self._lower_bound(X,delta_ll,params, lower_bound_sbp)
# check convergence
if last_score - scores[-1] < self.tol:
return a,b,params,scores
scores.append(last_score)
# compute q(V) - approximation of posterior for Stick Breaking Process
a,b = self._update_sbp(resps,Nk)
# compute q(PARAMS) - approximation of posterior for parameters of
# likelihood
params = self._update_params(X,Nk,resps,params)
return a,b,params,scores
def _fit(self,X):
'''
Fit parameters of mixture distribution
'''
X = self._check_X(X)
a_,b_,params_ = None,None,None
scores_ = [np.NINF]
for i in xrange(self.n_init):
a,b, params, scores = self._fit_single_init(X)
if scores_[-1] < scores[-1]:
a_, b_, params_, scores_ = a,b,params,scores
return a_, b_, params_, scores_
def predict_proba(self,X):
'''
Predict probability of cluster for test data
Parameters
----------
X : array-like, shape = [n_samples, n_features]
Data Matrix for test data
Returns
-------
probs : array, shape = (n_samples,n_components)
Probabilities of components membership
'''
check_is_fitted(self,'_model_params_')
X = self._check_X(X)
log_pr_x = self._log_prob_x(X,self._model_params_)
a,b = self._sbp_params_
probs = self._update_resps(log_pr_x,a,b)[0]
return probs
def predict(self,X):
'''
Predict cluster for test data
Parameters
----------
X : array-like, shape = [n_samples, n_features]
Data Matrix
Returns
-------
: array, shape = (n_samples,) component memberships
Cluster index
'''
return np.argmax(self.predict_proba(X),1)
def score(self,X):
'''
Computes the log probability under the model
Parameters
----------
X : array_like, shape (n_samples, n_features)
List of n_features-dimensional data points. Each row
corresponds to a single data point
Returns
-------
logprob: array with shape [n_samples,]
Log probabilities of each data point in X
'''
check_is_fitted(self,'_model_params_')
pass
# abstract methods that need to be implemented in subclass
def _log_prob_x(self,X,params):
raise NotImplementedError
def _update_params(self, X, Nk, resps, params):
raise NotImplementedError
def _lower_bound(self,X,delta_ll):
raise NotImplementedError
class DPBMM(DPExponentialMixture, BernoulliMixture):
'''
Dirichlet Process Bernoulli Mixture Model
Parameters
----------
n_components : int
Number of mixture components
alpha: float, optional (DEFAULT = 0.1)
Concentration parameter for Dirichlet Process Prior
n_iter: int, optional (DEFAULT = 100)
Number of iterations
tol: float, optional (DEFAULT = 1e-3)
Convergence threshold (tolerance)
n_init: int, optional (DEFAULT = 3)
Number of reinitialisations (helps to avoid local minimum)
a: float, optional (DEFAULT = 1.)
Parameter of beta distribution in stick breaking process
b: float, optional (DEFAULT = 1.)
Parameter of beta distribution in stick breaking process
Attributes
----------
means_ : numpy array of size (n_features, n_components)
Mean success probabilities for each cluster
scores_: list of unknown size (depends on number of iterations)
Log of lower bound
'''
def __init__(self, n_components, alpha = 0.1, n_iter = 100, tol = 1e-3, n_init = 3,
init_params = None, a = 1, b = 1):
super(DPBMM,self).__init__(n_components,alpha,n_iter,tol,n_init)
if init_params is None:
init_params = {}
self.init_params = init_params
self.a = a
self.b = b
def _log_prob_x(self,X,params):
'''
Expectation of log p(X|Z,Theta) with respect to approximating
distribution of Theta
'''
c = params['c']
d = params['d']
psi_cd = psi(c+d)
x_log = safe_sparse_dot(X,(psi(c)-psi(d)))
log_probs = x_log + np.sum(psi(d)-psi_cd,axis=0,keepdims = True)
return log_probs
def _update_params(self, X, Nk, resps, params):
'''
Update parameters of prior distribution for Bernoulli Succes Probabilities
'''
XR = safe_sparse_dot(X.T,resps)
params['c'] = params['c_init'] + XR
params['d'] = params['d_init'] + (Nk - XR)
return params
def _lower_bound(self, X, delta_ll, params, lower_bound_sbp):
'''
Computes lower bound
'''
c0,d0,c,d = params['c_init'], params['d_init'], params['c'], params['d']
e_logPM = _e_log_beta(c0,d0,c,d)
e_logQM = _e_log_beta(c,d,c,d)
ll = delta_ll + lower_bound_sbp + e_logPM - e_logQM
return ll
def fit(self,X):
'''
Fit Dirichlet Process Bernoulli Mixture Model
Parameters
----------
X : array_like, shape (n_samples, n_features)
Count Data
Returns
-------
object: self
self
'''
X = self._check_X(X)
a_, b_, params_, self.scores_ = self._fit(X)
# parameters of stick breaking process
self._sbp_params_ = (a_,b_)
self._model_params_ = params_
self.means_ = params_['c'] / ( params_['c'] + params_['d'] )
return self
class DPPMM(DPExponentialMixture, PoissonMixture):
'''
Dirichlet Process Poisson Mixture Model
Parameters
----------
n_components : int
Number of mixture components
alpha: float, optional (DEFAULT = 0.1)
Concentration parameter for Dirichlet Process Prior
n_iter: int, optional (DEFAULT = 100)
Number of iterations
tol: float, optional (DEFAULT = 1e-3)
Convergence threshold (tolerance)
n_init: int, optional (DEFAULT = 3)
Number of reinitialisations (helps to avoid local minimum)
a: float, optional (DEFAULT = 1.)
Parameter of beta distribution in stick breaking process
b: float, optional (DEFAULT = 1.)
Parameter of beta distribution in stick breaking process
Attributes
----------
means_ : numpy array of size (n_features, n_components)
Mean success probabilities for each cluster
scores_: list of unknown size (depends on number of iterations)
Log of lower bound
'''
def __init__(self, n_components, alpha = 0.1, n_iter = 100, tol = 1e-3, n_init = 3,
init_params = None, c = 1, d = 1):
super(DPPMM,self).__init__(n_components,alpha,n_iter,tol,n_init)
if init_params is None:
init_params = {}
self.init_params = init_params
self.c = c # parameters of gamma prior
self.d = d
def _log_prob_x(self,X,params):
'''
Expectation of log p(X|Z,Theta) with respect to approximating
distribution of Theta
'''
c = params['c']
d = params['d']
log_probs = np.dot(X, psi(c) - np.log(d)) + np.sum(gammaln(X+1),1,keepdims = True)
log_probs -= np.sum(c/d,0)
return log_probs
def _update_params(self, X, Nk, resps, params):
'''
Update parameters of prior distribution for Bernoulli Succes Probabilities
'''
XR = np.dot(X.T,resps)
params['c'] = params['c_init'] + XR
params['d'] = params['d_init'] + Nk
return params
def _lower_bound(self, X, delta_ll, params, lower_bound_sbp):
'''
Computes lower bound
'''
c0,d0,c,d = params['c_init'], params['d_init'], params['c'], params['d']
e_logPLambda = np.sum(_gamma_entropy(c0,d0,c,d))
e_logQLambda = np.sum(_gamma_entropy(c,d,c,d))
ll = delta_ll + lower_bound_sbp + e_logPLambda - e_logQLambda
return ll
def fit(self,X):
'''
Fit Dirichlet Process Poisson Mixture Model
Parameters
----------
X : array_like, shape (n_samples, n_features)
Count Data
Returns
-------
object: self
self
'''
X = self._check_X(X)
a_, b_, params_, self.scores_ = self._fit(X)
# parameters of stick breaking process
self._sbp_params_ = (a_,b_)
self._model_params_ = params_
self.means_ = params_['c'] / params_['d']
return self