-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
autoencoder.py
223 lines (172 loc) · 6.02 KB
/
autoencoder.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
"""
Costs related to autoencoders.
"""
from functools import wraps
from theano.tensor.shared_randomstreams import RandomStreams
from theano import tensor
import theano.sparse
from pylearn2.costs.cost import Cost, DefaultDataSpecsMixin
class GSNFriendlyCost(DefaultDataSpecsMixin, Cost):
"""
A Cost that can be used to train the GSN.
"""
@staticmethod
def cost(target, output):
"""
The cost of returning `output` when the truth was `target`
Parameters
----------
target : Theano tensor
The ground truth
output : Theano tensor
The model's output
"""
raise NotImplementedError()
def expr(self, model, data, *args, **kwargs):
"""
The cost of reconstructing `data` using `model`.
Parameters
----------
model : a GSN
data : a batch of inputs to reconstruct.
args : evidently ignored?
kwargs : optional keyword arguments
For use with third party TrainingAlgorithms or FixedVarDescr
"""
self.get_data_specs(model)[0].validate(data)
X = data
return self.cost(X, model.reconstruct(X))
class MeanSquaredReconstructionError(GSNFriendlyCost):
"""
.. todo::
WRITEME
"""
@staticmethod
@wraps(GSNFriendlyCost.cost)
def cost(targets, outputs):
a = targets
b = outputs
return ((a - b) ** 2).sum(axis=1).mean()
class MeanBinaryCrossEntropy(GSNFriendlyCost):
"""
.. todo::
WRITEME
"""
@staticmethod
@wraps(GSNFriendlyCost.cost)
def cost(target, output):
return tensor.nnet.binary_crossentropy(output, target) \
.sum(axis=1).mean()
class SampledMeanBinaryCrossEntropy(DefaultDataSpecsMixin, Cost):
"""
.. todo::
WRITEME properly
CE cost that goes with sparse autoencoder with L1 regularization on
activations
For theory:
Y. Dauphin, X. Glorot, Y. Bengio. ICML2011
Large-Scale Learning of Embeddings with Reconstruction Sampling
Parameters
----------
L1 : WRITEME
ratio : WRITEME
"""
def __init__(self, L1, ratio):
self.random_stream = RandomStreams(seed=1)
self.L1 = L1
self.one_ratio = ratio
@wraps(Cost.expr)
def expr(self, model, data, ** kwargs):
self.get_data_specs(model)[0].validate(data)
X = data
# X is theano sparse
X_dense = theano.sparse.dense_from_sparse(X)
noise = self.random_stream.binomial(size=X_dense.shape, n=1,
prob=self.one_ratio, ndim=None)
# a random pattern that indicates to reconstruct all the 1s and some of
# the 0s in X
P = noise + X_dense
P = theano.tensor.switch(P > 0, 1, 0)
P = tensor.cast(P, theano.config.floatX)
# L1 penalty on activations
reg_units = theano.tensor.abs_(model.encode(X)).sum(axis=1).mean()
# penalty on weights, optional
# params = model.get_params()
# W = params[2]
# there is a numerical problem when using
# tensor.log(1 - model.reconstruct(X, P))
# Pascal fixed it.
before_activation = model.reconstruct_without_dec_acti(X, P)
cost = (1 * X_dense *
tensor.log(tensor.log(1 + tensor.exp(-1 * before_activation)))
+ (1 - X_dense) *
tensor.log(1 + tensor.log(1 + tensor.exp(before_activation))))
cost = (cost * P).sum(axis=1).mean()
cost = cost + self.L1 * reg_units
return cost
class SampledMeanSquaredReconstructionError(MeanSquaredReconstructionError):
"""
mse cost that goes with sparse autoencoder with L1 regularization on
activations
For theory:
Y. Dauphin, X. Glorot, Y. Bengio. ICML2011
Large-Scale Learning of Embeddings with Reconstruction Sampling
Parameters
----------
L1 : WRITEME
ratio : WRITEME
"""
def __init__(self, L1, ratio):
self.random_stream = RandomStreams(seed=1)
self.L1 = L1
self.ratio = ratio
@wraps(Cost.expr)
def expr(self, model, data, ** kwargs):
self.get_data_specs(model)[0].validate(data)
X = data
# X is theano sparse
X_dense = theano.sparse.dense_from_sparse(X)
noise = self.random_stream.binomial(size=X_dense.shape, n=1,
prob=self.ratio, ndim=None)
# a random pattern that indicates to reconstruct all the 1s and some of
# the 0s in X
P = noise + X_dense
P = theano.tensor.switch(P > 0, 1, 0)
P = tensor.cast(P, theano.config.floatX)
# L1 penalty on activations
L1_units = theano.tensor.abs_(model.encode(X)).sum(axis=1).mean()
# penalty on weights, optional
# params = model.get_params()
# W = params[2]
# L1_weights = theano.tensor.abs_(W).sum()
cost = ((model.reconstruct(X, P) - X_dense) ** 2)
cost = (cost * P).sum(axis=1).mean()
cost = cost + self.L1 * L1_units
return cost
class SparseActivation(DefaultDataSpecsMixin, Cost):
"""
Autoencoder sparse activation cost.
Regularize on KL divergence from desired average activation of each
hidden unit as described in Andrew Ng's CS294A Lecture Notes. See
http://www.stanford.edu/class/cs294a/sparseAutoencoder_2011new.pdf.
Parameters
----------
coeff : float
Coefficient for this regularization term in the objective
function.
p : float
Desired average activation of each hidden unit.
"""
def __init__(self, coeff, p):
self.coeff = coeff
self.p = p
@wraps(Cost.expr)
def expr(self, model, data, **kwargs):
X = data
p = self.p
p_hat = tensor.abs_(model.encode(X)).mean(axis=0)
kl = p * tensor.log(p / p_hat) + (1 - p) * \
tensor.log((1 - p) / (1 - p_hat))
penalty = self.coeff * kl.sum()
penalty.name = 'sparse_activation_penalty'
return penalty