Tensorflow中RNN以及衍生RNN的源码

  1. # Copyright 2015 Google Inc. All Rights Reserved.  
  2. #  
  3. # Licensed under the Apache License, Version 2.0 (the "License");  
  4. # you may not use this file except in compliance with the License.  
  5. # You may obtain a copy of the License at  
  6. #  
  7. #     http://www.apache.org/licenses/LICENSE-2.0  
  8. #  
  9. # Unless required by applicable law or agreed to in writing, software  
  10. # distributed under the License is distributed on an "AS IS" BASIS,  
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  
  12. # See the License for the specific language governing permissions and  
  13. # limitations under the License.  
  14. # ==============================================================================  
  15.   
  16. """RNN helpers for TensorFlow models."""  
  17.   
  18. from __future__ import absolute_import  
  19. from __future__ import division  
  20. from __future__ import print_function  
  21.   
  22. from tensorflow.python.framework import dtypes  
  23. from tensorflow.python.framework import ops  
  24. from tensorflow.python.framework import tensor_shape  
  25. from tensorflow.python.framework import tensor_util  
  26. from tensorflow.python.ops import array_ops  
  27. from tensorflow.python.ops import control_flow_ops  
  28. from tensorflow.python.ops import logging_ops  
  29. from tensorflow.python.ops import math_ops  
  30. from tensorflow.python.ops import rnn_cell  
  31. from tensorflow.python.ops import tensor_array_ops  
  32. from tensorflow.python.ops import variable_scope as vs  
  33.   
  34.   
  35. def rnn(cell, inputs, initial_state=None, dtype=None,  
  36.         sequence_length=None, scope=None):  
  37.   """Creates a recurrent neural network specified by RNNCell "cell". 
  38.  
  39.   The simplest form of RNN network generated is: 
  40.     state = cell.zero_state(...) 
  41.     outputs = [] 
  42.     for input_ in inputs: 
  43.       output, state = cell(input_, state) 
  44.       outputs.append(output) 
  45.     return (outputs, state) 
  46.  
  47.   However, a few other options are available: 
  48.  
  49.   An initial state can be provided. 
  50.   If the sequence_length vector is provided, dynamic calculation is performed. 
  51.   This method of calculation does not compute the RNN steps past the maximum 
  52.   sequence length of the minibatch (thus saving computational time), 
  53.   and properly propagates the state at an example's sequence length 
  54.   to the final state output. 
  55.  
  56.   The dynamic calculation performed is, at time t for batch row b, 
  57.     (output, state)(b, t) = 
  58.       (t >= sequence_length(b)) 
  59.         ? (zeros(cell.output_size), states(b, sequence_length(b) - 1)) 
  60.         : cell(input(b, t), state(b, t - 1)) 
  61.  
  62.   Args: 
  63.     cell: An instance of RNNCell. 
  64.     inputs: A length T list of inputs, each a tensor of shape 
  65.       [batch_size, input_size]. 
  66.     initial_state: (optional) An initial state for the RNN.  This must be 
  67.       a tensor of appropriate type and shape [batch_size x cell.state_size]. 
  68.     dtype: (optional) The data type for the initial state.  Required if 
  69.       initial_state is not provided. 
  70.     sequence_length: Specifies the length of each sequence in inputs. 
  71.       An int32 or int64 vector (tensor) size [batch_size].  Values in [0, T). 
  72.     scope: VariableScope for the created subgraph; defaults to "RNN". 
  73.  
  74.   Returns: 
  75.     A pair (outputs, state) where: 
  76.       outputs is a length T list of outputs (one for each input) 
  77.       state is the final state 
  78.  
  79.   Raises: 
  80.     TypeError: If "cell" is not an instance of RNNCell. 
  81.     ValueError: If inputs is None or an empty list, or if the input depth 
  82.       cannot be inferred from inputs via shape inference. 
  83.   """  
  84.   
  85.   if not isinstance(cell, rnn_cell.RNNCell):  
  86.     raise TypeError("cell must be an instance of RNNCell")  
  87.   if not isinstance(inputs, list):  
  88.     raise TypeError("inputs must be a list")  
  89.   if not inputs:  
  90.     raise ValueError("inputs must not be empty")  
  91.   
  92.   outputs = []  
  93.   # Create a new scope in which the caching device is either  
  94.   # determined by the parent scope, or is set to place the cached  
  95.   # Variable using the same placement as for the rest of the RNN.  
  96.   with vs.variable_scope(scope or "RNN") as varscope:  
  97.     if varscope.caching_device is None:  
  98.       varscope.set_caching_device(lambda op: op.device)  
  99.   
  100.     # Temporarily avoid EmbeddingWrapper and seq2seq badness  
  101.     # TODO(lukaszkaiser): remove EmbeddingWrapper  
  102.     if inputs[0].get_shape().ndims != 1:  
  103.       (fixed_batch_size, input_size) = inputs[0].get_shape().with_rank(2)  
  104.       if input_size.value is None:  
  105.         raise ValueError(  
  106.             "Input size (second dimension of inputs[0]) must be accessible via "  
  107.             "shape inference, but saw value None.")  
  108.     else:  
  109.       fixed_batch_size = inputs[0].get_shape().with_rank_at_least(1)[0]  
  110.   
  111.     if fixed_batch_size.value:  
  112.       batch_size = fixed_batch_size.value  
  113.     else:  
  114.       batch_size = array_ops.shape(inputs[0])[0]  
  115.     if initial_state is not None:  
  116.       state = initial_state  
  117.     else:  
  118.       if not dtype:  
  119.         raise ValueError("If no initial_state is provided, dtype must be.")  
  120.       state = cell.zero_state(batch_size, dtype)  
  121.   
  122.     if sequence_length is not None:  # Prepare variables  
  123.       sequence_length = math_ops.to_int32(sequence_length)  
  124.       zero_output = array_ops.zeros(  
  125.           array_ops.pack([batch_size, cell.output_size]), inputs[0].dtype)  
  126.       zero_output.set_shape(  
  127.           tensor_shape.TensorShape([fixed_batch_size.value, cell.output_size]))  
  128.       min_sequence_length = math_ops.reduce_min(sequence_length)  
  129.       max_sequence_length = math_ops.reduce_max(sequence_length)  
  130.   
  131.     for time, input_ in enumerate(inputs):  
  132.       if time > 0: vs.get_variable_scope().reuse_variables()  
  133.       # pylint: disable=cell-var-from-loop  
  134.       call_cell = lambda: cell(input_, state)  
  135.       # pylint: enable=cell-var-from-loop  
  136.       if sequence_length is not None:  
  137.         (output, state) = _rnn_step(  
  138.             time, sequence_length, min_sequence_length, max_sequence_length,  
  139.             zero_output, state, call_cell)  
  140.       else:  
  141.         (output, state) = call_cell()  
  142.   
  143.       outputs.append(output)  
  144.   
  145.     return (outputs, state)  
  146.   
  147.   
  148. def state_saving_rnn(cell, inputs, state_saver, state_name,  
  149.                      sequence_length=None, scope=None):  
  150.   """RNN that accepts a state saver for time-truncated RNN calculation. 
  151.  
  152.   Args: 
  153.     cell: An instance of RNNCell. 
  154.     inputs: A length T list of inputs, each a tensor of shape 
  155.       [batch_size, input_size]. 
  156.     state_saver: A state saver object with methods `state` and `save_state`. 
  157.     state_name: The name to use with the state_saver. 
  158.     sequence_length: (optional) An int32/int64 vector size [batch_size]. 
  159.       See the documentation for rnn() for more details about sequence_length. 
  160.     scope: VariableScope for the created subgraph; defaults to "RNN". 
  161.  
  162.   Returns: 
  163.     A pair (outputs, state) where: 
  164.       outputs is a length T list of outputs (one for each input) 
  165.       states is the final state 
  166.  
  167.   Raises: 
  168.     TypeError: If "cell" is not an instance of RNNCell. 
  169.     ValueError: If inputs is None or an empty list. 
  170.   """  
  171.   initial_state = state_saver.state(state_name)  
  172.   (outputs, state) = rnn(cell, inputs, initial_state=initial_state,  
  173.                          sequence_length=sequence_length, scope=scope)  
  174.   save_state = state_saver.save_state(state_name, state)  
  175.   with ops.control_dependencies([save_state]):  
  176.     outputs[-1] = array_ops.identity(outputs[-1])  
  177.   
  178.   return (outputs, state)  
  179.   
  180.   
  181. def _rnn_step(  
  182.     time, sequence_length, min_sequence_length, max_sequence_length,  
  183.     zero_output, state, call_cell, skip_conditionals=False):  
  184.   """Calculate one step of a dynamic RNN minibatch. 
  185.  
  186.   Returns an (output, state) pair conditioned on the sequence_lengths. 
  187.   When skip_conditionals=False, the pseudocode is something like: 
  188.  
  189.   if t >= max_sequence_length: 
  190.     return (zero_output, state) 
  191.   if t < min_sequence_length: 
  192.     return call_cell() 
  193.  
  194.   # Selectively output zeros or output, old state or new state depending 
  195.   # on if we've finished calculating each row. 
  196.   new_output, new_state = call_cell() 
  197.   final_output = np.vstack([ 
  198.     zero_output if time >= sequence_lengths[r] else new_output_r 
  199.     for r, new_output_r in enumerate(new_output) 
  200.   ]) 
  201.   final_state = np.vstack([ 
  202.     state[r] if time >= sequence_lengths[r] else new_state_r 
  203.     for r, new_state_r in enumerate(new_state) 
  204.   ]) 
  205.   return (final_output, final_state) 
  206.  
  207.   Args: 
  208.     time: Python int, the current time step 
  209.     sequence_length: int32 `Tensor` vector of size [batch_size] 
  210.     min_sequence_length: int32 `Tensor` scalar, min of sequence_length 
  211.     max_sequence_length: int32 `Tensor` scalar, max of sequence_length 
  212.     zero_output: `Tensor` vector of shape [output_size] 
  213.     state: `Tensor` matrix of shape [batch_size, state_size] 
  214.     call_cell: lambda returning tuple of (new_output, new_state) where 
  215.       new_output is a `Tensor` matrix of shape [batch_size, output_size] 
  216.       new_state is a `Tensor` matrix of shape [batch_size, state_size] 
  217.     skip_conditionals: Python bool, whether to skip using the conditional 
  218.       calculations.  This is useful for dynamic_rnn, where the input tensor 
  219.       matches max_sequence_length, and using conditionals just slows 
  220.       everything down. 
  221.  
  222.   Returns: 
  223.     A tuple of (final_output, final_state) as given by the pseudocode above: 
  224.       final_output is a `Tensor` matrix of shape [batch_size, output_size] 
  225.       final_state is a `Tensor` matrix of shape [batch_size, state_size] 
  226.   """  
  227.   state_shape = state.get_shape()  
  228.   
  229.   def _copy_some_through(new_output, new_state):  
  230.     # Use broadcasting select to determine which values should get  
  231.     # the previous state & zero output, and which values should get  
  232.     # a calculated state & output.  
  233.     copy_cond = (time >= sequence_length)  
  234.     return (math_ops.select(copy_cond, zero_output, new_output),  
  235.             math_ops.select(copy_cond, state, new_state))  
  236.   
  237.   def _maybe_copy_some_through():  
  238.     """Run RNN step.  Pass through either no or some past state."""  
  239.     new_output, new_state = call_cell()  
  240.   
  241.     return control_flow_ops.cond(  
  242.         # if t < min_seq_len: calculate and return everything  
  243.         time < min_sequence_length, lambda: (new_output, new_state),  
  244.         # else copy some of it through  
  245.         lambda: _copy_some_through(new_output, new_state))  
  246.   
  247.   # TODO(ebrevdo): skipping these conditionals may cause a slowdown,  
  248.   # but benefits from removing cond() and its gradient.  We should  
  249.   # profile with and without this switch here.  
  250.   if skip_conditionals:  
  251.     # Instead of using conditionals, perform the selective copy at all time  
  252.     # steps.  This is faster when max_seq_len is equal to the number of unrolls  
  253.     # (which is typical for dynamic_rnn).  
  254.     new_output, new_state = call_cell()  
  255.     (final_output, final_state) = _copy_some_through(new_output, new_state)  
  256.   else:  
  257.     empty_update = lambda: (zero_output, state)  
  258.   
  259.     (final_output, final_state) = control_flow_ops.cond(  
  260.         # if t >= max_seq_len: copy all state through, output zeros  
  261.         time >= max_sequence_length, empty_update,  
  262.         # otherwise calculation is required: copy some or all of it through  
  263.         _maybe_copy_some_through)  
  264.   
  265.   final_output.set_shape(zero_output.get_shape())  
  266.   final_state.set_shape(state_shape)  
  267.   return (final_output, final_state)  
  268.   
  269.   
  270. def _reverse_seq(input_seq, lengths):  
  271.   """Reverse a list of Tensors up to specified lengths. 
  272.  
  273.   Args: 
  274.     input_seq: Sequence of seq_len tensors of dimension (batch_size, depth) 
  275.     lengths:   A tensor of dimension batch_size, containing lengths for each 
  276.                sequence in the batch. If "None" is specified, simply reverses 
  277.                the list. 
  278.  
  279.   Returns: 
  280.     time-reversed sequence 
  281.   """  
  282.   if lengths is None:  
  283.     return list(reversed(input_seq))  
  284.   
  285.   input_shape = tensor_shape.matrix(NoneNone)  
  286.   for input_ in input_seq:  
  287.     input_shape.merge_with(input_.get_shape())  
  288.     input_.set_shape(input_shape)  
  289.   
  290.   # Join into (time, batch_size, depth)  
  291.   s_joined = array_ops.pack(input_seq)  
  292.   
  293.   # TODO(schuster, ebrevdo): Remove cast when reverse_sequence takes int32  
  294.   if lengths is not None:  
  295.     lengths = math_ops.to_int64(lengths)  
  296.   
  297.   # Reverse along dimension 0  
  298.   s_reversed = array_ops.reverse_sequence(s_joined, lengths, 01)  
  299.   # Split again into list  
  300.   result = array_ops.unpack(s_reversed)  
  301.   for r in result:  
  302.     r.set_shape(input_shape)  
  303.   return result  
  304.   
  305.   
  306. def bidirectional_rnn(cell_fw, cell_bw, inputs,  
  307.                       initial_state_fw=None, initial_state_bw=None,  
  308.                       dtype=None, sequence_length=None, scope=None):  
  309.   """Creates a bidirectional recurrent neural network. 
  310.  
  311.   Similar to the unidirectional case above (rnn) but takes input and builds 
  312.   independent forward and backward RNNs with the final forward and backward 
  313.   outputs depth-concatenated, such that the output will have the format 
  314.   [time][batch][cell_fw.output_size + cell_bw.output_size]. The input_size of 
  315.   forward and backward cell must match. The initial state for both directions 
  316.   is zero by default (but can be set optionally) and no intermediate states are 
  317.   ever returned -- the network is fully unrolled for the given (passed in) 
  318.   length(s) of the sequence(s) or completely unrolled if length(s) is not given. 
  319.  
  320.   Args: 
  321.     cell_fw: An instance of RNNCell, to be used for forward direction. 
  322.     cell_bw: An instance of RNNCell, to be used for backward direction. 
  323.     inputs: A length T list of inputs, each a tensor of shape 
  324.       [batch_size, input_size]. 
  325.     initial_state_fw: (optional) An initial state for the forward RNN. 
  326.       This must be a tensor of appropriate type and shape 
  327.       [batch_size x cell.state_size]. 
  328.     initial_state_bw: (optional) Same as for initial_state_fw. 
  329.     dtype: (optional) The data type for the initial state.  Required if either 
  330.       of the initial states are not provided. 
  331.     sequence_length: (optional) An int32/int64 vector, size [batch_size], 
  332.       containing the actual lengths for each of the sequences. 
  333.     scope: VariableScope for the created subgraph; defaults to "BiRNN" 
  334.  
  335.   Returns: 
  336.     A tuple (outputs, output_state_fw, output_state_bw) where: 
  337.       outputs is a length T list of outputs (one for each input), which 
  338.       are depth-concatenated forward and backward outputs 
  339.       output_state_fw is the final state of the forward rnn 
  340.       output_state_bw is the final state of the backward rnn 
  341.  
  342.   Raises: 
  343.     TypeError: If "cell_fw" or "cell_bw" is not an instance of RNNCell. 
  344.     ValueError: If inputs is None or an empty list. 
  345.   """  
  346.   
  347.   if not isinstance(cell_fw, rnn_cell.RNNCell):  
  348.     raise TypeError("cell_fw must be an instance of RNNCell")  
  349.   if not isinstance(cell_bw, rnn_cell.RNNCell):  
  350.     raise TypeError("cell_bw must be an instance of RNNCell")  
  351.   if not isinstance(inputs, list):  
  352.     raise TypeError("inputs must be a list")  
  353.   if not inputs:  
  354.     raise ValueError("inputs must not be empty")  
  355.   
  356.   name = scope or "BiRNN"  
  357.   # Forward direction  
  358.   with vs.variable_scope(name + "_FW") as fw_scope:  
  359.     output_fw, output_state_fw = rnn(cell_fw, inputs, initial_state_fw, dtype,  
  360.                        sequence_length, scope=fw_scope)  
  361.   
  362.   # Backward direction  
  363.   with vs.variable_scope(name + "_BW") as bw_scope:  
  364.     tmp, output_state_bw = rnn(cell_bw, _reverse_seq(inputs, sequence_length),  
  365.                  initial_state_bw, dtype, sequence_length, scope=bw_scope)  
  366.   output_bw = _reverse_seq(tmp, sequence_length)  
  367.   # Concat each of the forward/backward outputs  
  368.   outputs = [array_ops.concat(1, [fw, bw])  
  369.              for fw, bw in zip(output_fw, output_bw)]  
  370.   
  371.   return (outputs, output_state_fw, output_state_bw)  
  372.   
  373.   
  374. def dynamic_rnn(cell, inputs, sequence_length=None, initial_state=None,  
  375.                 dtype=None, parallel_iterations=None, swap_memory=False,  
  376.                 time_major=False, scope=None):  
  377.   """Creates a recurrent neural network specified by RNNCell "cell". 
  378.  
  379.   This function is functionally identical to the function `rnn` above, but 
  380.   performs fully dynamic unrolling of `inputs`. 
  381.  
  382.   Unlike `rnn`, the input `inputs` is not a Python list of `Tensors`.  Instead, 
  383.   it is a single `Tensor` where the maximum time is either the first or second 
  384.   dimension (see the parameter `time_major`).  The corresponding output is 
  385.   a single `Tensor` having the same number of time steps and batch size. 
  386.  
  387.   The parameter `sequence_length` is required and dynamic calculation is 
  388.   automatically performed. 
  389.  
  390.   Args: 
  391.     cell: An instance of RNNCell. 
  392.     inputs: The RNN inputs. 
  393.       If time_major == False (default), this must be a tensor of shape: 
  394.         `[batch_size, max_time, input_size]`. 
  395.       If time_major == True, this must be a tensor of shape: 
  396.         `[max_time, batch_size, input_size]`. 
  397.     sequence_length: (optional) An int32/int64 vector sized `[batch_size]`. 
  398.     initial_state: (optional) An initial state for the RNN.  This must be 
  399.       a tensor of appropriate type and shape `[batch_size x cell.state_size]`. 
  400.     dtype: (optional) The data type for the initial state.  Required if 
  401.       initial_state is not provided. 
  402.     parallel_iterations: (Default: 32).  The number of iterations to run in 
  403.       parallel.  Those operations which do not have any temporal dependency 
  404.       and can be run in parallel, will be.  This parameter trades off 
  405.       time for space.  Values >> 1 use more memory but take less time, 
  406.       while smaller values use less memory but computations take longer. 
  407.     swap_memory: Swap the tensors produced in forward inference but needed 
  408.       for back prop from GPU to CPU. 
  409.     time_major: The shape format of the `inputs` and `outputs` Tensors. 
  410.       If true, these `Tensors` must be shaped `[max_time, batch_size, depth]`. 
  411.       If false, these `Tensors` must be shaped `[batch_size, max_time, depth]`. 
  412.       Using time_major = False is a bit more efficient because it avoids 
  413.       transposes at the beginning and end of the RNN calculation.  However, 
  414.       most TensorFlow data is batch-major, so by default this function 
  415.       accepts input and emits output in batch-major form. 
  416.     scope: VariableScope for the created subgraph; defaults to "RNN". 
  417.  
  418.   Returns: 
  419.     A pair (outputs, state) where: 
  420.       outputs: The RNN output `Tensor`. 
  421.         If time_major == False (default), this will be a `Tensor` shaped: 
  422.           `[batch_size, max_time, cell.output_size]`. 
  423.         If time_major == True, this will be a `Tensor` shaped: 
  424.           `[max_time, batch_size, cell.output_size]`. 
  425.       state: The final state, shaped: 
  426.         `[batch_size, cell.state_size]`. 
  427.  
  428.   Raises: 
  429.     TypeError: If "cell" is not an instance of RNNCell. 
  430.     ValueError: If inputs is None or an empty list. 
  431.   """  
  432.   
  433.   if not isinstance(cell, rnn_cell.RNNCell):  
  434.     raise TypeError("cell must be an instance of RNNCell")  
  435.   
  436.   # By default, time_major==False and inputs are batch-major: shaped  
  437.   #   [batch, time, depth]  
  438.   # For internal calculations, we transpose to [time, batch, depth]  
  439.   if not time_major:  
  440.     inputs = array_ops.transpose(inputs, [102])  # (B,T,D) => (T,B,D)  
  441.   
  442.   parallel_iterations = parallel_iterations or 32  
  443.   if sequence_length is not None:  
  444.     sequence_length = math_ops.to_int32(sequence_length)  
  445.     sequence_length = array_ops.identity(  # Just to find it in the graph.  
  446.         sequence_length, name="sequence_length")  
  447.   
  448.   # Create a new scope in which the caching device is either  
  449.   # determined by the parent scope, or is set to place the cached  
  450.   # Variable using the same placement as for the rest of the RNN.  
  451.   with vs.variable_scope(scope or "RNN") as varscope:  
  452.     if varscope.caching_device is None:  
  453.       varscope.set_caching_device(lambda op: op.device)  
  454.     input_shape = array_ops.shape(inputs)  
  455.     batch_size = input_shape[1]  
  456.   
  457.     if initial_state is not None:  
  458.       state = initial_state  
  459.     else:  
  460.       if not dtype:  
  461.         raise ValueError("If no initial_state is provided, dtype must be.")  
  462.       state = cell.zero_state(batch_size, dtype)  
  463.   
  464.     def _assert_has_shape(x, shape):  
  465.       x_shape = array_ops.shape(x)  
  466.       packed_shape = array_ops.pack(shape)  
  467.       return logging_ops.Assert(  
  468.           math_ops.reduce_all(math_ops.equal(x_shape, packed_shape)),  
  469.           ["Expected shape for Tensor %s is " % x.name,  
  470.            packed_shape, " but saw shape: ", x_shape])  
  471.   
  472.     if sequence_length is not None:  
  473.       # Perform some shape validation  
  474.       with ops.control_dependencies(  
  475.           [_assert_has_shape(sequence_length, [batch_size])]):  
  476.         sequence_length = array_ops.identity(  
  477.             sequence_length, name="CheckSeqLen")  
  478.   
  479.     (outputs, final_state) = _dynamic_rnn_loop(  
  480.         cell, inputs, state, parallel_iterations=parallel_iterations,  
  481.         swap_memory=swap_memory, sequence_length=sequence_length)  
  482.   
  483.     # Outputs of _dynamic_rnn_loop are always shaped [time, batch, depth].  
  484.     # If we are performing batch-major calculations, transpose output back  
  485.     # to shape [batch, time, depth]  
  486.     if not time_major:  
  487.       outputs = array_ops.transpose(outputs, [102])  # (T,B,D) => (B,T,D)  
  488.   
  489.     return (outputs, final_state)  
  490.   
  491.   
  492. def _dynamic_rnn_loop(  
  493.     cell, inputs, initial_state, parallel_iterations, swap_memory,  
  494.     sequence_length=None):  
  495.   """Internal implementation of Dynamic RNN. 
  496.  
  497.   Args: 
  498.     cell: An instance of RNNCell. 
  499.     inputs: A `Tensor` of shape [time, batch_size, depth]. 
  500.     initial_state: A `Tensor` of shape [batch_size, depth]. 
  501.     parallel_iterations: Positive Python int. 
  502.     swap_memory: A Python boolean 
  503.     sequence_length: (optional) An `int32` `Tensor` of shape [batch_size]. 
  504.  
  505.   Returns: 
  506.     Tuple (final_outputs, final_state). 
  507.     final_outputs: 
  508.       A `Tensor` of shape [time, batch_size, depth]`. 
  509.     final_state: 
  510.       A `Tensor` of shape [batch_size, depth]. 
  511.  
  512.   Raises: 
  513.     ValueError: If the input depth cannot be inferred via shape inference 
  514.       from the inputs. 
  515.   """  
  516.   state = initial_state  
  517.   assert isinstance(parallel_iterations, int), "parallel_iterations must be int"  
  518.   
  519.   # Construct an initial output  
  520.   input_shape = array_ops.shape(inputs)  
  521.   (time_steps, batch_size, _) = array_ops.unpack(input_shape, 3)  
  522.   
  523.   inputs_got_shape = inputs.get_shape().with_rank(3)  
  524.   (const_time_steps, const_batch_size, const_depth) = inputs_got_shape.as_list()  
  525.   
  526.   if const_depth is None:  
  527.     raise ValueError(  
  528.         "Input size (depth of inputs) must be accessible via shape inference, "  
  529.         "but saw value None.")  
  530.   
  531.   # Prepare dynamic conditional copying of state & output  
  532.   zero_output = array_ops.zeros(  
  533.       array_ops.pack([batch_size, cell.output_size]), inputs.dtype)  
  534.   if sequence_length is not None:  
  535.     min_sequence_length = math_ops.reduce_min(sequence_length)  
  536.     max_sequence_length = math_ops.reduce_max(sequence_length)  
  537.   
  538.   time = array_ops.constant(0, dtype=dtypes.int32, name="time")  
  539.   
  540.   with ops.op_scope([], "dynamic_rnn") as scope:  
  541.     base_name = scope  
  542.   
  543.   output_ta = tensor_array_ops.TensorArray(  
  544.       dtype=inputs.dtype, size=time_steps,  
  545.       tensor_array_name=base_name + "output")  
  546.   
  547.   input_ta = tensor_array_ops.TensorArray(  
  548.       dtype=inputs.dtype, size=time_steps,  
  549.       tensor_array_name=base_name + "input")  
  550.   
  551.   input_ta = input_ta.unpack(inputs)  
  552.   
  553.   def _time_step(time, state, output_ta_t):  
  554.     """Take a time step of the dynamic RNN. 
  555.  
  556.     Args: 
  557.       time: int32 scalar Tensor. 
  558.       state: Vector. 
  559.       output_ta_t: `TensorArray`, the output with existing flow. 
  560.  
  561.     Returns: 
  562.       The tuple (time + 1, new_state, output_ta_t with updated flow). 
  563.     """  
  564.   
  565.     input_t = input_ta.read(time)  
  566.     # Restore some shape information  
  567.     input_t.set_shape([const_batch_size, const_depth])  
  568.   
  569.     call_cell = lambda: cell(input_t, state)  
  570.   
  571.     if sequence_length is not None:  
  572.       (output, new_state) = _rnn_step(  
  573.           time=time,  
  574.           sequence_length=sequence_length,  
  575.           min_sequence_length=min_sequence_length,  
  576.           max_sequence_length=max_sequence_length,  
  577.           zero_output=zero_output,  
  578.           state=state,  
  579.           call_cell=call_cell,  
  580.           skip_conditionals=True)  
  581.     else:  
  582.       (output, new_state) = call_cell()  
  583.   
  584.     output_ta_t = output_ta_t.write(time, output)  
  585.   
  586.     return (time + 1, new_state, output_ta_t)  
  587.   
  588.   (_, final_state, output_final_ta) = control_flow_ops.while_loop(  
  589.       cond=lambda time, _1, _2: time < time_steps,  
  590.       body=_time_step,  
  591.       loop_vars=(time, state, output_ta),  
  592.       parallel_iterations=parallel_iterations,  
  593.       swap_memory=swap_memory)  
  594.   
  595.   final_outputs = output_final_ta.pack()  
  596.   # Restore some shape information  
  597.   final_outputs.set_shape([  
  598.       const_time_steps, const_batch_size, cell.output_size])  
  599.   
  600.   return (final_outputs, final_state)  
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值