keras 0.2.0__py2.7.egg

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (116) hide show
  1. EGG-INFO/PKG-INFO +11 -0
  2. EGG-INFO/SOURCES.txt +51 -0
  3. EGG-INFO/dependency_links.txt +1 -0
  4. EGG-INFO/requires.txt +6 -0
  5. EGG-INFO/top_level.txt +1 -0
  6. EGG-INFO/zip-safe +1 -0
  7. keras/__init__.py +15 -0
  8. keras/__init__.pyc +0 -0
  9. keras/activations.py +49 -0
  10. keras/activations.pyc +0 -0
  11. keras/backend/__init__.py +39 -0
  12. keras/backend/__init__.pyc +0 -0
  13. keras/backend/common.py +31 -0
  14. keras/backend/common.pyc +0 -0
  15. keras/backend/tensorflow_backend.py +602 -0
  16. keras/backend/tensorflow_backend.pyc +0 -0
  17. keras/backend/theano_backend.py +622 -0
  18. keras/backend/theano_backend.pyc +0 -0
  19. keras/callbacks.py +295 -0
  20. keras/callbacks.pyc +0 -0
  21. keras/constraints.py +45 -0
  22. keras/constraints.pyc +0 -0
  23. keras/datasets/__init__.py +0 -0
  24. keras/datasets/__init__.pyc +0 -0
  25. keras/datasets/cifar.py +22 -0
  26. keras/datasets/cifar.pyc +0 -0
  27. keras/datasets/cifar10.py +31 -0
  28. keras/datasets/cifar10.pyc +0 -0
  29. keras/datasets/cifar100.py +28 -0
  30. keras/datasets/cifar100.pyc +0 -0
  31. keras/datasets/data_utils.py +50 -0
  32. keras/datasets/data_utils.pyc +0 -0
  33. keras/datasets/imdb.py +66 -0
  34. keras/datasets/imdb.pyc +0 -0
  35. keras/datasets/mnist.py +23 -0
  36. keras/datasets/mnist.pyc +0 -0
  37. keras/datasets/reuters.py +148 -0
  38. keras/datasets/reuters.pyc +0 -0
  39. keras/initializations.py +86 -0
  40. keras/initializations.pyc +0 -0
  41. keras/layers/__init__.py +0 -0
  42. keras/layers/__init__.pyc +0 -0
  43. keras/layers/advanced_activations.py +156 -0
  44. keras/layers/advanced_activations.pyc +0 -0
  45. keras/layers/containers.py +405 -0
  46. keras/layers/containers.pyc +0 -0
  47. keras/layers/convolutional.py +505 -0
  48. keras/layers/convolutional.pyc +0 -0
  49. keras/layers/core.py +1428 -0
  50. keras/layers/core.pyc +0 -0
  51. keras/layers/embeddings.py +88 -0
  52. keras/layers/embeddings.pyc +0 -0
  53. keras/layers/noise.py +55 -0
  54. keras/layers/noise.pyc +0 -0
  55. keras/layers/normalization.py +123 -0
  56. keras/layers/normalization.pyc +0 -0
  57. keras/layers/ntm.py +326 -0
  58. keras/layers/ntm.pyc +0 -0
  59. keras/layers/recurrent.py +354 -0
  60. keras/layers/recurrent.pyc +0 -0
  61. keras/models.py +743 -0
  62. keras/models.pyc +0 -0
  63. keras/objectives.py +59 -0
  64. keras/objectives.pyc +0 -0
  65. keras/optimizers.py +229 -0
  66. keras/optimizers.pyc +0 -0
  67. keras/preprocessing/__init__.py +0 -0
  68. keras/preprocessing/__init__.pyc +0 -0
  69. keras/preprocessing/image.py +246 -0
  70. keras/preprocessing/image.pyc +0 -0
  71. keras/preprocessing/sequence.py +124 -0
  72. keras/preprocessing/sequence.pyc +0 -0
  73. keras/preprocessing/text.py +176 -0
  74. keras/preprocessing/text.pyc +0 -0
  75. keras/regularizers.py +86 -0
  76. keras/regularizers.pyc +0 -0
  77. keras/utils/__init__.py +0 -0
  78. keras/utils/__init__.pyc +0 -0
  79. keras/utils/generic_utils.py +133 -0
  80. keras/utils/generic_utils.pyc +0 -0
  81. keras/utils/io_utils.py +71 -0
  82. keras/utils/io_utils.pyc +0 -0
  83. keras/utils/layer_utils.py +93 -0
  84. keras/utils/layer_utils.pyc +0 -0
  85. keras/utils/np_utils.py +53 -0
  86. keras/utils/np_utils.pyc +0 -0
  87. keras/utils/test_utils.py +27 -0
  88. keras/utils/test_utils.pyc +0 -0
  89. keras/utils/theano_utils.py +44 -0
  90. keras/utils/theano_utils.pyc +0 -0
  91. keras/utils/visualize_util.py +41 -0
  92. keras/utils/visualize_util.pyc +0 -0
  93. keras/wrappers/__init__.py +0 -0
  94. keras/wrappers/__init__.pyc +0 -0
  95. keras/wrappers/scikit_learn.py +266 -0
  96. keras/wrappers/scikit_learn.pyc +0 -0
  97. tests/__init__.py +0 -0
  98. tests/__init__.pyc +0 -0
  99. tests/manual/__init__.py +0 -0
  100. tests/manual/__init__.pyc +0 -0
  101. tests/manual/check_autoencoder.py +134 -0
  102. tests/manual/check_autoencoder.pyc +0 -0
  103. tests/manual/check_callbacks.py +236 -0
  104. tests/manual/check_callbacks.pyc +0 -0
  105. tests/manual/check_constraints.py +100 -0
  106. tests/manual/check_constraints.pyc +0 -0
  107. tests/manual/check_masked_recurrent.py +130 -0
  108. tests/manual/check_masked_recurrent.pyc +0 -0
  109. tests/manual/check_model_utils.py +44 -0
  110. tests/manual/check_model_utils.pyc +0 -0
  111. tests/manual/check_save_weights.py +40 -0
  112. tests/manual/check_save_weights.pyc +0 -0
  113. tests/manual/check_wrappers.py +126 -0
  114. tests/manual/check_wrappers.pyc +0 -0
  115. tests/manual/check_yaml.py +101 -0
  116. tests/manual/check_yaml.pyc +0 -0
