-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathscikitRBM.py
450 lines (373 loc) · 15.2 KB
/
scikitRBM.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
"""Restricted Boltzmann Machine
"""
# Main author: Yann N. Dauphin <[email protected]>
# Author: Vlad Niculae
# Author: Gabriel Synnaeve
# License: BSD Style.
import time
import numpy as np
import heapq
from sklearn.base import BaseEstimator
from sklearn.base import TransformerMixin
from sklearn.externals.six.moves import xrange
from sklearn.utils import check_arrays
from sklearn.utils import check_random_state
from sklearn.utils import issparse
from sklearn.utils.extmath import safe_sparse_dot
from sklearn.utils.extmath import logistic_sigmoid
import amitgroup.plot as gr
class BernoulliRBM(BaseEstimator, TransformerMixin):
"""Bernoulli Restricted Boltzmann Machine (RBM).
A Restricted Boltzmann Machine with binary visible units and
binary hiddens. Parameters are estimated using Stochastic Maximum
Likelihood (SML), also known as Persistent Contrastive Divergence (PCD)
[2].
The time complexity of this implementation is ``O(d ** 2)`` assuming
d ~ n_features ~ n_components.
Parameters
----------
n_components : int, optional
Number of binary hidden units.
learning_rate : float, optional
The learning rate for weight updates. It is *highly* recommended
to tune this hyper-parameter. Reasonable values are in the
10**[0., -3.] range.
batch_size : int, optional
Number of examples per minibatch.
n_iter : int, optional
Number of iterations/sweeps over the training dataset to perform
during training.
verbose : int, optional
The verbosity level. Enabling it (with a non-zero value) will compute
the log-likelihood of each mini-batch and hence cause a runtime overhead
in the order of 10%.
random_state : integer or numpy.RandomState, optional
A random number generator instance to define the state of the
random permutations generator. If an integer is given, it fixes the
seed. Defaults to the global numpy random number generator.
Attributes
----------
`components_` : array-like, shape (n_components, n_features), optional
Weight matrix, where n_features in the number of visible
units and n_components is the number of hidden units.
`intercept_hidden_` : array-like, shape (n_components,), optional
Biases of the hidden units.
`intercept_visible_` : array-like, shape (n_features,), optional
Biases of the visible units.
Examples
--------
>>> import numpy as np
>>> from sklearn.neural_network import BernoulliRBM
>>> X = np.array([[0, 0, 0], [0, 1, 1], [1, 0, 1], [1, 1, 1]])
>>> model = BernoulliRBM(n_components=2)
>>> model.fit(X)
BernoulliRBM(batch_size=10, learning_rate=0.1, n_components=2, n_iter=10,
random_state=None, verbose=False)
References
----------
[1] Hinton, G. E., Osindero, S. and Teh, Y. A fast learning algorithm for
deep belief nets. Neural Computation 18, pp 1527-1554.
http://www.cs.toronto.edu/~hinton/absps/fastnc.pdf
[2] Tieleman, T. Training Restricted Boltzmann Machines using
Approximations to the Likelihood Gradient. International Conference
on Machine Learning (ICML) 2008
"""
def __init__(self, n_components=256, learning_rate=0.1, batch_size=10,
n_iter=10, verbose=False, random_state=None, getNum = 1):
self.getNum = getNum
self.n_components = n_components
self.learning_rate = learning_rate
self.batch_size = batch_size
self.n_iter = n_iter
self.verbose = verbose
self.random_state = random_state
def printOutWeight(self):
gr.images(1000 * self.components_.reshape(self.n_components,16,16),zero_to_one = False, vmin = -2, vmax = 2)
#gr.images(self.components_.reshape(self.n_components,16,16))
def gen_even_slices(self,n, n_packs, n_samples=None):
"""Generator to create n_packs slices going up to n.
Pass n_samples when the slices are to be used for sparse matrix indexing;
slicing off-the-end raises an exception, while it works for NumPy arrays.
Examples
--------
>>> from sklearn.utils import gen_even_slices
>>> list(gen_even_slices(10, 1))
[slice(0, 10, None)]
>>> list(gen_even_slices(10, 10)) #doctest: +ELLIPSIS
[slice(0, 1, None), slice(1, 2, None), ..., slice(9, 10, None)]
>>> list(gen_even_slices(10, 5)) #doctest: +ELLIPSIS
[slice(0, 2, None), slice(2, 4, None), ..., slice(8, 10, None)]
>>> list(gen_even_slices(10, 3))
[slice(0, 4, None), slice(4, 7, None), slice(7, 10, None)]
"""
start = 0
for pack_num in range(n_packs):
this_n = n // n_packs
if pack_num < n % n_packs:
this_n += 1
if this_n > 0:
end = start + this_n
if n_samples is not None:
end = min(n_samples, end)
yield slice(start, end, None)
start = end
def transform(self, X):
"""Compute the hidden layer activation probabilities, P(h=1|v=X).
Parameters
----------
X : {array-like, sparse matrix} shape (n_samples, n_features)
The data to be transformed.
Returns
-------
h : array, shape (n_samples, n_components)
Latent representations of the data.
"""
X, = check_arrays(X, sparse_format='csr', dtype=np.float)
return self._mean_hiddens(X)
def _mean_hiddens(self, v):
"""Computes the probabilities P(h=1|v).
Parameters
----------
v : array-like, shape (n_samples, n_features)
Values of the visible layer.
Returns
-------
h : array-like, shape (n_samples, n_components)
Corresponding mean field values for the hidden layer.
"""
return logistic_sigmoid(safe_sparse_dot(v, self.components_.T)
+ self.intercept_hidden_)
def _sample_hiddens(self, v, rng):
"""Sample from the distribution P(h|v).
Parameters
----------
v : array-like, shape (n_samples, n_features)
Values of the visible layer to sample from.
rng : RandomState
Random number generator to use.
Returns
-------
h : array-like, shape (n_samples, n_components)
Values of the hidden layer.
"""
p = self._mean_hiddens(v)
p[rng.uniform(size=p.shape) < p] = 1.
return np.floor(p, p)
def _sample_hiddens_part(self,v,rng):
"""Sample from the distribution P(h|v).
Parameters
----------
v: array-like, shape(n_samples, n_features)
Values of the visible layer to sample from.
rng: RandomState
Random number generator to use.
Returns
-----
h : array-like, shape (n_samples, n_components)
Values of the hidden layer.
"""
p = self._mean_hiddens(v)
return self._sample_hiddens_winnerTakeAll(p,rng)
def winner_take_all(self,proArray):
newArray = np.zeros(proArray.shape)
newArray = proArray
newArray = newArray/(sum(newArray))
# vote = numpy.random.multinomial(newArray.shape[0],newArray,1)
#vote = np.random.multinomial(newArray.shape[0],newArray,1)[0]
#print np.max(vote)
# getNum = self.n_components/10
sortedIndex = np.argsort(newArray)[::-1]
getNum = self.getNum
#print(getNum)
winner = np.zeros(proArray.shape[0])
winnerIndex = sortedIndex[:getNum]
winner[winnerIndex] = 1
#print winner
return winner.flatten()
def _sample_hiddens_winnerTakeAll(self, h_pos_mean, rng):
"""Sample from the distribution P(h|v).
Parameters
----------
v : array-like, shape (n_samples, n_features)
Values of the visible layer to sample from.
rng : RandomState
Random number generator to use.
Returns
-------
h : array-like, shape (n_samples, n_components)
Values of the hidden layer.
"""
p = h_pos_mean
newP = np.zeros(p.shape)
winner = map(self.winner_take_all,p)
winner = np.asarray(winner)
#print winner.shape
return winner
def _sample_visibles(self, h, rng):
"""Sample from the distribution P(v|h).
Parameters
----------
h : array-like, shape (n_samples, n_components)
Values of the hidden layer to sample from.
rng : RandomState
Random number generator to use.
Returns
-------
v : array-like, shape (n_samples, n_features)
Values of the visible layer.
"""
p = logistic_sigmoid(np.dot(h, self.components_)
+ self.intercept_visible_)
p[rng.uniform(size=p.shape) < p] = 1.
return np.floor(p, p)
def _free_energy(self, v):
"""Computes the free energy F(v) = - log sum_h exp(-E(v,h)).
Parameters
----------
v : array-like, shape (n_samples, n_features)
Values of the visible layer.
Returns
-------
free_energy : array-like, shape (n_samples,)
The value of the free energy.
"""
#print safe_sparse_dot(v, self.components_.T)
#print self.intercept_hidden_
return (- safe_sparse_dot(v, self.intercept_visible_)
- np.log(1. + np.exp(safe_sparse_dot(v, self.components_.T)
+ self.intercept_hidden_)).sum(axis=1))
def gibbs(self, v):
"""Perform one Gibbs sampling step.
Parameters
----------
v : array-like, shape (n_samples, n_features)
Values of the visible layer to start from.
Returns
-------
v_new : array-like, shape (n_samples, n_features)
Values of the visible layer after one Gibbs step.
"""
rng = check_random_state(self.random_state)
h_ = self._sample_hiddens(v, rng)
v_ = self._sample_visibles(h_, rng)
return v_
def _fit(self, v_pos, rng,winnerTakeAll):
"""Inner fit for one mini-batch.
Adjust the parameters to maximize the likelihood of v using
Stochastic Maximum Likelihood (SML).
Parameters
----------
v_pos : array-like, shape (n_samples, n_features)
The data to use for training.
rng : RandomState
Random number generator to use for sampling.
Returns
-------
pseudo_likelihood : array-like, shape (n_samples,)
If verbose=True, pseudo-likelihood estimate for this batch.
"""
# h_pos = self._mean_hiddens(v_pos)
# h_pos = self._sample_hiddens_winnerTakeAll(v_pos,rng)
h_pos_mean_hidden = self._mean_hiddens(v_pos)
if(winnerTakeAll):
#print(sum(self._sample_hiddens_winnerTakeAll(v_pos,rng)))
h_pos = np.multiply(h_pos_mean_hidden, self._sample_hiddens_winnerTakeAll(h_pos_mean_hidden,rng))
else:
h_pos = h_pos_mean_hidden
v_neg = self._sample_visibles(self.h_samples_, rng)
# h_neg = self._mean_hiddens(v_neg)
if(winnerTakeAll):
h_neg_mean_hidden = self._mean_hiddens(v_neg)
h_neg_state = self._sample_hiddens_winnerTakeAll(h_neg_mean_hidden,rng)
h_neg = np.multiply(h_neg_mean_hidden,h_neg_state)
else:
h_neg = self._mean_hiddens(v_neg)
lr = float(self.learning_rate) / v_pos.shape[0]
update = safe_sparse_dot(v_pos.T, h_pos, dense_output=True).T
update -= np.dot(v_neg.T, h_neg).T
#gr.images(lr* update)
#print update.shape
#gr.images(1000 * update.reshape(15,16,16))
#print update
self.components_ += lr * update
self.intercept_hidden_ += lr * (h_pos.sum(axis=0) - h_neg.sum(axis=0))
self.intercept_visible_ += lr * (np.asarray(
v_pos.sum(axis=0)).squeeze() -
v_neg.sum(axis=0))
# h_neg[rng.uniform(size=h_neg.shape) < h_neg] = 1.0 # sample binomial
# self.h_samples_ = np.floor(h_neg, h_neg)
h_neg[rng.uniform(size=h_neg.shape) < h_neg] = 1.0
self.h_samples_ = np.floor(h_neg, h_neg)
if(winnerTakeAll):
self.h_samples_ = h_neg_state
#print np.sum(self.h_samples_,axis = 1)
if self.verbose:
return self.score_samples(v_pos)
def score_samples(self, v):
"""Compute the pseudo-likelihood of v.
Parameters
----------
v : {array-like, sparse matrix} shape (n_samples, n_features)
Values of the visible layer.
Returns
-------
pseudo_likelihood : array-like, shape (n_samples,)
Value of the pseudo-likelihood (proxy to likelihood).
print update"""
rng = check_random_state(self.random_state)
fe = self._free_energy(v)
if issparse(v):
v_ = v.toarray()
else:
v_ = v.copy()
i_ = rng.randint(0, v.shape[1], v.shape[0])
v_[np.arange(v.shape[0]), i_] = 1 - v_[np.arange(v.shape[0]), i_]
fe_ = self._free_energy(v_)
#print fe_
#print fe
return v.shape[1] * logistic_sigmoid(fe_ - fe, log=True)
def fit(self, X, winnerTakeAll,plList, y=None,):
"""Fit the model to the data X.
Parameters
----------
X : {array-like, sparse matrix} shape (n_samples, n_features)
Training data.
Returns
-------
self : BernoulliRBM
The fitted model.
"""
X, = check_arrays(X, sparse_format='csr', dtype=np.float)
n_samples = X.shape[0]
rng = check_random_state(self.random_state)
self.components_ = np.asarray(
rng.normal(0, 0.001, (self.n_components, X.shape[1])),
order='fortran')
self.intercept_hidden_ = np.zeros(self.n_components, )
self.intercept_visible_ = np.zeros(X.shape[1], )
self.h_samples_ = np.zeros((self.batch_size, self.n_components))
n_batches = int(np.ceil(float(n_samples) / self.batch_size))
batch_slices = list(self.gen_even_slices(n_batches * self.batch_size,n_batches, n_samples))
verbose = self.verbose
for iteration in xrange(self.n_iter):
pl = 0.
if verbose:
begin = time.time()
batch_index = 0
for batch_slice in batch_slices:
if(batch_index + 1 != n_batches - 1):
#next_batch = batch_slice
next_h_pos_mean_hidden = self._mean_hiddens(X[batch_index + 1])
pl_batch = self._fit(X[batch_slice], rng,winnerTakeAll)
if verbose:
pl += pl_batch.sum()
#self.printOutWeight()
batch_index = batch_index + 1
if verbose:
pl /= n_samples
end = time.time()
print("Iteration %d, pseudo-likelihood = %.2f, time = %.2fs"
% (iteration, pl, end - begin))
plList[iteration] = pl
#self.printOutWeight()
return self