-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpretrain.py
261 lines (232 loc) · 9.58 KB
/
pretrain.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
from __future__ import division
from __future__ import print_function
import numpy as np
from scipy.optimize import fmin_l_bfgs_b as bfgs
from numba import autojit
def flow(params,*args):
"""MPF objective function for RBM. Used to pretrain DBM layers.
Parameters
----------
params : array-like, shape (n_weights+n_biasv+nbiash)
Weights (flattened), visible biases, and hidden biases.
*args : tuple or list or args
Expects eps which is coefficient for MPF and data which is a
vectors of visible states to learn on.
"""
eps = args[0]
data = args[1]
n_visible = args[2]
n_hidden = args[3]
n_data = data.shape[0]
num = n_visible*n_hidden
weights = params[:num].reshape((n_visible,n_hidden))
biasv = params[num:num+n_visible]
num += n_visible
biash = params[num:num+n_hidden]
sflow = np.sum(iterEnergy(weights,biasv,biash,data,n_visible))
#np.sum([np.exp(.5*(energyDiff(weights,biasv,biash,data,ii))) for ii in xrange(n_visible)])
k = eps*sflow/n_data
return k
@autojit
def iterEnergy(weights,biasv,biash,data,n_visible):
result = 0.
energy = -data.dot(biasv)-np.sum(np.log(1.+np.exp(biash+data.dot(weights))),axis=1)
for ii in xrange(n_visible):
flip = data.copy()
flip[:,ii] = 1.-flip[:,ii]
terms = biash+data.dot(weights)
termsBF = biash+flip.dot(weights)
logTermsBF = np.sum(np.log(1.+np.exp(termsBF)),axis=1)
result+= np.exp(.5*(energy-(-flip[:,ii]*biasv[ii]-logTermsBF)))
return result
def gradFlow(params,*args):
"""Gradient of MPF objective function for RBM. Used to pretrain DBM layers.
Parameters
----------
params : array-like, shape (n_units^2+2*n_units)
Weights (flattened), visible biases, and hidden biases.
*args : tuple or list or args
Expects eps which is coefficient for MPF and data which is a
vectors of visible states to learn on.
"""
eps = args[0]
data = args[1]
n_visible = args[2]
n_hidden = args[3]
n_data = data.shape[0]
num = n_visible*n_hidden
weights = params[:num].reshape((n_visible,n_hidden))
biasv = params[num:num+n_visible]
num += n_visible
biash = params[num:num+n_hidden]
dkdw,dkdbv,dkdbh = iterde(weights,biasv,biash,data,n_visible)
return .5*eps*np.concatenate((dkdw.ravel(),dkdbv,dkdbh))/n_data
@autojit
def iterde(weights,biasv,biash,data,n_visible):
dkdw = np.zeros_like(weights)
dkdbv = np.zeros_like(biasv)
dkdbh = np.zeros_like(biash)
energy = -data.dot(biasv)-np.sum(np.log(1.+np.exp(biash+data.dot(weights))),axis=1)
for ii in xrange(n_visible):
flip = data.copy()
flip[:,ii] = 1.-flip[:,ii]
terms = biash+data.dot(weights)
sig_terms = sigm(terms)
termsBF = biash+flip.dot(weights)
sig_termsBF = sigm(termsBF)
logTermsBF = np.sum(np.log(1.+np.exp(termsBF)),axis=1)
diffe = np.exp(.5*(energy-(-flip[:,ii]*biasv[ii]-logTermsBF)))
dkdw += data.T.dot(-sig_terms*diffe[:,np.newaxis])-flip.T.dot(-sig_termsBF*diffe[:,np.newaxis])
dkdbv[ii] += np.dot(1.-2.*data[:,ii],diffe)
dkdbh += diffe.dot(-sig_terms-(-sig_termsBF))
return (dkdw,dkdbv,dkdbh)
def sigm(x):
"""Sigmoid function
Parameters
----------
x : array-like
Array of elements to calculate sigmoid for.
"""
return 1./(1.+np.exp(-x))
class preRBM(object):
"""RBM object used to pretrain a DBM layer"""
def __init__(self,n_visible,n_hidden,layer,rng):
if layer == 'bottom':
self.n_visible = 2*n_visible
self.n_hidden = n_hidden
elif layer == 'middle':
self.n_visible = n_visible
self.n_hidden = n_hidden
elif layer == 'top':
self.n_visible = n_visible
self.n_hidden = 2*n_hidden
else:
raise ValueError
self.layer = layer
self.rng = rng
self.weights = rng.uniform(low=-4.*np.sqrt(6./(self.n_visible+self.n_hidden)),
high=4.*np.sqrt(6./(self.n_visible+self.n_hidden)),
size=(self.n_visible,self.n_hidden))
self.biasv = 0.*rng.uniform(low=-4.*np.sqrt(6./(self.n_visible+self.n_hidden)),
high=4.*np.sqrt(6./(self.n_visible+self.n_hidden)),
size=self.n_visible)
self.biash = 0.*rng.uniform(low=-4.*np.sqrt(6./(self.n_visible+self.n_hidden)),
high=4.*np.sqrt(6./(self.n_visible+self.n_hidden)),
size=self.n_hidden)
self.vw = 0.
self.vbv = 0.
self.vbh = 0.
self.constrainWeights()
def constrainWeights(self):
if self.layer == 'bottom':
num = int(self.n_visible/2)
weights = .5*(self.weights[:num]+self.weights[num:])
self.weights[:num] = weights
self.weights[num:] = weights
biasv = .5*(self.biasv[:num]+self.biasv[num:])
self.biasv[:num] = biasv
self.biasv[num:] = biasv
elif self.layer == 'top':
num = int(self.n_hidden/2)
weights = .5*(self.weights[:,:num]+self.weights[:,num:])
self.weights[:,:num] = weights
self.weights[:,num:] = weights
biash = .5*(self.biash[:num]+self.biash[num:])
self.biash[:num] = biash
self.biash[num:] = biash
def train(self,eps,data,nIter = None):
if nIter is None:
nIter = 15000
if self.layer == 'bottom':
states = np.tile(data,(1,2))
else:
states = data
params = np.concatenate((self.weights.ravel(),self.biasv,self.biash))
params,f,d = bfgs(flow,params,fprime=gradFlow,args=(eps,states,self.n_visible,self.n_hidden),iprint=0,maxiter = nIter)
num = self.n_visible*self.n_hidden
self.weights = params[:num].reshape(self.n_visible,self.n_hidden)
self.biasv = params[num:num+self.n_visible]
num += self.n_visible
self.biash = params[num:]
self.constrainWeights()
if self.layer == 'bottom':
weights = self.weights[:int(self.n_visible/2)]
biasv = self.biasv[:int(self.n_visible/2)]
biash = self.biash
elif self.layer == 'middle':
weights = self.weights/2.
biasv = self.biasv
biash = self.biash
elif self.layer == 'top':
weights = self.weights[:,:int(self.n_hidden/2)]
biasv = self.biasv
biash = self.biash[:int(self.n_hidden/2)]
else:
raise ValueError
return (weights,biasv,biash)
def trainStep(self,eps,data,steps,alpha):
if self.layer == 'bottom':
states = np.tile(data,(1,2))
else:
states = data
dkdw = np.zeros_like(self.weights)
dkdbv = np.zeros_like(self.biasv)
dkdbh = np.zeros_like(self.biash)
n_data = data.shape[0]
params = np.concatenate((self.weights.ravel(),self.biasv,self.biash))
for jj in xrange(steps):
energy = -data.dot(self.biasv)-np.sum(np.log(1.+np.exp(self.biash+data.dot(self.weights))),axis=1)
for ii in xrange(self.n_visible):
flip = data.copy()
flip[:,ii] = 1.-flip[:,ii]
terms = self.biash+data.dot(self.weights)
sig_terms = sigm(terms)
termsBF = self.biash+flip.dot(self.weights)
sig_termsBF = sigm(termsBF)
logTermsBF = np.sum(np.log(1.+np.exp(termsBF)),axis=1)
diffe = np.exp(.5*(energy-(-flip[:,ii]*self.biasv[ii]-logTermsBF)))
dkdw += data.T.dot(-sig_terms*diffe[:,np.newaxis])-flip.T.dot(-sig_termsBF*diffe[:,np.newaxis])
dkdbv[ii] += np.dot(1.-2.*data[:,ii],diffe)
dkdbh += diffe.dot(-sig_terms-(-sig_termsBF))
self.vw = alpha*self.vw-eps*dkdw/float(n_data)
self.weights += self.vw
self.vbv = alpha*self.vbv-eps*dkdbv/float(n_data)
self.biasv += self.vbv
self.vbh = alpha*self.vbh-eps*dkdbh/float(n_data)
self.biash += self.vbh
params = np.concatenate((self.weights.ravel(),self.biasv,self.biash))
self.constrainWeights()
if self.layer == 'bottom':
weights = self.weights[:int(self.n_visible/2)]
biasv = self.biasv[:int(self.n_visible/2)]
biash = self.biash
elif self.layer == 'middle':
weights = self.weights/2.
biasv = self.biasv
biash = self.biash
elif self.layer == 'top':
weights = self.weights[:,:int(self.n_hidden/2)]
biasv = self.biasv
biash = self.biash[:int(self.n_hidden/2)]
else:
raise ValueError
return (weights,biasv,biash)
def nextActivation(self,data,steps):
n_data = data.shape[0]
if self.layer == 'bottom':
n_units = self.n_hidden
weights = self.weights[:int(self.n_visible/2)]
biash = self.biash
elif self.layer == 'middle':
n_units = self.n_visible
weights = self.weights/2.
elif self.layer == 'top':
n_units = self.n_visible
weights = self.weights[:,:int(self.n_hidden/2)]
biash = self.biash[:int(self.n_hidden/2)]
else:
raise ValueError
hidden_state = rng.randn(n_data,n_units)
for ii in xrange(steps):
terms = np.tile(bias,(n_data,1))+data.dot(weights)
return sigm(terms)