keras/layers/core.pyc ADDED
Binary file
@@ -0,0 +1,88 @@
1
+ from __future__ import absolute_import
2
+ from .. import backend as K
3
+
4
+ from .. import activations, initializations, regularizers, constraints
5
+ from ..layers.core import Layer, MaskedLayer
6
+
7
+ from ..constraints import unitnorm
8
+
9
+
10
+ class Embedding(Layer):
11
+ '''
12
+ Turn positive integers (indexes) into denses vectors of fixed size.
13
+ eg. [[4], [20]] -> [[0.25, 0.1], [0.6, -0.2]]
14
+
15
+ @input_dim: size of vocabulary (highest input integer + 1)
16
+ @out_dim: size of dense representation
17
+ '''
18
+ input_ndim = 2
19
+
20
+ def __init__(self, input_dim, output_dim,
21
+ init='uniform', input_length=None,
22
+ W_regularizer=None, activity_regularizer=None,
23
+ W_constraint=None,
24
+ mask_zero=False,
25
+ weights=None, **kwargs):
26
+ self.input_dim = input_dim
27
+ self.output_dim = output_dim
28
+ self.init = initializations.get(init)
29
+ self.input_length = input_length
30
+ self.mask_zero = mask_zero
31
+
32
+ self.W_constraint = constraints.get(W_constraint)
33
+ self.constraints = [self.W_constraint]
34
+
35
+ self.W_regularizer = regularizers.get(W_regularizer)
36
+ self.activity_regularizer = regularizers.get(activity_regularizer)
37
+
38
+ self.initial_weights = weights
39
+ kwargs['input_shape'] = (self.input_dim,)
40
+ super(Embedding, self).__init__(**kwargs)
41
+
42
+ def build(self):
43
+ self.input = K.placeholder(shape=(None, self.input_length),
44
+ dtype='int32')
45
+ self.W = self.init((self.input_dim, self.output_dim))
46
+ self.params = [self.W]
47
+ self.regularizers = []
48
+ if self.W_regularizer:
49
+ self.W_regularizer.set_param(self.W)
50
+ self.regularizers.append(self.W_regularizer)
51
+
52
+ if self.activity_regularizer:
53
+ self.activity_regularizer.set_layer(self)
54
+ self.regularizers.append(self.activity_regularizer)
55
+
56
+ if self.initial_weights is not None:
57
+ self.set_weights(self.initial_weights)
58
+
59
+ def get_output_mask(self, train=None):
60
+ X = self.get_input(train)
61
+ if not self.mask_zero:
62
+ return None
63
+ else:
64
+ if K._BACKEND == "tensorflow":
65
+ raise Exception("Masking is Theano-only for the time being.")
66
+ return K.ones_like(X) * (1 - K.equal(X, 0))
67
+
68
+ @property
69
+ def output_shape(self):
70
+ return (self.input_shape[0], self.input_length, self.output_dim)
71
+
72
+ def get_output(self, train=False):
73
+ X = self.get_input(train)
74
+ out = K.gather(self.W, X)
75
+ return out
76
+
77
+ def get_config(self):
78
+ config = {"name": self.__class__.__name__,
79
+ "input_dim": self.input_dim,
80
+ "output_dim": self.output_dim,
81
+ "init": self.init.__name__,
82
+ "input_length": self.input_length,
83
+ "mask_zero": self.mask_zero,
84
+ "activity_regularizer": self.activity_regularizer.get_config() if self.activity_regularizer else None,
85
+ "W_regularizer": self.W_regularizer.get_config() if self.W_regularizer else None,
86
+ "W_constraint": self.W_constraint.get_config() if self.W_constraint else None}
87
+ base_config = super(Embedding, self).get_config()
88
+ return dict(list(base_config.items()) + list(config.items()))
Binary file
keras/layers/noise.py ADDED
@@ -0,0 +1,55 @@
1
+ from __future__ import absolute_import
2
+ from .core import MaskedLayer
3
+ from .. import backend as K
4
+
5
+
6
+ class GaussianNoise(MaskedLayer):
7
+ '''
8
+ Corruption process with GaussianNoise
9
+ '''
10
+ def __init__(self, sigma, **kwargs):
11
+ super(GaussianNoise, self).__init__(**kwargs)
12
+ self.sigma = sigma
13
+
14
+ def get_output(self, train=False):
15
+ X = self.get_input(train)
16
+ if not train or self.sigma == 0:
17
+ return X
18
+ else:
19
+ return X + K.random_normal(shape=K.shape(X),
20
+ mean=0.,
21
+ std=self.sigma)
22
+
23
+ def get_config(self):
24
+ config = {"name": self.__class__.__name__,
25
+ "sigma": self.sigma}
26
+ base_config = super(GaussianNoise, self).get_config()
27
+ return dict(list(base_config.items()) + list(config.items()))
28
+
29
+
30
+ class GaussianDropout(MaskedLayer):
31
+ '''
32
+ Multiplicative Gaussian Noise
33
+ Reference:
34
+ Dropout: A Simple Way to Prevent Neural Networks from Overfitting
35
+ Srivastava, Hinton, et al. 2014
36
+ http://www.cs.toronto.edu/~rsalakhu/papers/srivastava14a.pdf
37
+ '''
38
+ def __init__(self, p, **kwargs):
39
+ super(GaussianDropout, self).__init__(**kwargs)
40
+ self.p = p
41
+
42
+ def get_output(self, train):
43
+ X = self.get_input(train)
44
+ if train:
45
+ # self.p refers to drop probability rather than
46
+ # retain probability (as in paper), for consistency
47
+ X *= K.random_normal(shape=K.shape(X), mean=1.0,
48
+ std=self.p / (1.0 - self.p))
49
+ return X
50
+
51
+ def get_config(self):
52
+ config = {"name": self.__class__.__name__,
53
+ "p": self.p}
54
+ base_config = super(GaussianDropout, self).get_config()
55
+ return dict(list(base_config.items()) + list(config.items()))
keras/layers/noise.pyc ADDED
Binary file
@@ -0,0 +1,123 @@
1
+ from ..layers.core import Layer
2
+ from .. import initializations
3
+ from .. import backend as K
4
+
5
+
6
+ class BatchNormalization(Layer):
7
+ '''
8
+ Reference:
9
+ Batch Normalization: Accelerating Deep Network Training
10
+ by Reducing Internal Covariate Shift
11
+ http://arxiv.org/pdf/1502.03167v3.pdf
12
+
13
+ mode: 0 -> featurewise normalization
14
+ 1 -> samplewise normalization
15
+ (may sometimes outperform featurewise mode)
16
+
17
+ momentum: momentum term in the computation
18
+ of a running estimate of the mean and std of the data
19
+ '''
20
+ def __init__(self, epsilon=1e-6, mode=0, momentum=0.9,
21
+ weights=None, **kwargs):
22
+ self.init = initializations.get("uniform")
23
+ self.epsilon = epsilon
24
+ self.mode = mode
25
+ self.momentum = momentum
26
+ self.initial_weights = weights
27
+ super(BatchNormalization, self).__init__(**kwargs)
28
+
29
+ def build(self):
30
+ input_shape = self.input_shape # starts with samples axis
31
+ input_shape = input_shape[1:]
32
+
33
+ self.gamma = self.init((input_shape))
34
+ self.beta = K.zeros(input_shape)
35
+
36
+ self.params = [self.gamma, self.beta]
37
+ self.running_mean = K.zeros(input_shape)
38
+ self.running_std = K.ones((input_shape))
39
+
40
+ # initialize self.updates: batch mean/std computation
41
+ X = self.get_input(train=True)
42
+ m = K.mean(X, axis=0)
43
+ std = K.mean(K.square(X - m) + self.epsilon, axis=0)
44
+ std = K.sqrt(std)
45
+ mean_update = self.momentum * self.running_mean + (1-self.momentum) * m
46
+ std_update = self.momentum * self.running_std + (1-self.momentum) * std
47
+ self.updates = [(self.running_mean, mean_update),
48
+ (self.running_std, std_update)]
49
+
50
+ if self.initial_weights is not None:
51
+ self.set_weights(self.initial_weights)
52
+ del self.initial_weights
53
+
54
+ def get_weights(self):
55
+ super_weights = super(BatchNormalization, self).get_weights()
56
+ return super_weights + [K.get_value(self.running_mean),
57
+ K.get_value(self.running_std)]
58
+
59
+ def set_weights(self, weights):
60
+ K.set_value(self.running_mean, weights[-2])
61
+ K.set_value(self.running_std, weights[-1])
62
+ super(BatchNormalization, self).set_weights(weights[:-2])
63
+
64
+ def get_output(self, train):
65
+ X = self.get_input(train)
66
+ if self.mode == 0:
67
+ X_normed = ((X - self.running_mean) /
68
+ (self.running_std + self.epsilon))
69
+ elif self.mode == 1:
70
+ m = K.mean(X, axis=-1, keepdims=True)
71
+ std = K.std(X, axis=-1, keepdims=True)
72
+ X_normed = (X - m) / (std + self.epsilon)
73
+ out = self.gamma * X_normed + self.beta
74
+ return out
75
+
76
+ def get_config(self):
77
+ config = {"name": self.__class__.__name__,
78
+ "epsilon": self.epsilon,
79
+ "mode": self.mode,
80
+ "momentum": self.momentum}
81
+ base_config = super(BatchNormalization, self).get_config()
82
+ return dict(list(base_config.items()) + list(config.items()))
83
+
84
+
85
+ class LRN2D(Layer):
86
+ """
87
+ This code is adapted from pylearn2.
88
+ License at: https://github.com/lisa-lab/pylearn2/blob/master/LICENSE.txt
89
+ """
90
+
91
+ def __init__(self, alpha=1e-4, k=2, beta=0.75, n=5, **kwargs):
92
+ if n % 2 == 0:
93
+ raise NotImplementedError("LRN2D only works with odd n. n provided: " + str(n))
94
+ super(LRN2D, self).__init__(**kwargs)
95
+ self.alpha = alpha
96
+ self.k = k
97
+ self.beta = beta
98
+ self.n = n
99
+
100
+ def get_output(self, train):
101
+ X = self.get_input(train)
102
+ b, ch, r, c = K.shape(X)
103
+ half_n = self.n // 2
104
+ input_sqr = K.square(X)
105
+ extra_channels = K.zeros((b, ch + 2 * half_n, r, c))
106
+ input_sqr = K.concatenate([extra_channels[:, :half_n, :, :],
107
+ input_sqr,
108
+ extra_channels[:, half_n + ch:, :, :]],
109
+ axis=1)
110
+ scale = self.k
111
+ for i in range(self.n):
112
+ scale += self.alpha * input_sqr[:, i:i + ch, :, :]
113
+ scale = scale ** self.beta
114
+ return X / scale
115
+
116
+ def get_config(self):
117
+ config = {"name": self.__class__.__name__,
118
+ "alpha": self.alpha,
119
+ "k": self.k,
120
+ "beta": self.beta,
121
+ "n": self.n}
122
+ base_config = super(LRN2D, self).get_config()
123
+ return dict(list(base_config.items()) + list(config.items()))
Binary file
keras/layers/ntm.py ADDED
@@ -0,0 +1,326 @@
1
+ import numpy as np
2
+ from scipy.linalg import circulant
3
+
4
+ from .. import backend as K
5
+ import theano
6
+ import theano.tensor as T
7
+ floatX = theano.config.floatX
8
+
9
+ from keras.layers.recurrent import Recurrent, GRU, LSTM
10
+ from keras.utils.theano_utils import shared_zeros, alloc_zeros_matrix, shared_scalar
11
+ tol = 1e-4
12
+
13
+
14
+ def _update_controller(self, inp, h_tm1, M, mask):
15
+ """ Update inner RNN controler
16
+ We have to update the inner RNN inside the Neural Turing Machine, this
17
+ is an almost literal copy of keras.layers.recurrent.GRU and
18
+ keras.layers.recurrent.LSTM see these clases for further details.
19
+ """
20
+ x = T.concatenate([inp, M], axis=-1)
21
+ # get inputs
22
+ if self.inner_rnn == 'gru':
23
+ x_z = T.dot(x, self.rnn.W_z) + self.rnn.b_z
24
+ x_r = T.dot(x, self.rnn.W_r) + self.rnn.b_r
25
+ x_h = T.dot(x, self.rnn.W_h) + self.rnn.b_h
26
+
27
+ elif self.inner_rnn == 'lstm':
28
+ xi = T.dot(x, self.rnn.W_i) + self.rnn.b_i
29
+ xf = T.dot(x, self.rnn.W_f) + self.rnn.b_f
30
+ xc = T.dot(x, self.rnn.W_c) + self.rnn.b_c
31
+ xo = T.dot(x, self.rnn.W_o) + self.rnn.b_o
32
+
33
+ elif self.inner_rnn == 'simple':
34
+ x = T.dot(x, self.rnn.W) + self.rnn.b
35
+
36
+ # update state
37
+ if self.inner_rnn == 'gru':
38
+ h = self.rnn._step(x_z, x_r, x_h, 1., h_tm1[0],
39
+ self.rnn.U_z,
40
+ self.rnn.U_r,
41
+ self.rnn.U_h)
42
+ h = mask[:, None] * h + (1-mask[:, None])*h_tm1[0]
43
+ h = (h, )
44
+
45
+ elif self.inner_rnn == 'lstm':
46
+ h = self.rnn._step(xi, xf, xo, xc, 1.,
47
+ h_tm1[1], h_tm1[0],
48
+ self.rnn.U_i, self.rnn.U_f,
49
+ self.rnn.U_o, self.rnn.U_c)
50
+ h = h[::-1]
51
+ h = tuple([mask[:, None]*h[i] +
52
+ (1-mask[:, None])*h_tm1[i] for i in range(len(h))])
53
+
54
+ elif self.inner_rnn == 'simple':
55
+ h = self.rnn._step(x, 1, h_tm1[0], self.rnn.U)
56
+ h = mask[:, None] * h + (1-mask[:, None])*h_tm1[0]
57
+ h = (h, )
58
+
59
+ return h
60
+
61
+
62
+ def _circulant(leng, n_shifts):
63
+ """ Generate circulant copies of a vector.
64
+ This will generate a tensor with `n_shifts` of rotated versions the
65
+ identity matrix. When this tensor is multiplied by a vector
66
+ the result are `n_shifts` shifted versions of that vector. Since
67
+ everything is done with inner products, this operation is differentiable.
68
+
69
+ Paramters:
70
+ ----------
71
+ leng: int > 0, number of memory locations
72
+ n_shifts: int > 0, number of allowed shifts (if 1, no shift)
73
+
74
+ Returns:
75
+ --------
76
+ shift operation, a tensor with dimensions (n_shifts, leng, leng)
77
+ """
78
+ eye = np.eye(leng)
79
+ shifts = range(n_shifts//2, -n_shifts//2, -1)
80
+ C = np.asarray([np.roll(eye, s, axis=1) for s in shifts])
81
+ return theano.shared(C.astype(theano.config.floatX))
82
+
83
+
84
+ def _renorm(x):
85
+ return x / (x.sum(axis=1, keepdims=True))
86
+
87
+
88
+ def _softmax(x):
89
+ wt = x.flatten(ndim=2)
90
+ w = T.nnet.softmax(wt)
91
+ return w.reshape(x.shape) # T.clip(s, 0, 1)
92
+
93
+
94
+ def _cosine_distance(M, k):
95
+ dot = (M * k[:, None, :]).sum(axis=-1)
96
+ nM = T.sqrt((M**2).sum(axis=-1))
97
+ nk = T.sqrt((k**2).sum(axis=-1, keepdims=True))
98
+ return dot / (nM * nk)
99
+
100
+
101
+ class NeuralTuringMachine(Recurrent):
102
+ """ Neural Turing Machines
103
+
104
+ Parameters:
105
+ -----------
106
+ shift_range: int, number of available shifts, ex. if 3, avilable shifts are
107
+ (-1, 0, 1)
108
+ n_slots: number of memory locations
109
+ m_length: memory length at each location
110
+ inner_rnn: str, supported values are 'gru' and 'lstm'
111
+ output_dim: hidden state size (RNN controller output_dim)
112
+
113
+ Known issues and TODO:
114
+ ----------------------
115
+ Theano may complain when n_slots == 1.
116
+ Add multiple reading and writing heads.
117
+
118
+ """
119
+ def __init__(self, output_dim, n_slots, m_length, shift_range=3,
120
+ inner_rnn='gru', truncate_gradient=-1, return_sequences=False,
121
+ init='glorot_uniform', inner_init='orthogonal',
122
+ input_dim=None, input_length=None, **kwargs):
123
+ if K._BACKEND != 'theano':
124
+ raise Exception('NeuralTuringMachine is only available for Theano for the time being. ' +
125
+ 'It will be adapted to TensorFlow soon.')
126
+ self.output_dim = output_dim
127
+ self.n_slots = n_slots
128
+ self.m_length = m_length
129
+ self.shift_range = shift_range
130
+ self.init = init
131
+ self.inner_init = inner_init
132
+ self.inner_rnn = inner_rnn
133
+ self.return_sequences = return_sequences
134
+ self.truncate_gradient = truncate_gradient
135
+
136
+ self.input_dim = input_dim
137
+ self.input_length = input_length
138
+ if self.input_dim:
139
+ kwargs['input_shape'] = (self.input_length, self.input_dim)
140
+ super(NeuralTuringMachine, self).__init__(**kwargs)
141
+
142
+ def build(self):
143
+ input_leng, input_dim = self.input_shape[1:]
144
+ self.input = T.tensor3()
145
+
146
+ if self.inner_rnn == 'gru':
147
+ self.rnn = GRU(
148
+ input_dim=input_dim+self.m_length,
149
+ input_length=input_leng,
150
+ output_dim=self.output_dim, init=self.init,
151
+ inner_init=self.inner_init)
152
+ elif self.inner_rnn == 'lstm':
153
+ self.rnn = LSTM(
154
+ input_dim=input_dim+self.m_length,
155
+ input_length=input_leng,
156
+ output_dim=self.output_dim, init=self.init,
157
+ inner_init=self.inner_init)
158
+ else:
159
+ raise ValueError('this inner_rnn is not implemented yet.')
160
+
161
+ self.rnn.build()
162
+
163
+ # initial memory, state, read and write vecotrs
164
+ self.M = theano.shared((.001*np.ones((1,)).astype(floatX)))
165
+ self.init_h = shared_zeros((self.output_dim))
166
+ self.init_wr = self.rnn.init((self.n_slots,))
167
+ self.init_ww = self.rnn.init((self.n_slots,))
168
+
169
+ # write
170
+ self.W_e = self.rnn.init((self.output_dim, self.m_length)) # erase
171
+ self.b_e = shared_zeros((self.m_length))
172
+ self.W_a = self.rnn.init((self.output_dim, self.m_length)) # add
173
+ self.b_a = shared_zeros((self.m_length))
174
+
175
+ # get_w parameters for reading operation
176
+ self.W_k_read = self.rnn.init((self.output_dim, self.m_length))
177
+ self.b_k_read = self.rnn.init((self.m_length, ))
178
+ self.W_c_read = self.rnn.init((self.output_dim, 3)) # 3 = beta, g, gamma see eq. 5, 7, 9 in Graves et. al 2014
179
+ self.b_c_read = shared_zeros((3))
180
+ self.W_s_read = self.rnn.init((self.output_dim, self.shift_range))
181
+ self.b_s_read = shared_zeros((self.shift_range))
182
+
183
+ # get_w parameters for writing operation
184
+ self.W_k_write = self.rnn.init((self.output_dim, self.m_length))
185
+ self.b_k_write = self.rnn.init((self.m_length, ))
186
+ self.W_c_write = self.rnn.init((self.output_dim, 3)) # 3 = beta, g, gamma see eq. 5, 7, 9
187
+ self.b_c_write = shared_zeros((3))
188
+ self.W_s_write = self.rnn.init((self.output_dim, self.shift_range))
189
+ self.b_s_write = shared_zeros((self.shift_range))
190
+
191
+ self.C = _circulant(self.n_slots, self.shift_range)
192
+
193
+ self.params = self.rnn.params + [
194
+ self.W_e, self.b_e,
195
+ self.W_a, self.b_a,
196
+ self.W_k_read, self.b_k_read,
197
+ self.W_c_read, self.b_c_read,
198
+ self.W_s_read, self.b_s_read,
199
+ self.W_k_write, self.b_k_write,
200
+ self.W_s_write, self.b_s_write,
201
+ self.W_c_write, self.b_c_write,
202
+ self.M,
203
+ self.init_h, self.init_wr, self.init_ww]
204
+
205
+ if self.inner_rnn == 'lstm':
206
+ self.init_c = shared_zeros((self.output_dim))
207
+ self.params = self.params + [self.init_c, ]
208
+
209
+ def _read(self, w, M):
210
+ return (w[:, :, None]*M).sum(axis=1)
211
+
212
+ def _write(self, w, e, a, M, mask):
213
+ Mtilda = M * (1 - w[:, :, None]*e[:, None, :])
214
+ Mout = Mtilda + w[:, :, None]*a[:, None, :]
215
+ return mask[:, None, None]*Mout + (1-mask[:, None, None])*M
216
+
217
+ def _get_content_w(self, beta, k, M):
218
+ num = beta[:, None] * _cosine_distance(M, k)
219
+ return _softmax(num)
220
+
221
+ def _get_location_w(self, g, s, C, gamma, wc, w_tm1, mask):
222
+ wg = g[:, None] * wc + (1-g[:, None])*w_tm1
223
+ Cs = (C[None, :, :, :] * wg[:, None, None, :]).sum(axis=3)
224
+ wtilda = (Cs * s[:, :, None]).sum(axis=1)
225
+ wout = _renorm(wtilda ** gamma[:, None])
226
+ return mask[:, None] * wout + (1-mask[:, None])*w_tm1
227
+
228
+ def _get_controller_output(self, h, W_k, b_k, W_c, b_c, W_s, b_s):
229
+ k = T.tanh(T.dot(h, W_k) + b_k) # + 1e-6
230
+ c = T.dot(h, W_c) + b_c
231
+ beta = T.nnet.relu(c[:, 0]) + 1e-6
232
+ g = T.nnet.sigmoid(c[:, 1])
233
+ gamma = T.nnet.relu(c[:, 2]) + 1
234
+ s = T.nnet.softmax(T.dot(h, W_s) + b_s)
235
+ return k, beta, g, gamma, s
236
+
237
+ def _get_initial_states(self, batch_size):
238
+ init_M = self.M.dimshuffle(0, 'x', 'x').repeat(
239
+ batch_size, axis=0).repeat(self.n_slots, axis=1).repeat(
240
+ self.m_length, axis=2)
241
+
242
+ init_h = self.init_h.dimshuffle(('x', 0)).repeat(batch_size, axis=0)
243
+ init_wr = self.init_wr.dimshuffle(('x', 0)).repeat(batch_size, axis=0)
244
+ init_ww = self.init_ww.dimshuffle(('x', 0)).repeat(batch_size, axis=0)
245
+ if self.inner_rnn == 'lstm':
246
+ init_c = self.init_c.dimshuffle(('x', 0)).repeat(batch_size, axis=0)
247
+ return init_M, T.nnet.softmax(init_wr), T.nnet.softmax(init_ww), init_h, init_c
248
+ else:
249
+ return init_M, T.nnet.softmax(init_wr), T.nnet.softmax(init_ww), init_h
250
+
251
+ def _step(self, x, mask, M_tm1, wr_tm1, ww_tm1, *args):
252
+ # read
253
+ if self.inner_rnn == 'lstm':
254
+ h_tm1 = args[0:2][::-1] # (cell_tm1, h_tm1)
255
+ else:
256
+ h_tm1 = args[0:1] # (h_tm1, )
257
+ k_read, beta_read, g_read, gamma_read, s_read = self._get_controller_output(
258
+ h_tm1[-1], self.W_k_read, self.b_k_read, self.W_c_read, self.b_c_read,
259
+ self.W_s_read, self.b_s_read)
260
+ wc_read = self._get_content_w(beta_read, k_read, M_tm1)
261
+ wr_t = self._get_location_w(g_read, s_read, self.C, gamma_read,
262
+ wc_read, wr_tm1, mask)
263
+ M_read = self._read(wr_t, M_tm1)
264
+
265
+ # update controller
266
+ h_t = _update_controller(self, x, h_tm1, M_read, mask)
267
+
268
+ # write
269
+ k_write, beta_write, g_write, gamma_write, s_write = self._get_controller_output(
270
+ h_t[-1], self.W_k_write, self.b_k_write, self.W_c_write,
271
+ self.b_c_write, self.W_s_write, self.b_s_write)
272
+ wc_write = self._get_content_w(beta_write, k_write, M_tm1)
273
+ ww_t = self._get_location_w(g_write, s_write, self.C, gamma_write,
274
+ wc_write, ww_tm1, mask)
275
+ e = T.nnet.sigmoid(T.dot(h_t[-1], self.W_e) + self.b_e)
276
+ a = T.tanh(T.dot(h_t[-1], self.W_a) + self.b_a)
277
+ M_t = self._write(ww_t, e, a, M_tm1, mask)
278
+
279
+ return (M_t, wr_t, ww_t) + h_t
280
+
281
+ def get_output(self, train=False):
282
+ outputs = self.get_full_output(train)
283
+
284
+ if self.return_sequences:
285
+ return outputs[-1]
286
+ else:
287
+ return outputs[-1][:, -1]
288
+
289
+ @property
290
+ def output_shape(self):
291
+ input_shape = self.input_shape
292
+ if self.return_sequences:
293
+ return input_shape[0], input_shape[1], self.output_dim
294
+ else:
295
+ return input_shape[0], self.output_dim
296
+
297
+ def get_full_output(self, train=False):
298
+ """
299
+ This method is for research and visualization purposes. Use it as:
300
+ X = model.get_input() # full model
301
+ Y = ntm.get_output() # this layer
302
+ F = theano.function([X], Y, allow_input_downcast=True)
303
+ [memory, read_address, write_address, rnn_state] = F(x)
304
+
305
+ if inner_rnn == "lstm" use it as:
306
+ [memory, read_address, write_address, rnn_cell, rnn_state] = F(x)
307
+
308
+ """
309
+ X = self.get_input(train)
310
+ padded_mask = self.get_padded_shuffled_mask(train, X, pad=1)[:, :, 0]
311
+ X = X.dimshuffle((1, 0, 2))
312
+
313
+ init_states = self._get_initial_states(X.shape[1])
314
+ outputs, updates = theano.scan(self._step,
315
+ sequences=[X, padded_mask],
316
+ outputs_info=init_states,
317
+ non_sequences=self.params,
318
+ truncate_gradient=self.truncate_gradient)
319
+
320
+ out = [outputs[0].dimshuffle((1, 0, 2, 3)),
321
+ outputs[1].dimshuffle(1, 0, 2),
322
+ outputs[2].dimshuffle((1, 0, 2)),
323
+ outputs[3].dimshuffle((1, 0, 2))]
324
+ if self.inner_rnn == 'lstm':
325
+ out + [outputs[4].dimshuffle((1, 0, 2))]
326
+ return out
keras/layers/ntm.pyc ADDED
Binary file