|
| 1 | + |
| 2 | +import tensorflow as tf |
| 3 | + |
| 4 | +class CRNNCell(object): |
| 5 | + """CRNN cell. |
| 6 | + """ |
| 7 | + |
| 8 | + def __call__(self, inputs, state, scope=None): |
| 9 | + """Run this RNN cell on inputs, starting from the inputted state. |
| 10 | + """ |
| 11 | + raise NotImplementedError("Abstract method") |
| 12 | + |
| 13 | + @property |
| 14 | + def state_size(self): |
| 15 | + """sizes of states used by cell. |
| 16 | + """ |
| 17 | + raise NotImplementedError("Abstract method") |
| 18 | + |
| 19 | + @property |
| 20 | + def output_size(self): |
| 21 | + """Integer or TensorShape: size of outputs produced by cell.""" |
| 22 | + raise NotImplementedError("Abstract method") |
| 23 | + |
| 24 | + def set_zero_state(self, batch_size, dtype): |
| 25 | + """Return zero-filled state tensor(s). |
| 26 | + Args: |
| 27 | + batch_size: int, float, or unit Tensor representing batch size. |
| 28 | + dtype: data type for the state. |
| 29 | + Returns: |
| 30 | + tensor with shape '[batch_size x shape[0] x shape[1] x features] |
| 31 | + filled with zeros |
| 32 | + """ |
| 33 | + |
| 34 | + shape = self.shape |
| 35 | + features = self.features |
| 36 | + zeros = tf.zeros([batch_size, shape[0], shape[1], features * 2]) |
| 37 | + return zeros |
| 38 | + |
| 39 | +class clstm(CRNNCell): |
| 40 | + """CNN LSTM network's single cell. |
| 41 | + """ |
| 42 | + |
| 43 | +# https://github.com/tensorflow/tensorflow/blob/master/tensorflow/contrib/rnn/python/ops/core_rnn_cell_impl.py |
| 44 | + |
| 45 | + def __init__(self, shape, filter_size, features, forget_bias=1.0, input_size=None, |
| 46 | + state_is_tuple=False, activation=tf.nn.tanh): |
| 47 | + """Initialize the basic CLSTM cell. |
| 48 | + Args: |
| 49 | + shape: int tuple of the height and width of the cell |
| 50 | + filter_size: int tuple of the height and width of the filter |
| 51 | + features: int of the depth of the cell |
| 52 | + forget_bias: float, the bias added to forget gates (see above). |
| 53 | + input_size: Deprecated. |
| 54 | + state_is_tuple: If True, accepted and returned states are 2-tuples of |
| 55 | + the `c_state` and `m_state`. If False, they are concatenated |
| 56 | + along the column axis. Soon deprecated. |
| 57 | + activation: Activation function of inner states. |
| 58 | + """ |
| 59 | + if input_size is not None: |
| 60 | + logging.warn("%s: Input_size parameter is deprecated.", self) |
| 61 | + self.shape = shape |
| 62 | + self.filter_size = filter_size |
| 63 | + self.features = features |
| 64 | + self._forget_bias = forget_bias |
| 65 | + self._state_is_tuple = state_is_tuple |
| 66 | + self._activation = activation |
| 67 | + |
| 68 | + @property |
| 69 | + def state_size(self): |
| 70 | + return (LSTMStateTuple(self._num_units, self._num_units) |
| 71 | + if self._state_is_tuple else 2 * self._num_units) |
| 72 | + |
| 73 | + @property |
| 74 | + def output_size(self): |
| 75 | + return self._num_units |
| 76 | + |
| 77 | + def __call__(self, inputs, state, scope=None): |
| 78 | + """Long short-term memory cell (LSTM).""" |
| 79 | + with tf.variable_scope(scope or type(self).__name__): |
| 80 | + # Parameters of gates are concatenated into one multiply for efficiency. |
| 81 | + if self._state_is_tuple: |
| 82 | + c, h = state |
| 83 | + else: |
| 84 | + c, h = tf.split(3, 2, state) |
| 85 | + concat = _convolve_linear([inputs, h], self.filter_size, self.features * 4, True) |
| 86 | + |
| 87 | + # i = input_gate, j = new_input, f = forget_gate, o = output_gate |
| 88 | + i, j, f, o = tf.split(3, 4, concat) |
| 89 | + |
| 90 | + new_c = (c * tf.nn.sigmoid(f + self._forget_bias) + tf.nn.sigmoid(i) * |
| 91 | + self._activation(j)) |
| 92 | + new_h = self._activation(new_c) * tf.nn.sigmoid(o) |
| 93 | + |
| 94 | + if self._state_is_tuple: |
| 95 | + new_state = LSTMStateTuple(new_c, new_h) |
| 96 | + else: |
| 97 | + new_state = tf.concat(3, [new_c, new_h]) |
| 98 | + return new_h, new_state |
| 99 | + |
| 100 | +def _convolve_linear(args, filter_size, features, bias, bias_start=0.0, scope=None): |
| 101 | + """convolution: |
| 102 | + Args: |
| 103 | + args: 4D Tensor or list of 4D, batch x n, Tensors. |
| 104 | + filter_size: int tuple of filter with height and width. |
| 105 | + features: int, as number of features. |
| 106 | + bias_start: starting value to initialize bias; 0 by default. |
| 107 | + scope: VariableScope for created subgraph; defaults to "Linear". |
| 108 | + Returns: |
| 109 | + 4D Tensor with shape [batch h w features] |
| 110 | + Raises: |
| 111 | + ValueError: if some of arguments have unspecified or wrong shape. |
| 112 | + """ |
| 113 | + |
| 114 | + # Calculate total size of arguments on dimension 1. |
| 115 | + total_arg_size_depth = 0 |
| 116 | + shapes = [a.get_shape().as_list() for a in args] |
| 117 | + for shape in shapes: |
| 118 | + if len(shape) != 4: |
| 119 | + raise ValueError("Linear needs 4D arguments: %s" % str(shapes)) |
| 120 | + if not shape[3]: |
| 121 | + raise ValueError("Linear needs shape[4] of arguments: %s" % str(shapes)) |
| 122 | + else: |
| 123 | + total_arg_size_depth += shape[3] |
| 124 | + |
| 125 | + dtype = [a.dtype for a in args][0] |
| 126 | + |
| 127 | + # Computation |
| 128 | + with tf.variable_scope(scope or "Conv"): |
| 129 | + mat = tf.get_variable( |
| 130 | + "Mat", [filter_size[0], filter_size[1], total_arg_size_depth, features], dtype=dtype) |
| 131 | + if len(args) == 1: |
| 132 | + res = tf.nn.conv2d(args[0], mat, strides=[1, 1, 1, 1], padding='SAME') |
| 133 | + else: |
| 134 | + res = tf.nn.conv2d(tf.concat(3, args), mat, strides=[1, 1, 1, 1], padding='SAME') |
| 135 | + if not bias: |
| 136 | + return res |
| 137 | + bias_term = tf.get_variable( |
| 138 | + "Bias", [features], |
| 139 | + dtype=dtype, |
| 140 | + initializer=tf.constant_initializer( |
| 141 | + bias_start, dtype=dtype)) |
| 142 | + return res + bias_term |
| 143 | + |
0 commit comments