forked from lrjconan/deep_parsimonious
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathnn_cell_lib.py
547 lines (447 loc) · 23.9 KB
/
nn_cell_lib.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
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
"""
Basic cells of neural networks
Renjie Liao
"""
import numpy as np
import tensorflow as tf
from kmeans_update import kmeans_clustering
def weight_variable(shape, init_method=None, dtype=tf.float32, init_param=None, wd=None, name=None, trainable=True):
""" Initialize Weights
Input:
shape: list of int, shape of the weights
init_method: string, indicates initialization method
init_param: a dictionary,
init_val: if it is not None, it should be a tensor
wd: a float, weight decay
name:
trainable:
Output:
var: a TensorFlow Variable
"""
if init_method is None:
initializer = tf.zeros_initializer(shape, dtype=dtype)
elif init_method == 'normal':
initializer = tf.random_normal_initializer(
mean=init_param['mean'], stddev=init_param['stddev'], seed=1, dtype=dtype)
elif init_method == 'truncated_normal':
initializer = tf.truncated_normal_initializer(
mean=init_param['mean'], stddev=init_param['stddev'], seed=1, dtype=dtype)
elif init_method == 'uniform':
initializer = tf.random_uniform_initializer(
minval=init_param['minval'], maxval=init_param['maxval'], seed=1, dtype=dtype)
elif init_method == 'constant':
initializer = tf.constant_initializer(
value=init_param['val'], dtype=dtype)
else:
raise ValueError('Non supported initialization method!')
var = tf.Variable(initializer(shape), name=name, trainable=trainable)
if wd:
weight_decay = tf.mul(tf.nn.l2_loss(var), wd, name='weight_decay')
tf.add_to_collection('weight_decay', weight_decay)
return var
class MLP(object):
""" Multi Layer Perceptron (MLP)
Note: the number of layers is N
Input:
dims: a list of N+1 int, number of hidden units (last one is the input dimension)
activation: a list of N activation function names
add_bias: a boolean, indicates whether adding bias or not
wd: a float, weight decay
init_weights: a list of dictionaries of tensors, a dictionary has keys ['w', 'b'] for one layer
model: a dictionary, contains all variables for future use, e.g., debug
scope: tf scope of the model
Output:
a function which outputs a list of N tensors, each is the hidden activation of one layer
"""
def __init__(self, dims, activation=None, add_bias=True, wd=None, init_weights=None, init_std=None, scope='MLP'):
num_layer = len(dims) - 1
self.num_layer = num_layer
self.w = [None] * num_layer
self.b = [None] * num_layer
self.act_func = [None] * num_layer
self.dims = dims
self.activation = activation
self.add_bias = add_bias
self.wd = wd
self.init_weights = init_weights
self.init_std = init_std
self.scope = scope
# initialize variables
with tf.variable_scope(scope):
for ii in xrange(num_layer):
with tf.variable_scope('layer_{}'.format(ii)):
dim_in = dims[ii - 1]
dim_out = dims[ii]
if init_weights and init_weights[ii] is not None:
self.w[ii] = init_weights[ii]['w']
else:
self.w[ii] = weight_variable([dim_in, dim_out], init_method='truncated_normal', init_param={
'mean': 0.0, 'stddev': init_std[ii]}, wd=wd, name='w')
print 'MLP weight size in layer {}: {}'.format(ii, [dim_in, dim_out])
if add_bias:
if init_weights and init_weights[ii] is not None:
self.b[ii] = init_weights[ii]['b']
else:
self.b[ii] = weight_variable([dim_out], init_method='constant', init_param={
'val': 0.0}, wd=wd, name='b')
print 'MLP bias size in layer {}: {}'.format(ii, dim_out)
if activation and activation[ii] is not None:
if activation[ii] == 'relu':
self.act_func[ii] = tf.nn.relu
elif activation[ii] == 'sigmoid':
self.act_func[ii] = tf.sigmoid
elif activation[ii] == 'tanh':
self.act_func[ii] = tf.tanh
else:
raise ValueError('Non supported activation method!')
print 'MLP activate function in layer {}: {}'.format(ii, activation[ii])
def run(self, x):
h = [None] * self.num_layer
with tf.variable_scope(self.scope):
for ii in xrange(self.num_layer):
with tf.variable_scope('layer_{}'.format(ii)):
if ii == 0:
input_vec = x
else:
input_vec = h[ii - 1]
h[ii] = tf.matmul(input_vec, self.w[ii])
if self.add_bias:
h[ii] += self.b[ii]
if self.act_func and self.act_func[ii] is not None:
h[ii] = self.act_func[ii](h[ii])
return h
class CNN(object):
""" Convolutional Neural Network (CNN)
Note: the number of layers is N
each layer looks like 'conv + [relu] + [pool]', [] means optional
Input:
conv_filters: a dictionary
key 'filter_shape': a list of N lists, each is 4-d list (H, W, C_in, C_out) specify the shape of a filter
key 'filter_stride': a list of N lists, each is 4-d list (B, H, W, C) specify the stride of filters in one layer
pooling: a dictionary
key 'func_name': a list of N strings, each is name of pooling method ['max', 'avg']
key 'pool_size': a list of N lists, each is 4-d list specify the size of pooling in one layer
key 'pool_stride': a list of N lists, each is 4-d list specify the stride of pooling in one layer
activation: a list of N activation function names
add_bias: a boolean, indicates whether adding bias or not
wd: a float, weight decay
init_weights: a list of dictionaries, each dict has keys ['w', 'b'] for [weight, bias]
model: a dictionary, contains all variables
scope: tf scope of the model
Output:
a function which outputs a list of N tensors, each is the feature map of one layer
"""
def __init__(self, conv_filters, pooling, activation=None, add_bias=True, wd=None, init_std=None, init_weights=None, scope='CNN'):
num_layer = len(conv_filters['filter_shape'])
self.num_layer = num_layer
self.w = [None] * num_layer
self.b = [None] * num_layer
self.pool_func = [None] * num_layer
self.act_func = [None] * num_layer
self.conv_filters = conv_filters
self.pooling = pooling
self.add_bias = add_bias
self.init_std = init_std
self.init_weights = init_weights
self.scope = scope
print 'CNN: {}'.format(scope)
print 'Activation: {}'.format(activation)
with tf.variable_scope(scope):
for ii in xrange(num_layer):
with tf.variable_scope('layer_{}'.format(ii)):
if init_weights and init_weights[ii] is not None:
self.w[ii] = init_weights[ii]['w']
else:
self.w[ii] = weight_variable(conv_filters['filter_shape'][ii], init_method='truncated_normal', init_param={
'mean': 0.0, 'stddev': init_std[ii]}, wd=wd, name='w')
print 'CNN filter size of layer {}: {}'.format(ii, conv_filters['filter_shape'][ii])
if add_bias:
if init_weights and init_weights[ii] is not None:
self.b[ii] = init_weights[ii]['b']
else:
self.b[ii] = weight_variable([conv_filters['filter_shape'][ii][3]], init_method='constant', init_param={
'val': 0}, wd=wd, name='b')
print 'CNN bias size in layer {}: {}'.format(ii, conv_filters['filter_shape'][ii][3])
if pooling['func_name'] and pooling['func_name'][ii] is not None:
if pooling['func_name'][ii] == 'max':
self.pool_func[ii] = tf.nn.max_pool
elif pooling['func_name'][ii] == 'avg':
self.pool_func[ii] = tf.nn.avg_pool
else:
raise ValueError('Non supported pooling method!')
if activation and activation[ii] is not None:
if activation[ii] == 'relu':
self.act_func[ii] = tf.nn.relu
elif activation[ii] == 'sigmoid':
self.act_func[ii] = tf.sigmoid
elif activation[ii] == 'tanh':
self.act_func[ii] = tf.tanh
else:
raise ValueError('Non supported activation method!')
def run(self, x):
""" x must be of size [B H W C] """
h = [None] * self.num_layer
with tf.variable_scope(self.scope):
for ii in xrange(self.num_layer):
if ii == 0:
input_vec = x
else:
input_vec = h[ii - 1]
h[ii] = tf.nn.conv2d(input_vec, self.w[ii], self.conv_filters[
'filter_stride'][ii], padding='SAME')
if self.add_bias:
h[ii] += self.b[ii]
if self.act_func[ii] is not None:
h[ii] = self.act_func[ii](h[ii])
if self.pool_func[ii] is not None:
h[ii] = self.pool_func[ii](h[ii], ksize=self.pooling['pool_size'][
ii], strides=self.pooling['pool_stride'][ii], padding='SAME')
return h
class CNN_cluster(object):
""" Convolutional Neural Network (CNN) with Clustering
Note: the number of layers is N
each layer looks like 'conv + [relu] + [pool]', [] means optional
Input:
conv_filters: a dictionary
key 'filter_shape': a list of N lists, each is 4-d list (H, W, C_in, C_out) specify the shape of a filter
key 'filter_stride': a list of N lists, each is 4-d list (B, H, W, C) specify the stride of filters in one layer
pooling: a dictionary
key 'func_name': a list of N strings, each is name of pooling method ['max', 'avg']
key 'pool_size': a list of N lists, each is 4-d list specify the size of pooling in one layer
key 'pool_stride': a list of N lists, each is 4-d list specify the stride of pooling in one layer
clustering_type: list of string, size N, {'sample', 'spatial', 'channel'}
clustering_shape: list of lists, size M X D, M = number of clusters, D = dimension of cluster
activation: a list of N activation function names
add_bias: a boolean, indicates whether adding bias or not
wd: a float, weight decay
init_weights: a list of dictionaries, each dict has keys ['w', 'b'] for [weight, bias]
model: a dictionary, contains all variables
scope: tf scope of the model
Output:
a function which outputs a list of N tensors, each is the feature map of one layer
"""
def __init__(self, conv_filters, pooling, clustering_type, clustering_shape, alpha, num_cluster, activation=None, add_bias=True, wd=None, init_std=None, init_weights=None, scope='CNN_cluster'):
num_layer = len(conv_filters['filter_shape'])
self.num_layer = num_layer
self.w = [None] * num_layer
self.b = [None] * num_layer
self.pool_func = [None] * num_layer
self.act_func = [None] * num_layer
self.cluster_center = [None] * num_layer
self.cluster_label = [None] * num_layer
self.add_bias = add_bias
self.scope = scope
self.conv_filters = conv_filters
self.pooling = pooling
self.clustering_type = clustering_type
self.clustering_shape = clustering_shape
self.alpha = alpha
self.num_cluster = num_cluster
print 'CNN: {}'.format(scope)
print 'Activation: {}'.format(activation)
with tf.variable_scope(scope):
for ii in xrange(num_layer):
with tf.variable_scope('layer_{}'.format(ii)):
if init_weights and init_weights[ii] is not None:
self.w[ii] = init_weights[ii]['w']
else:
self.w[ii] = weight_variable(conv_filters['filter_shape'][ii], init_method='truncated_normal', init_param={
'mean': 0.0, 'stddev': init_std[ii]}, wd=wd, name='w')
print 'CNN filter size in layer {}: {}'.format(ii, conv_filters['filter_shape'][ii])
if clustering_shape[ii]:
self.cluster_center[ii] = weight_variable(
[num_cluster[ii], clustering_shape[ii][1]],
init_method='truncated_normal',
init_param={'mean': 0.0, 'stddev': init_std[ii]},
name='cluster_center', trainable=False)
if clustering_shape[ii][0] < num_cluster[ii]:
random_init_label = np.random.choice(
num_cluster[ii], clustering_shape[ii][0], replace=False)
else:
random_init_label = np.concatenate([np.random.permutation(num_cluster[ii]), np.random.choice(
num_cluster[ii], clustering_shape[ii][0] - num_cluster[ii])])
self.cluster_label[ii] = tf.Variable(
random_init_label, name='cluster_label', trainable=False, dtype=tf.int64)
if add_bias:
if init_weights and init_weights[ii] is not None:
self.b[ii] = init_weights[ii]['b']
else:
self.b[ii] = weight_variable([conv_filters['filter_shape'][ii][
3]], init_method='constant', init_param={'val': 0.0}, wd=wd, name='b')
print 'CNN filter bias in layer {}: {}'.format(ii, conv_filters['filter_shape'][ii][3])
if pooling['func_name'] and pooling['func_name'][ii] is not None:
if pooling['func_name'][ii] == 'max':
self.pool_func[ii] = tf.nn.max_pool
elif pooling['func_name'][ii] == 'avg':
self.pool_func[ii] = tf.nn.avg_pool
else:
raise ValueError('Unsupported pooling method!')
if activation and activation[ii] is not None:
if activation[ii] == 'relu':
self.act_func[ii] = tf.nn.relu
elif activation[ii] == 'sigmoid':
self.act_func[ii] = tf.sigmoid
elif activation[ii] == 'tanh':
self.act_func[ii] = tf.tanh
else:
raise ValueError('Unsupported activation method!')
def run(self, x, eta, idx_center=None, idx_sample=None):
""" x must be of size [B H W C] """
h = [None] * self.num_layer
embeddings = []
reg_ops = []
reset_ops = []
clustering_ops = []
with tf.variable_scope(self.scope):
for ii in xrange(self.num_layer):
if ii == 0:
input_vec = x
else:
input_vec = h[ii - 1]
h[ii] = tf.nn.conv2d(input_vec, self.w[ii], self.conv_filters[
'filter_stride'][ii], padding='SAME')
if self.add_bias:
h[ii] += self.b[ii]
if self.clustering_type[ii] == 'sample':
embedding = h[ii]
elif self.clustering_type[ii] == 'spatial':
embedding = h[ii]
elif self.clustering_type[ii] == 'channel':
embedding = tf.transpose(h[ii], [0, 3, 1, 2])
if self.clustering_shape[ii] is not None:
embedding = tf.reshape(
embedding, [-1, self.clustering_shape[ii][1]])
embeddings += [embedding]
clustering_ops += [kmeans_clustering(
embedding, self.cluster_center[ii],
self.cluster_label[ii], self.num_cluster[ii], eta)]
sample_center = tf.stop_gradient(
tf.gather(self.cluster_center[ii], self.cluster_label[ii]))
reg_ops += [tf.reduce_mean(
tf.square(embedding - sample_center)) * self.alpha[ii] / 2.0]
reset_ops += [tf.scatter_update(
self.cluster_center[ii], idx_center[ii],
tf.gather(embedding, idx_sample[ii]))]
if self.act_func[ii] is not None:
h[ii] = self.act_func[ii](h[ii])
if self.pool_func[ii] is not None:
h[ii] = self.pool_func[ii](
h[ii], ksize=self.pooling['pool_size'][ii],
strides=self.pooling['pool_stride'][ii], padding='SAME')
return h, embeddings, clustering_ops, reg_ops, reset_ops
class MLP_cluster(object):
""" Multi Layer Perceptron (MLP)
Note: the number of layers is N
Input:
dims: a list of N+1 int, number of hidden units (last one is the input dimension)
activation: a list of N activation function names
add_bias: a boolean, indicates whether adding bias or not
wd: a float, weight decay
init_weights: a list of dictionaries of tensors, a dictionary has keys ['w', 'b'] for one layer
model: a dictionary, contains all variables for future use, e.g., debug
scope: tf scope of the model
Output:
a function which outputs a list of N tensors, each is the hidden activation of one layer
"""
def __init__(self, dims, clustering_shape, alpha, num_cluster,
activation=None, add_bias=True, wd=None, init_weights=None,
init_std=None, scope='MLP'):
num_layer = len(dims) - 1
self.num_layer = num_layer
self.w = [None] * num_layer
self.b = [None] * num_layer
self.act_func = [None] * num_layer
self.cluster_center = [None] * num_layer
self.cluster_label = [None] * num_layer
self.dims = dims
self.activation = activation
self.add_bias = add_bias
self.wd = wd
self.init_weights = init_weights
self.init_std = init_std
self.clustering_shape = clustering_shape
self.alpha = alpha
self.num_cluster = num_cluster
self.scope = scope
# initialize variables
with tf.variable_scope(scope):
for ii in xrange(num_layer):
with tf.variable_scope('layer_{}'.format(ii)):
dim_in = dims[ii - 1]
dim_out = dims[ii]
if init_weights and init_weights[ii] is not None:
self.w[ii] = init_weights[ii]['w']
else:
self.w[ii] = weight_variable(
[dim_in, dim_out], init_method='truncated_normal',
init_param={'mean': 0.0, 'stddev': init_std[ii]},
wd=wd, name='w')
print 'MLP weight size in layer {}: {}'.format(
ii, [dim_in, dim_out])
if clustering_shape[ii]:
self.cluster_center[ii] = weight_variable(
[num_cluster[ii], clustering_shape[ii][1]],
init_method='truncated_normal',
init_param={'mean': 0.0, 'stddev': init_std[ii]},
name='cluster_center', trainable=False)
if clustering_shape[ii][0] < num_cluster[ii]:
random_init_label = np.random.choice(
num_cluster[ii], clustering_shape[ii][0],
replace=False)
else:
random_init_label = np.concatenate(
[np.random.permutation(num_cluster[ii]),
np.random.choice(
num_cluster[ii],
clustering_shape[ii][0] - num_cluster[ii])])
self.cluster_label[ii] = tf.Variable(
random_init_label, name='cluster_label',
trainable=False, dtype=tf.int64)
if add_bias:
if init_weights and init_weights[ii] is not None:
self.b[ii] = init_weights[ii]['b']
else:
self.b[ii] = weight_variable(
[dim_out], init_method='constant',
init_param={'val': 0.0}, wd=wd, name='b')
print 'MLP bias size in layer {}: {}'.format(ii, dim_out)
if activation and activation[ii] is not None:
if activation[ii] == 'relu':
self.act_func[ii] = tf.nn.relu
elif activation[ii] == 'sigmoid':
self.act_func[ii] = tf.sigmoid
elif activation[ii] == 'tanh':
self.act_func[ii] = tf.tanh
else:
raise ValueError('Non supported activation method!')
print 'MLP activate function in layer {}: {}'.format(ii, activation[ii])
def run(self, x, eta, idx_center=None, idx_sample=None):
h = [None] * self.num_layer
embeddings = []
reg_ops = []
reset_ops = []
clustering_ops = []
with tf.variable_scope(self.scope):
for ii in xrange(self.num_layer):
with tf.variable_scope('layer_{}'.format(ii)):
if ii == 0:
input_vec = x
else:
input_vec = h[ii - 1]
h[ii] = tf.matmul(input_vec, self.w[ii])
if self.add_bias:
h[ii] += self.b[ii]
if self.clustering_shape[ii] is not None:
embedding = h[ii]
embeddings += [embedding]
clustering_ops += [kmeans_clustering(embedding, self.cluster_center[
ii], self.cluster_label[ii], self.num_cluster[ii], eta)]
sample_center = tf.stop_gradient(
tf.gather(self.cluster_center[ii], self.cluster_label[ii]))
reg_ops += [tf.reduce_mean(
tf.square(embedding - sample_center)) * self.alpha[ii] / 2.0]
reset_ops += [tf.scatter_update(self.cluster_center[ii], idx_center[
ii], tf.gather(h[ii], idx_sample[ii]))]
if self.act_func and self.act_func[ii] is not None:
h[ii] = self.act_func[ii](h[ii])
return h, embeddings, clustering_ops, reg_ops, reset_ops