forked from tensorlayer/TensorLayer
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcore.py
More file actions
1470 lines (1240 loc) · 54.4 KB
/
Copy pathcore.py
File metadata and controls
1470 lines (1240 loc) · 54.4 KB
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
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
import six
import time
from abc import ABCMeta, abstractmethod
import numpy as np
import tensorflow as tf
from tensorflow.python.util.deprecation import deprecated
from .. import _logging as logging
from .. import files, iterate, utils, visualize
from ..deprecation import deprecated_alias
__all__ = [
'LayersConfig',
'TF_GRAPHKEYS_VARIABLES',
'flatten_reshape',
'clear_layers_name',
'set_name_reuse',
'initialize_rnn_state',
'print_all_variables',
'get_variables_with_name',
'get_layers_with_name',
'list_remove_repeat',
'merge_networks',
'initialize_global_variables',
'Layer',
'InputLayer',
'OneHotInputLayer',
'Word2vecEmbeddingInputlayer',
'EmbeddingInputlayer',
'AverageEmbeddingInputlayer',
'DenseLayer',
'ReconLayer',
'DropoutLayer',
'GaussianNoiseLayer',
'DropconnectDenseLayer',
]
@six.add_metaclass(ABCMeta)
class LayersConfig(object):
tf_dtype = tf.float32 # TensorFlow DType
set_keep = {} # A dictionary for holding tf.placeholders
@abstractmethod
def __init__(self):
pass
try: # For TF12 and later
TF_GRAPHKEYS_VARIABLES = tf.GraphKeys.GLOBAL_VARIABLES
except Exception: # For TF11 and before
TF_GRAPHKEYS_VARIABLES = tf.GraphKeys.VARIABLES
def flatten_reshape(variable, name='flatten'):
"""Reshapes a high-dimension vector input.
[batch_size, mask_row, mask_col, n_mask] ---> [batch_size, mask_row x mask_col x n_mask]
Parameters
----------
variable : TensorFlow variable or tensor
The variable or tensor to be flatten.
name : str
A unique layer name.
Returns
-------
Tensor
Flatten Tensor
Examples
--------
>>> W_conv2 = weight_variable([5, 5, 100, 32]) # 64 features for each 5x5 patch
>>> b_conv2 = bias_variable([32])
>>> W_fc1 = weight_variable([7 * 7 * 32, 256])
>>> h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)
>>> h_pool2 = max_pool_2x2(h_conv2)
>>> h_pool2.get_shape()[:].as_list() = [batch_size, 7, 7, 32]
... [batch_size, mask_row, mask_col, n_mask]
>>> h_pool2_flat = tl.layers.flatten_reshape(h_pool2)
... [batch_size, mask_row * mask_col * n_mask]
>>> h_pool2_flat_drop = tf.nn.dropout(h_pool2_flat, keep_prob)
...
"""
dim = 1
for d in variable.get_shape()[1:].as_list():
dim *= d
return tf.reshape(variable, shape=[-1, dim], name=name)
@deprecated("2018-06-30", "TensorLayer relies on TensorFlow to check naming.")
def clear_layers_name():
logging.warning('this method is DEPRECATED and has no effect, please remove it from your code.')
@deprecated("2018-06-30", "TensorLayer relies on TensorFlow to check name reusing.")
def set_name_reuse(enable=True):
logging.warning('this method is DEPRECATED and has no effect, please remove it from your code.')
def initialize_rnn_state(state, feed_dict=None):
"""Returns the initialized RNN state.
The inputs are `LSTMStateTuple` or `State` of `RNNCells`, and an optional `feed_dict`.
Parameters
----------
state : RNN state.
The TensorFlow's RNN state.
feed_dict : dictionary
Initial RNN state; if None, returns zero state.
Returns
-------
RNN state
The TensorFlow's RNN state.
"""
try: # TF1.0
LSTMStateTuple = tf.contrib.rnn.LSTMStateTuple
except Exception:
LSTMStateTuple = tf.nn.rnn_cell.LSTMStateTuple
if isinstance(state, LSTMStateTuple):
c = state.c.eval(feed_dict=feed_dict)
h = state.h.eval(feed_dict=feed_dict)
return (c, h)
else:
new_state = state.eval(feed_dict=feed_dict)
return new_state
def print_all_variables(train_only=False):
"""Print information of trainable or all variables,
without ``tl.layers.initialize_global_variables(sess)``.
Parameters
----------
train_only : boolean
Whether print trainable variables only.
- If True, print the trainable variables.
- If False, print all variables.
"""
# tvar = tf.trainable_variables() if train_only else tf.all_variables()
if train_only:
t_vars = tf.trainable_variables()
logging.info(" [*] printing trainable variables")
else:
try: # TF1.0+
t_vars = tf.global_variables()
except Exception: # TF0.12
t_vars = tf.all_variables()
logging.info(" [*] printing global variables")
for idx, v in enumerate(t_vars):
logging.info(" var {:3}: {:15} {}".format(idx, str(v.get_shape()), v.name))
def get_variables_with_name(name=None, train_only=True, printable=False):
"""Get a list of TensorFlow variables by a given name scope.
Parameters
----------
name : str
Get the variables that contain this name.
train_only : boolean
If Ture, only get the trainable variables.
printable : boolean
If True, print the information of all variables.
Returns
-------
list of Tensor
A list of TensorFlow variables
Examples
--------
>>> dense_vars = tl.layers.get_variable_with_name('dense', True, True)
"""
if name is None:
raise Exception("please input a name")
logging.info(" [*] geting variables with %s" % name)
# tvar = tf.trainable_variables() if train_only else tf.all_variables()
if train_only:
t_vars = tf.trainable_variables()
else:
try: # TF1.0+
t_vars = tf.global_variables()
except Exception: # TF0.12
t_vars = tf.all_variables()
d_vars = [var for var in t_vars if name in var.name]
if printable:
for idx, v in enumerate(d_vars):
logging.info(" got {:3}: {:15} {}".format(idx, v.name, str(v.get_shape())))
return d_vars
def get_layers_with_name(net, name="", printable=False):
"""Get a list of layers' output in a network by a given name scope.
Parameters
-----------
net : :class:`Layer`
The last layer of the network.
name : str
Get the layers' output that contain this name.
printable : boolean
If True, print information of all the layers' output
Returns
--------
list of Tensor
A list of layers' output (TensorFlow tensor)
Examples
---------
>>> layers = tl.layers.get_layers_with_name(net, "CNN", True)
"""
logging.info(" [*] geting layers with %s" % name)
layers = []
i = 0
for layer in net.all_layers:
# logging.info(type(layer.name))
if name in layer.name:
layers.append(layer)
if printable:
logging.info(" got {:3}: {:15} {}".format(i, layer.name, str(layer.get_shape())))
i = i + 1
return layers
def list_remove_repeat(x):
"""Remove the repeated items in a list, and return the processed list.
You may need it to create merged layer like Concat, Elementwise and etc.
Parameters
----------
x : list
Input
Returns
-------
list
A list that after removing it's repeated items
Examples
-------
>>> l = [2, 3, 4, 2, 3]
>>> l = list_remove_repeat(l)
... [2, 3, 4]
"""
y = []
for i in x:
if not i in y:
y.append(i)
return y
def merge_networks(layers=None):
"""Merge all parameters, layers and dropout probabilities to a :class:`Layer`.
The output of return network is the first network in the list.
Parameters
----------
layers : list of :class:`Layer`
Merge all parameters, layers and dropout probabilities to the first layer in the list.
Returns
--------
:class:`Layer`
The network after merging all parameters, layers and dropout probabilities to the first network in the list.
Examples
---------
>>> n1 = ...
>>> n2 = ...
>>> n1 = tl.layers.merge_networks([n1, n2])
"""
if layers is None:
raise Exception("layers should be a list of TensorLayer's Layers.")
layer = layers[0]
all_params = []
all_layers = []
all_drop = {}
for l in layers:
all_params.extend(l.all_params)
all_layers.extend(l.all_layers)
all_drop.update(l.all_drop)
layer.all_params = list(all_params)
layer.all_layers = list(all_layers)
layer.all_drop = dict(all_drop)
layer.all_layers = list_remove_repeat(layer.all_layers)
layer.all_params = list_remove_repeat(layer.all_params)
return layer
def initialize_global_variables(sess):
"""Initialize the global variables of TensorFlow.
Run ``sess.run(tf.global_variables_initializer())`` for TF 0.12+ or
``sess.run(tf.initialize_all_variables())`` for TF 0.11.
Parameters
----------
sess : Session
TensorFlow session.
"""
assert sess is not None
# try: # TF12+
sess.run(tf.global_variables_initializer())
# except: # TF11
# sess.run(tf.initialize_all_variables())
class Layer(object):
"""The basic :class:`Layer` class represents a single layer of a neural network.
It should be subclassed when implementing new types of layers.
Because each layer can keep track of the layer(s) feeding into it, a
network's output :class:`Layer` instance can double as a handle to the full
network.
Parameters
----------
prev_layer : :class:`Layer` or None
Previous layer (optional), for adding all properties of previous layer(s) to this layer.
name : str or None
A unique layer name.
Methods
---------
print_params(details=True, session=None)
Print all parameters of this network.
print_layers()
Print all outputs of all layers of this network.
count_params()
Return the number of parameters of this network.
Examples
---------
- Define model
>>> x = tf.placeholder("float32", [None, 100])
>>> n = tl.layers.InputLayer(x, name='in')
>>> n = tl.layers.DenseLayer(n, 80, name='d1')
>>> n = tl.layers.DenseLayer(n, 80, name='d2')
- Get information
>>> print(n)
... Last layer is: DenseLayer (d2) [None, 80]
>>> n.print_layers()
... [TL] layer 0: d1/Identity:0 (?, 80) float32
... [TL] layer 1: d2/Identity:0 (?, 80) float32
>>> n.print_params(False)
... [TL] param 0: d1/W:0 (100, 80) float32_ref
... [TL] param 1: d1/b:0 (80,) float32_ref
... [TL] param 2: d2/W:0 (80, 80) float32_ref
... [TL] param 3: d2/b:0 (80,) float32_ref
... [TL] num of params: 14560
>>> n.count_params()
... 14560
- Slicing the outputs
>>> n2 = n[:, :30]
>>> print(n2)
... Last layer is: Layer (d2) [None, 30]
- Iterating the outputs
>>> for l in n:
>>> print(l)
... Tensor("d1/Identity:0", shape=(?, 80), dtype=float32)
... Tensor("d2/Identity:0", shape=(?, 80), dtype=float32)
"""
# Added to allow auto-completion
inputs = None
outputs = None
all_layers = []
all_params = []
all_drop = {}
@deprecated_alias(layer='prev_layer', end_support_version=1.9) # TODO remove this line for the 1.9 release
def __init__(self, prev_layer, name=None):
if name is None:
raise ValueError('Layer must have a name.')
scope_name = tf.get_variable_scope().name
if scope_name:
name = scope_name + '/' + name
self.name = name
# get all properties of previous layer(s)
if isinstance(prev_layer, Layer): # 1. for normal layer have only 1 input i.e. DenseLayer
# Hint : list(), dict() is pass by value (shallow), without them,
# it is pass by reference.
self.all_layers = list(prev_layer.all_layers)
self.all_params = list(prev_layer.all_params)
self.all_drop = dict(prev_layer.all_drop)
elif isinstance(prev_layer, list): # 2. for layer have multiply inputs i.e. ConcatLayer
self.all_layers = list_remove_repeat(sum([l.all_layers for l in prev_layer], []))
self.all_params = list_remove_repeat(sum([l.all_params for l in prev_layer], []))
self.all_drop = dict(sum([list(l.all_drop.items()) for l in prev_layer], []))
elif isinstance(prev_layer, tf.Tensor):
raise Exception("Please use InputLayer to convert Tensor/Placeholder to TL layer")
elif prev_layer is not None: # tl.models
self.all_layers = list(prev_layer.all_layers)
self.all_params = list(prev_layer.all_params)
self.all_drop = dict(prev_layer.all_drop)
# raise Exception("Unknown layer type %s" % type(prev_layer))
def print_params(self, details=True, session=None):
"""Print all info of parameters in the network"""
for i, p in enumerate(self.all_params):
if details:
try:
# logging.info(" param {:3}: {:15} (mean: {:<18}, median: {:<18}, std: {:<18}) {}".format(i, str(p.eval().shape), p.eval().mean(), np.median(p.eval()), p.eval().std(), p.name))
val = p.eval(session=session)
logging.info(
" param {:3}: {:20} {:15} {} (mean: {:<18}, median: {:<18}, std: {:<18}) ".format(
i, p.name, str(val.shape), p.dtype.name, val.mean(), np.median(val), val.std()
)
)
except Exception as e:
logging.info(str(e))
raise Exception(
"Hint: print params details after tl.layers.initialize_global_variables(sess) or use network.print_params(False)."
)
else:
logging.info(" param {:3}: {:20} {:15} {}".format(i, p.name, str(p.get_shape()), p.dtype.name))
logging.info(" num of params: %d" % self.count_params())
def print_layers(self):
"""Print all info of layers in the network"""
for i, layer in enumerate(self.all_layers):
# logging.info(" layer %d: %s" % (i, str(layer)))
logging.info(
" layer {:3}: {:20} {:15} {}".format(i, layer.name, str(layer.get_shape()), layer.dtype.name)
)
def count_params(self):
"""Return the number of parameters in the network"""
n_params = 0
for _i, p in enumerate(self.all_params):
n = 1
# for s in p.eval().shape:
for s in p.get_shape():
try:
s = int(s)
except Exception:
s = 1
if s:
n = n * s
n_params = n_params + n
return n_params
def __str__(self):
return " Last layer is: %s (%s) %s" % (self.__class__.__name__, self.name, self.outputs.get_shape().as_list())
def __getitem__(self, key):
net_new = Layer(prev_layer=None, name=self.name)
net_new.inputs = self.inputs
net_new.outputs = self.outputs[key]
net_new.all_layers = list(self.all_layers[:-1])
net_new.all_layers.append(net_new.outputs)
net_new.all_params = list(self.all_params)
net_new.all_drop = dict(self.all_drop)
return net_new
def __setitem__(self, key, item):
# self.outputs[key] = item
raise NotImplementedError("%s: __setitem__" % self.name)
def __delitem__(self, key):
raise NotImplementedError("%s: __delitem__" % self.name)
def __iter__(self):
for x in self.all_layers:
yield x
def __len__(self):
return len(self.all_layers)
class InputLayer(Layer):
"""
The :class:`InputLayer` class is the starting layer of a neural network.
Parameters
----------
inputs : placeholder or tensor
The input of a network.
name : str
A unique layer name.
"""
def __init__(self, inputs=None, name='input'):
super(InputLayer, self).__init__(prev_layer=None, name=name)
logging.info("InputLayer %s: %s" % (self.name, inputs.get_shape()))
self.outputs = inputs
self.all_layers = []
self.all_params = []
self.all_drop = {}
class OneHotInputLayer(Layer):
"""
The :class:`OneHotInputLayer` class is the starting layer of a neural network, see ``tf.one_hot``.
Parameters
----------
inputs : placeholder or tensor
The input of a network.
depth : None or int
If the input indices is rank N, the output will have rank N+1. The new axis is created at dimension `axis` (default: the new axis is appended at the end).
on_value : None or number
The value to represnt `ON`. If None, it will default to the value 1.
off_value : None or number
The value to represnt `OFF`. If None, it will default to the value 0.
axis : None or int
The axis.
dtype : None or TensorFlow dtype
The data type, None means tf.float32.
name : str
A unique layer name.
Examples
---------
>>> x = tf.placeholder(tf.int32, shape=[None])
>>> net = tl.layers.OneHotInputLayer(x, depth=8, name='onehot')
... (?, 8)
"""
def __init__(self, inputs=None, depth=None, on_value=None, off_value=None, axis=None, dtype=None, name='input'):
super(OneHotInputLayer, self).__init__(prev_layer=None, name=name)
logging.info("OneHotInputLayer %s: %s" % (self.name, inputs.get_shape()))
# assert depth != None, "depth is not given"
if depth is None:
logging.info(" [*] depth == None the number of output units is undefined")
self.outputs = tf.one_hot(inputs, depth, on_value=on_value, off_value=off_value, axis=axis, dtype=dtype)
self.all_layers = []
self.all_params = []
self.all_drop = {}
class Word2vecEmbeddingInputlayer(Layer):
"""
The :class:`Word2vecEmbeddingInputlayer` class is a fully connected layer.
For Word Embedding, words are input as integer index.
The output is the embedded word vector.
Parameters
----------
inputs : placeholder or tensor
The input of a network. For word inputs, please use integer index format, 2D tensor : [batch_size, num_steps(num_words)]
train_labels : placeholder
For word labels. integer index format
vocabulary_size : int
The size of vocabulary, number of words
embedding_size : int
The number of embedding dimensions
num_sampled : int
The mumber of negative examples for NCE loss
nce_loss_args : dictionary
The arguments for tf.nn.nce_loss()
E_init : initializer
The initializer for initializing the embedding matrix
E_init_args : dictionary
The arguments for embedding initializer
nce_W_init : initializer
The initializer for initializing the nce decoder weight matrix
nce_W_init_args : dictionary
The arguments for initializing the nce decoder weight matrix
nce_b_init : initializer
The initializer for initializing of the nce decoder bias vector
nce_b_init_args : dictionary
The arguments for initializing the nce decoder bias vector
name : str
A unique layer name
Attributes
----------
nce_cost : Tensor
The NCE loss.
outputs : Tensor
The embedding layer outputs.
normalized_embeddings : Tensor
Normalized embedding matrix.
Examples
--------
With TensorLayer : see ``tensorlayer/example/tutorial_word2vec_basic.py``
>>> batch_size = 8
>>> train_inputs = tf.placeholder(tf.int32, shape=(batch_size))
>>> train_labels = tf.placeholder(tf.int32, shape=(batch_size, 1))
>>> net = tl.layers.Word2vecEmbeddingInputlayer(inputs=train_inputs,
... train_labels=train_labels, vocabulary_size=1000, embedding_size=200,
... num_sampled=64, name='word2vec')
... (8, 200)
>>> cost = net.nce_cost
>>> train_params = net.all_params
>>> cost = net.nce_cost
>>> train_params = net.all_params
>>> train_op = tf.train.GradientDescentOptimizer(learning_rate).minimize(
... cost, var_list=train_params)
>>> normalized_embeddings = net.normalized_embeddings
Without TensorLayer : see ``tensorflow/examples/tutorials/word2vec/word2vec_basic.py``
>>> train_inputs = tf.placeholder(tf.int32, shape=(batch_size))
>>> train_labels = tf.placeholder(tf.int32, shape=(batch_size, 1))
>>> embeddings = tf.Variable(
... tf.random_uniform([vocabulary_size, embedding_size], -1.0, 1.0))
>>> embed = tf.nn.embedding_lookup(embeddings, train_inputs)
>>> nce_weights = tf.Variable(
... tf.truncated_normal([vocabulary_size, embedding_size],
... stddev=1.0 / math.sqrt(embedding_size)))
>>> nce_biases = tf.Variable(tf.zeros([vocabulary_size]))
>>> cost = tf.reduce_mean(
... tf.nn.nce_loss(weights=nce_weights, biases=nce_biases,
... inputs=embed, labels=train_labels,
... num_sampled=num_sampled, num_classes=vocabulary_size,
... num_true=1))
References
----------
`tensorflow/examples/tutorials/word2vec/word2vec_basic.py <https://github.com/tensorflow/tensorflow/blob/r0.7/tensorflow/examples/tutorials/word2vec/word2vec_basic.py>`__
"""
def __init__(
self,
inputs=None,
train_labels=None,
vocabulary_size=80000,
embedding_size=200,
num_sampled=64,
nce_loss_args=None,
E_init=tf.random_uniform_initializer(minval=-1.0, maxval=1.0),
E_init_args=None,
nce_W_init=tf.truncated_normal_initializer(stddev=0.03),
nce_W_init_args=None,
nce_b_init=tf.constant_initializer(value=0.0),
nce_b_init_args=None,
name='word2vec',
):
if nce_loss_args is None:
nce_loss_args = {}
if E_init_args is None:
E_init_args = {}
if nce_W_init_args is None:
nce_W_init_args = {}
if nce_b_init_args is None:
nce_b_init_args = {}
super(Word2vecEmbeddingInputlayer, self).__init__(prev_layer=None, name=name)
logging.info("Word2vecEmbeddingInputlayer %s: (%d, %d)" % (self.name, vocabulary_size, embedding_size))
self.inputs = inputs
# Look up embeddings for inputs.
# Note: a row of 'embeddings' is the vector representation of a word.
# for the sake of speed, it is better to slice the embedding matrix
# instead of transfering a word id to one-hot-format vector and then
# multiply by the embedding matrix.
# embed is the outputs of the hidden layer (embedding layer), it is a
# row vector with 'embedding_size' values.
with tf.variable_scope(name):
embeddings = tf.get_variable(
name='embeddings', shape=(vocabulary_size, embedding_size), initializer=E_init,
dtype=LayersConfig.tf_dtype, **E_init_args
)
embed = tf.nn.embedding_lookup(embeddings, self.inputs)
# Construct the variables for the NCE loss (i.e. negative sampling)
nce_weights = tf.get_variable(
name='nce_weights', shape=(vocabulary_size, embedding_size), initializer=nce_W_init,
dtype=LayersConfig.tf_dtype, **nce_W_init_args
)
nce_biases = tf.get_variable(
name='nce_biases', shape=(vocabulary_size), initializer=nce_b_init, dtype=LayersConfig.tf_dtype,
**nce_b_init_args
)
# Compute the average NCE loss for the batch.
# tf.nce_loss automatically draws a new sample of the negative labels
# each time we evaluate the loss.
self.nce_cost = tf.reduce_mean(
tf.nn.nce_loss(
weights=nce_weights, biases=nce_biases, inputs=embed, labels=train_labels, num_sampled=num_sampled,
num_classes=vocabulary_size, **nce_loss_args
)
)
self.outputs = embed
self.normalized_embeddings = tf.nn.l2_normalize(embeddings, 1)
self.all_layers = [self.outputs]
self.all_params = [embeddings, nce_weights, nce_biases]
self.all_drop = {}
class EmbeddingInputlayer(Layer):
"""
The :class:`EmbeddingInputlayer` class is a look-up table for word embedding.
Word content are accessed using integer indexes, then the output is the embedded word vector.
To train a word embedding matrix, you can used :class:`Word2vecEmbeddingInputlayer`.
If you have a pre-trained matrix, you can assign the parameters into it.
Parameters
----------
inputs : placeholder
The input of a network. For word inputs.
Please use integer index format, 2D tensor : (batch_size, num_steps(num_words)).
vocabulary_size : int
The size of vocabulary, number of words.
embedding_size : int
The number of embedding dimensions.
E_init : initializer
The initializer for the embedding matrix.
E_init_args : dictionary
The arguments for embedding matrix initializer.
name : str
A unique layer name.
Attributes
----------
outputs : tensor
The embedding layer output is a 3D tensor in the shape: (batch_size, num_steps(num_words), embedding_size).
Examples
--------
>>> batch_size = 8
>>> x = tf.placeholder(tf.int32, shape=(batch_size, ))
>>> net = tl.layers.EmbeddingInputlayer(inputs=x, vocabulary_size=1000, embedding_size=50, name='embed')
... (8, 50)
"""
def __init__(
self,
inputs=None,
vocabulary_size=80000,
embedding_size=200,
E_init=tf.random_uniform_initializer(-0.1, 0.1),
E_init_args=None,
name='embedding',
):
if E_init_args is None:
E_init_args = {}
super(EmbeddingInputlayer, self).__init__(prev_layer=None, name=name)
logging.info("EmbeddingInputlayer %s: (%d, %d)" % (self.name, vocabulary_size, embedding_size))
self.inputs = inputs
with tf.variable_scope(name):
embeddings = tf.get_variable(
name='embeddings', shape=(vocabulary_size, embedding_size), initializer=E_init,
dtype=LayersConfig.tf_dtype, **E_init_args
)
embed = tf.nn.embedding_lookup(embeddings, self.inputs)
self.outputs = embed
self.all_layers = [self.outputs]
self.all_params = [embeddings]
self.all_drop = {}
class AverageEmbeddingInputlayer(Layer):
"""The :class:`AverageEmbeddingInputlayer` averages over embeddings of inputs.
This is often used as the input layer for models like DAN[1] and FastText[2].
Parameters
----------
inputs : placeholder or tensor
The network input.
For word inputs, please use integer index format, 2D tensor: (batch_size, num_steps(num_words)).
vocabulary_size : int
The size of vocabulary.
embedding_size : int
The dimension of the embedding vectors.
pad_value : int
The scalar padding value used in inputs, 0 as default.
embeddings_initializer : initializer
The initializer of the embedding matrix.
embeddings_kwargs : None or dictionary
The arguments to get embedding matrix variable.
name : str
A unique layer name.
References
----------
- [1] Iyyer, M., Manjunatha, V., Boyd-Graber, J., & Daum’e III, H. (2015). Deep Unordered Composition Rivals Syntactic Methods for Text Classification. In Association for Computational Linguistics.
- [2] Joulin, A., Grave, E., Bojanowski, P., & Mikolov, T. (2016). `Bag of Tricks for Efficient Text Classification. <http://arxiv.org/abs/1607.01759>`__
Examples
---------
>>> batch_size = 8
>>> length = 5
>>> x = tf.placeholder(tf.int32, shape=(batch_size, length))
>>> net = tl.layers.AverageEmbeddingInputlayer(x, vocabulary_size=1000, embedding_size=50, name='avg')
... (8, 50)
"""
def __init__(
self,
inputs,
vocabulary_size,
embedding_size,
pad_value=0,
embeddings_initializer=tf.random_uniform_initializer(-0.1, 0.1),
embeddings_kwargs=None,
name='average_embedding',
):
super(AverageEmbeddingInputlayer, self).__init__(prev_layer=None, name=name)
logging.info("AverageEmbeddingInputlayer %s: (%d, %d)" % (name, vocabulary_size, embedding_size))
# if embeddings_kwargs is None:
# embeddings_kwargs = {}
if inputs.get_shape().ndims != 2:
raise ValueError('inputs must be of size batch_size * batch_sentence_length')
self.inputs = inputs
with tf.variable_scope(name):
self.embeddings = tf.get_variable(
name='embeddings', shape=(vocabulary_size, embedding_size), initializer=embeddings_initializer,
dtype=LayersConfig.tf_dtype,
**(embeddings_kwargs or {})
# **embeddings_kwargs
) # **(embeddings_kwargs or {}),
word_embeddings = tf.nn.embedding_lookup(
self.embeddings,
self.inputs,
name='word_embeddings',
)
# Zero out embeddings of pad value
masks = tf.not_equal(self.inputs, pad_value, name='masks')
word_embeddings *= tf.cast(
tf.expand_dims(masks, axis=-1),
# tf.float32,
dtype=LayersConfig.tf_dtype,
)
sum_word_embeddings = tf.reduce_sum(word_embeddings, axis=1)
# Count number of non-padding words in each sentence
sentence_lengths = tf.count_nonzero(
masks,
axis=1,
keepdims=True,
# dtype=tf.float32,
dtype=LayersConfig.tf_dtype,
name='sentence_lengths',
)
sentence_embeddings = tf.divide(
sum_word_embeddings,
sentence_lengths + 1e-8, # Add epsilon to avoid dividing by 0
name='sentence_embeddings'
)
self.outputs = sentence_embeddings
self.all_layers = [self.outputs]
self.all_params = [self.embeddings]
self.all_drop = {}
class DenseLayer(Layer):
"""The :class:`DenseLayer` class is a fully connected layer.
Parameters
----------
prev_layer : :class:`Layer`
Previous layer.
n_units : int
The number of units of this layer.
act : activation function
The activation function of this layer.
W_init : initializer
The initializer for the weight matrix.
b_init : initializer or None
The initializer for the bias vector. If None, skip biases.
W_init_args : dictionary
The arguments for the weight matrix initializer.
b_init_args : dictionary
The arguments for the bias vector initializer.
name : a str
A unique layer name.
Examples
--------
With TensorLayer
>>> net = tl.layers.InputLayer(x, name='input')
>>> net = tl.layers.DenseLayer(net, 800, act=tf.nn.relu, name='relu')
Without native TensorLayer APIs, you can do as follow.
>>> W = tf.Variable(
... tf.random_uniform([n_in, n_units], -1.0, 1.0), name='W')
>>> b = tf.Variable(tf.zeros(shape=[n_units]), name='b')
>>> y = tf.nn.relu(tf.matmul(inputs, W) + b)
Notes
-----
If the layer input has more than two axes, it needs to be flatten by using :class:`FlattenLayer`.
"""
@deprecated_alias(layer='prev_layer', end_support_version=1.9) # TODO remove this line for the 1.9 release
def __init__(
self,
prev_layer,
n_units=100,
act=tf.identity,
W_init=tf.truncated_normal_initializer(stddev=0.1),
b_init=tf.constant_initializer(value=0.0),
W_init_args=None,
b_init_args=None,
name='dense',
):
super(DenseLayer, self).__init__(prev_layer=prev_layer, name=name)
logging.info("DenseLayer %s: %d %s" % (name, n_units, act.__name__))
self.inputs = prev_layer.outputs
self.n_units = n_units
if W_init_args is None:
W_init_args = {}
if b_init_args is None:
b_init_args = {}
if self.inputs.get_shape().ndims != 2:
raise Exception("The input dimension must be rank 2, please reshape or flatten it")
n_in = int(self.inputs.get_shape()[-1])
with tf.variable_scope(name):
W = tf.get_variable(
name='W', shape=(n_in, n_units), initializer=W_init, dtype=LayersConfig.tf_dtype, **W_init_args
)
if b_init is not None:
try:
b = tf.get_variable(
name='b', shape=(n_units), initializer=b_init, dtype=LayersConfig.tf_dtype, **b_init_args
)
except Exception: # If initializer is a constant, do not specify shape.
b = tf.get_variable(name='b', initializer=b_init, dtype=LayersConfig.tf_dtype, **b_init_args)
self.outputs = act(tf.matmul(self.inputs, W) + b)
else:
self.outputs = act(tf.matmul(self.inputs, W))
self.all_layers.append(self.outputs)
if b_init is not None:
self.all_params.extend([W, b])
else:
self.all_params.append(W)
class ReconLayer(DenseLayer):