
Xc           @   s  d  d l  Z d  d l m Z d  d l m Z d  d l m Z d  d l m Z d  d l m Z	 d  d l
 m Z d  d l Z d  d l Z d  d l Z d d	 l m Z d d
 l m Z d d l m Z d d l m Z m Z e Z e Z d a i  a i  a e a d d  Z  d   Z! d   Z" d   Z# d   Z$ d   Z% d   Z& d   Z' d   Z( d   Z) d   Z* d   Z+ e j, Z, d d d  Z- d   Z. d d d d  Z/ d d d e d d  Z0 d   Z1 d   Z2 d    Z3 d!   Z4 d"   Z5 d d d#  Z6 d d d$  Z7 d d d%  Z8 d d d&  Z9 d d d'  Z: d d d d(  Z; d d d d)  Z< d*   Z= d+   Z> d,   Z? d-   Z@ d.   ZA d/   ZB d0   ZC d d1  ZD d2   ZE d3   ZF d4   ZG d e d5  ZH d e d6  ZI d e d7  Z d e d8  ZJ d e d9  ZK d e d:  ZL d e d;  ZM d e d<  ZN d e d=  Z d  d>  ZO d  d?  ZP d@   ZQ dA   ZR dB   ZS dC   ZT dD   ZU dE   ZV dF   ZW dG   ZX dH   ZY dI   ZZ dJ   Z[ dK   Z\ dL   Z] dM   Z^ dN   Z_ dO   Z` dP   Za dQ   Zb dR   Zc dS dT  Zd dS dU  Ze d  dV  Zf dW   Zg dX   Zh dY   Zi dZ   Zj d[   Zk d\   Zl d d d] d^  Zm d_   Zn d`   Zo da   Zp d  db  Zq dc   Zr d dd  Zs d d f d de  Zt d d d f d df  Zu dg dh  Zv di   Zw dj   Zx dk   Zy dl   Zz dm   Z{ dn   Z| do   Z} d dp  Z~ dq e f dr     YZ d ds  Z dt   Z du   Z e d d e d dv  Z dw   Z d dx  Z d dy  Z dz d d{  Z d| d}  Z d~   Z d   Z d   Z e d  Z e d  Z e d  Z d   Z d   Z d   Z d d d  Z d   Z d   Z d   Z d   Z d   Z d   Z d   Z d   Z d   Z d   Z d d d d d  Z d d d d d  Z d d d d  Z d d d d d  Z d d d d d  Z d d d d d  Z d d d d d  Z d d  Z dz d| d d d  Z dz d| d d d  Z dz d d d  Z dz d| d d d  Z d   Z d   Z e d d d  Z d d  Z d d d  Z d d d  Z d S(   iN(   t   moving_averages(   t   tensor_array_ops(   t   control_flow_ops(   t   functional_ops(   t   ctc_ops(   t   defaultdicti   (   t   floatx(   t   _EPSILON(   t   image_data_format(   t   set_image_dim_orderingt   image_dim_orderingt    c         C   sK   t  j   } | t k r+ t t  t | <n  t | |  c d 7<t | |  S(   Ni   (   t   tft   get_default_grapht   _GRAPH_UID_DICTSR   t   int(   t   prefixt   graph(    (    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyt   get_uid-   s
    c           C   s
   i  a  d  S(   N(   R   (    (    (    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyt
   reset_uids6   s    c          C   sC   t  j   t   d a t  j d d d d  }  |  t t  j   <d S(   sp   Destroys the current TF graph and creates a new one.

    Useful to avoid clutter from old models / layers.
    t   dtypet   boolt   namet   keras_learning_phaseN(   R   t   reset_default_graphR   t   Nonet   _SESSIONt   placeholdert   _GRAPH_LEARNING_PHASESR   (   t   phase(    (    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyt   clear_session;   s
    
c         C   s
   |  a  d S(   s<  Sets the manual variable initialization flag.

    This boolean flag determines whether
    variables should be initialized
    as they are instantiated (default), or if
    the user should handle the initialization
    (e.g. via `tf.initialize_all_variables()`).

    # Arguments
        value: Python boolean.
    N(   t   _MANUAL_VAR_INIT(   t   value(    (    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyt   manual_variable_initializationI   s    c          C   sE   t  j   }  |  t k r= t  j d d d d  } | t |  <n  t |  S(   s*  Returns the learning phase flag.

    The learning phase flag is a bool tensor (0 = test, 1 = train)
    to be passed as input to any Keras function
    that uses a different behavior at train time and test time.

    # Returns
        Learning phase (scalar integer tensor or Python integer).
    R   R   R   R   (   R   R   R   R   (   R   R   (    (    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyt   learning_phaseY   s    
	c         C   s5   |  d d h k r! t  d   n  |  t t j   <d S(   s   Sets the learning phase to a fixed value.

    # Arguments
        value: Learning phase value, either 0 or 1 (integers).

    # Raises
        ValueError: if `value` is neither `0` nor `1`.
    i    i   s%   Expected learning phase to be 0 or 1.N(   t
   ValueErrorR   R   R   (   R    (    (    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyt   set_learning_phasek   s    
c          C   s   t  j   d k	 r! t  j   }  n~ t d k r t j j d  sT t  j d t  } n0 t	 t j j d   } t  j d | d t  } t  j
 d |  a n  t }  t s t   n  |  S(   s  Returns the TF session to be used by the backend.

    If a default TensorFlow session is available, we will return it.

    Else, we will return the global Keras session.

    If no global Keras session exists at this point:
    we will create a new global session.

    Note that you can manually set the global session
    via `K.set_session(sess)`.

    # Returns
        A TensorFlow session.
    t   OMP_NUM_THREADSt   allow_soft_placementt   intra_op_parallelism_threadst   configN(   R   t   get_default_sessionR   R   t   ost   environt   gett   ConfigProtot   TrueR   t   SessionR   t   _initialize_variables(   t   sessionR(   t
   num_thread(    (    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyt   get_session{   s    	
c         C   s
   |  a  d S(   sX   Sets the global TensorFlow session.

    # Arguments
        session: A TF Session.
    N(   R   (   R1   (    (    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyt   set_session   s    c         C   s   |  d k r t  j S|  d k r& t  j S|  d k r9 t  j S|  d k rL t  j S|  d k r_ t  j S|  d k rr t  j S|  d k r t  j S|  d k r t  j St	 d	 |    d  S(
   Nt   float16t   float32t   float64t   int16t   int32t   int64t   uint8t   uint16s   Unsupported dtype:(
   R   R5   R6   R7   R8   R9   R:   t   int8R<   R#   (   R   (    (    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyt   _convert_string_dtype   s"    c         C   s7   t  j |   }  |  j | k r3 t  j |  |  }  n  |  S(   N(   R   t   convert_to_tensorR   t   cast(   t   xR   (    (    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyt
   _to_tensor   s    c         C   s   t  |  t j  S(   s  Returns whether a tensor is a sparse tensor.

    # Arguments
        tensor: A tensor instance.

    # Returns
        A boolean.

    # Example
    ```python
        >>> from keras import backend as K
        >>> a = K.placeholder((2, 2), sparse=False)
        >>> print(K.is_sparse(a))
        False
        >>> b = K.placeholder((2, 2), sparse=True)
        >>> print(K.is_sparse(b))
        True
    ```
    (   t
   isinstanceR   t   SparseTensor(   t   tensor(    (    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyt	   is_sparse   s    c         C   s!   t  |   r t j |   S|  Sd S(   s  Converts a sparse tensor into a dense tensor and returns it.

    # Arguments
        tensor: A tensor instance (potentially sparse).

    # Returns
        A dense tensor.

    # Examples
    ```python
        >>> from keras import backend as K
        >>> b = K.placeholder((2, 2), sparse=True)
        >>> print(K.is_sparse(b))
        True
        >>> c = K.to_dense(b)
        >>> print(K.is_sparse(c))
        False
    ```
    N(   RF   R   t   sparse_tensor_to_dense(   RE   (    (    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyt   to_dense   s    c         C   s%  | d	 k r t   } n  t |  d  r |  j   } t j t j | j d  t j | j d  f d  } t	 j
 d | d | j d | j  } | j | _ t | _ | St	 j |  d t |  d | } t |  t j  r |  j | _ n0 t |  d  rt t t |  j     | _ n  t | _ | S(
   s  Instantiates a variable and returns it.

    # Arguments
        value: Numpy array, initial value of the tensor.
        dtype: Tensor type.
        name: Optional name string for the tensor.

    # Returns
        A variable instance (with Keras metadata included).

    # Examples
    ```python
        >>> from keras import backend as K
        >>> val = np.array([[1, 2], [3, 4]])
        >>> kvar = K.variable(value=val, dtype='float64', name='example_var')
        >>> K.dtype(kvar)
        'float64'
        >>> print(kvar)
        example_var
        >>> kvar.eval()
        array([[ 1.,  2.],
               [ 3.,  4.]])
    ```
    t   tocooi   t   indicest   valuest   dense_shapeR   R   t	   get_shapeN(   R   R   t   hasattrRI   t   npt   concatenatet   expand_dimst   rowt   colR   RD   t   datat   shapet   _keras_shapet   Falset   _uses_learning_phaset   VariableR>   RC   t   ndarrayt   tuplet   mapR   RM   (   R    R   R   t
   sparse_cooRJ   t   v(    (    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyt   variable   s&    		!!	c          C   s   t  j   }  g  } xA |  D]9 } t | d  s9 | j r | j |  t | _ q q W| r~ t   } | j t  j |   n  d S(   s>   Utility to initialize uninitialized variables on the fly.
    t   _keras_initializedN(	   R   t   global_variablesRN   R`   t   appendR.   R3   t   runt   variables_initializer(   t	   variablest   uninitialized_variablesR^   t   sess(    (    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyR0   '  s    	c         C   s7   | d  k r t   } n  t j |  d | d | d | S(   NR   RU   R   (   R   R   R   t   constant(   R    R   RU   R   (    (    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyRh   5  s    c         C   s   | d k r t   } n  |  sO | rO t g  t |  D] } d ^ q4  }  qO n  | rs t j | d |  d | } n t j | d |  d | } |  | _ t | _	 | S(   sI  Instantiates a placeholder tensor and returns it.

    # Arguments
        shape: Shape of the placeholder
            (integer tuple, may include `None` entries).
        ndim: Number of axes of the tensor.
            At least one of {`shape`, `ndim`} must be specified.
            If both are specified, `shape` is used.
        dtype: Placeholder type.
        sparse: Boolean, whether the placeholder should have a sparse type.
        name: Optional name string for the placeholder.

    # Returns
        Tensor instance (with Keras metadata included).

    # Examples
    ```python
        >>> from keras import backend as K
        >>> input_ph = K.placeholder(shape=(2, 4, 5))
        >>> input_ph._keras_shape
        (2, 4, 5)
        >>> input_ph
        <tf.Tensor 'Placeholder_4:0' shape=(2, 4, 5) dtype=float32>
    ```
    RU   R   N(
   R   R   R[   t   rangeR   t   sparse_placeholderR   RV   RW   RX   (   RU   t   ndimR   t   sparseR   t   _RA   (    (    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyR   ;  s    +		c         C   s   t  j |   S(   sl  Returns the symbolic shape of a tensor or variable.

    # Arguments
        x: A tensor or variable.

    # Returns
        A symbolic shape (which is itself a tensor).

    # Examples
    ```
        # TensorFlow example
        >>> from keras import backend as K
        >>> tf_session = K.get_session()
        >>> val = np.array([[1, 2], [3, 4]])
        >>> kvar = K.variable(value=val)
        >>> input = keras.backend.placeholder(shape=(2, 4, 5))
        >>> K.shape(kvar)
        <tf.Tensor 'Shape_8:0' shape=(2,) dtype=int32>
        >>> K.shape(input)
        <tf.Tensor 'Shape_9:0' shape=(3,) dtype=int32>
        # To get integer shape (Instead, you can use K.int_shape(x))
        >>> K.shape(kvar).eval(session=tf_session)
        array([2, 2], dtype=int32)
        >>> K.shape(input).eval(session=tf_session)
        array([2, 4, 5], dtype=int32)
    ```
    (   R   RU   (   RA   (    (    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyRU   c  s    c         C   sb   t  |  d  r |  j S|  j   } y' t g  | D] } | j   ^ q/  SWn t k
 r] d SXd S(   s  Returns the shape tensor or variable as a tuple of int or None entries.

    # Arguments
        x: Tensor or variable.

    # Returns
        A tuple of integers (or None entries).

    # Examples
    ```python
        >>> from keras import backend as K
        >>> input = K.placeholder(shape=(2, 4, 5))
        >>> K.int_shape(input)
        (2, 4, 5)
        >>> val = np.array([[1, 2], [3, 4]])
        >>> kvar = K.variable(value=val)
        >>> K.int_shape(kvar)
        (2, 2)
    ```
    RV   N(   RN   RV   RM   R[   t   __int__R#   R   (   RA   RU   t   i(    (    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyt	   int_shape  s    'c         C   s)   |  j    j } | d k	 r% t |  Sd S(   s  Returns the number of axes in a tensor, as an integer.

    # Arguments
        x: Tensor or variable.

    # Returns
        Integer (scalar), number of axes.

    # Examples
    ```python
        >>> from keras import backend as K
        >>> input = K.placeholder(shape=(2, 4, 5))
        >>> val = np.array([[1, 2], [3, 4]])
        >>> kvar = K.variable(value=val)
        >>> K.ndim(input)
        3
        >>> K.ndim(kvar)
        2
    ```
    N(   RM   t   _dimsR   t   len(   RA   t   dims(    (    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyRk     s    
c         C   s
   |  j  j S(   s  Returns the dtype of a Keras tensor or variable, as a string.

    # Arguments
        x: Tensor or variable.

    # Returns
        String, dtype of `x`.

    # Examples
    ```python
        >>> from keras import backend as K
        >>> K.dtype(K.placeholder(shape=(2,4,5)))
        'float32'
        >>> K.dtype(K.placeholder(shape=(2,4,5), dtype='float32'))
        'float32'
        >>> K.dtype(K.placeholder(shape=(2,4,5), dtype='float64'))
        'float64'
        # Keras variable
        >>> kvar = K.variable(np.array([[1, 2], [3, 4]]))
        >>> K.dtype(kvar)
        'float32_ref'
        >>> kvar = K.variable(np.array([[1, 2], [3, 4]]), dtype='float32')
        >>> K.dtype(kvar)
        'float32_ref'
    ```
    (   R   R   (   RA   (    (    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyR     s    c         C   s   t  |   j d t    S(   sp  Evaluates the value of a variable.

    # Arguments
        x: A variable.

    # Returns
        A Numpy array.

    # Examples
    ```python
        >>> from keras import backend as K
        >>> kvar = K.variable(np.array([[1, 2], [3, 4]]), dtype='float32')
        >>> K.eval(kvar)
        array([[ 1.,  2.],
               [ 3.,  4.]], dtype=float32)
    ```
    R1   (   RH   t   evalR3   (   RA   (    (    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyRt     s    c         C   s^   | d k r t   } n  t t t |    }  t |  } t t j d d | |   | |  S(   sX  Instantiates an all-zeros variable and returns it.

    # Arguments
        shape: Tuple of integers, shape of returned Keras variable
        dtype: String, data type of returned Keras variable
        name: String, name of returned Keras variable

    # Returns
        A variable (including Keras metadata), filled with `0.0`.

    # Example
    ```python
        >>> from keras import backend as K
        >>> kvar = K.zeros((3,4))
        >>> K.eval(kvar)
        array([[ 0.,  0.,  0.,  0.],
               [ 0.,  0.,  0.,  0.],
               [ 0.,  0.,  0.,  0.]], dtype=float32)
    ```
    g        R   N(	   R   R   R[   R\   R   R>   R_   R   t   constant_initializer(   RU   R   R   t   tf_dtype(    (    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyt   zeros  s    c         C   s^   | d k r t   } n  t t t |    }  t |  } t t j d d | |   | |  S(   sK  Instantiates an all-ones tensor variable and returns it.

    # Arguments
        shape: Tuple of integers, shape of returned Keras variable.
        dtype: String, data type of returned Keras variable.
        name: String, name of returned Keras variable.

    # Returns
        A Keras variable, filled with `1.0`.

    # Example
    ```python
        >>> from keras import backend as K
        >>> kvar = K.ones((3,4))
        >>> K.eval(kvar)
        array([[ 1.,  1.,  1.,  1.],
               [ 1.,  1.,  1.,  1.],
               [ 1.,  1.,  1.,  1.]], dtype=float32)
    ```
    g      ?R   N(	   R   R   R[   R\   R   R>   R_   R   Ru   (   RU   R   R   Rv   (    (    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyt   ones  s    c         C   s   t  t j |   | |  S(   s  Instantiate an identity matrix and returns it.

    # Arguments
        size: Integer, number of rows/columns.
        dtype: String, data type of returned Keras variable.
        name: String, name of returned Keras variable.

    # Returns
        A Keras variable, an identity matrix.

    # Example
    ```python
        >>> from keras import backend as K
        >>> kvar = K.eye(3)
        >>> K.eval(kvar)
        array([[ 1.,  0.,  0.],
               [ 0.,  1.,  0.],
               [ 0.,  0.,  1.]], dtype=float32)
    ```

    (   R_   RO   t   eye(   t   sizeR   R   (    (    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyRy   (  s    c         C   s   t  j |  d | d | S(   s  Instantiates an all-zeros variable of the same shape as another tensor.

    # Arguments
        x: Keras variable or Keras tensor.
        dtype: String, dtype of returned Keras variable.
             None uses the dtype of x.
        name: String, name for the variable to create.

    # Returns
        A Keras variable with the shape of x filled with zeros.

    # Example
    ```python
        >>> from keras import backend as K
        >>> kvar = K.variable(np.random.random((2,3)))
        >>> kvar_zeros = K.zeros_like(kvar)
        >>> K.eval(kvar_zeros)
        array([[ 0.,  0.,  0.],
               [ 0.,  0.,  0.]], dtype=float32)
    ```
    R   R   (   R   t
   zeros_like(   RA   R   R   (    (    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyR{   A  s    c         C   s   t  j |  d | d | S(   s  Instantiates an all-ones variable of the same shape as another tensor.

    # Arguments
        x: Keras variable or tensor.
        dtype: String, dtype of returned Keras variable.
             None uses the dtype of x.
        name: String, name for the variable to create.

    # Returns
        A Keras variable with the shape of x filled with ones.

    # Example
    ```python
        >>> from keras import backend as K
        >>> kvar = K.variable(np.random.random((2,3)))
        >>> kvar_ones = K.ones_like(kvar)
        >>> K.eval(kvar_ones)
        array([[ 1.,  1.,  1.],
               [ 1.,  1.,  1.]], dtype=float32)
    ```
    R   R   (   R   t	   ones_like(   RA   R   R   (    (    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyR|   Z  s    c         C   s   | d k r t   } n  t t t |    }  t |  } | d k rZ t j j d  } n  t	 j
 | | d | d | |   } t | d | d | S(   s^  Instantiates a variable with values drawn from a uniform distribution.

    # Arguments
        shape: Tuple of integers, shape of returned Keras variable.
        low: Float, lower boundary of the output interval.
        high: Float, upper boundary of the output interval.
        dtype: String, dtype of returned Keras variable.
        name: String, name of returned Keras variable.
        seed: Integer, random seed.

    # Returns
        A Keras variable, filled with drawn samples.

    # Example
    ```python
        # TensorFlow example
        >>> kvar = K.random_uniform_variable((2,3), 0, 1)
        >>> kvar
        <tensorflow.python.ops.variables.Variable object at 0x10ab40b10>
        >>> K.eval(kvar)
        array([[ 0.10940075,  0.10047495,  0.476143  ],
               [ 0.66137183,  0.00869417,  0.89220798]], dtype=float32)
    ```
    g    eAR   t   seedR   N(   R   R   R[   R\   R   R>   RO   t   randomt   randintR   t   random_uniform_initializerR_   (   RU   t   lowt   highR   R   R}   Rv   R    (    (    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyt   random_uniform_variables  s    c         C   s   | d k r t   } n  t t t |    }  t |  } | d k rZ t j j d  } n  t	 j
 | | d | d | |   } t | d | d | S(   s`  Instantiates a variable with values drawn from a normal distribution.

    # Arguments
        shape: Tuple of integers, shape of returned Keras variable.
        mean: Float, mean of the normal distribution.
        scale: Float, standard deviation of the normal distribution.
        dtype: String, dtype of returned Keras variable.
        name: String, name of returned Keras variable.
        seed: Integer, random seed.

    # Returns
        A Keras variable, filled with drawn samples.

    # Example
    ```python
        # TensorFlow example
        >>> kvar = K.random_normal_variable((2,3), 0, 1)
        >>> kvar
        <tensorflow.python.ops.variables.Variable object at 0x10ab12dd0>
        >>> K.eval(kvar)
        array([[ 1.19591331,  0.68685907, -0.63814116],
               [ 0.92629528,  0.28055015,  1.70484698]], dtype=float32)
    ```
    g    eAR   R}   R   N(   R   R   R[   R\   R   R>   RO   R~   R   R   t   random_normal_initializerR_   (   RU   t   meant   scaleR   R   R}   Rv   R    (    (    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyt   random_normal_variable  s    c         C   s?   |  j    } t j g  t t |   D] } | | j ^ q%  S(   s|  Returns the number of scalars in a Keras variable.

    # Arguments
        x: Keras variable.

    # Returns
        Integer, the number of scalars in `x`.

    # Example
    ```python
        >>> kvar = K.zeros((2,3))
        >>> K.count_params(kvar)
        6
        >>> K.eval(kvar)
        array([[ 0.,  0.,  0.],
               [ 0.,  0.,  0.]], dtype=float32)
    ```
    (   RM   RO   t   prodRi   Rr   t   _value(   RA   RU   Ro   (    (    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyt   count_params  s    c         C   s   t  j |  |  S(   s  Casts a tensor to a different dtype and returns it.

    You can cast a Keras variable but it still returns a Keras tensor.

    # Arguments
        x: Keras tensor (or variable).
        dtype: String, either (`'float16'`, `'float32'`, or `'float64'`).

    # Returns
        Keras tensor with dtype `dtype`.

    # Example
    ```python
        >>> from keras import backend as K
        >>> input = K.placeholder((2, 3), dtype='float32')
        >>> input
        <tf.Tensor 'Placeholder_2:0' shape=(2, 3) dtype=float32>
        # It doesn't work in-place as below.
        >>> K.cast(input, dtype='float16')
        <tf.Tensor 'Cast_1:0' shape=(2, 3) dtype=float16>
        >>> input
        <tf.Tensor 'Placeholder_2:0' shape=(2, 3) dtype=float32>
        # you need to assign it.
        >>> input = K.cast(input, dtype='float16')
        >>> input
        <tf.Tensor 'Cast_2:0' shape=(2, 3) dtype=float16>
    ```
    (   R   R@   (   RA   R   (    (    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyR@     s    c         C   s   t  j |  |  S(   N(   R   t   assign(   RA   t   new_x(    (    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyt   update  s    c         C   s   t  j |  |  S(   N(   R   t
   assign_add(   RA   t	   increment(    (    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyt
   update_add  s    c         C   s   t  j |  |  S(   N(   R   t
   assign_sub(   RA   t	   decrement(    (    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyt
   update_sub  s    c         C   s   t  j |  | | d t S(   Nt   zero_debias(   R    t   assign_moving_averageRW   (   RA   R    t   momentum(    (    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyt   moving_average_update  s    c   
      C   s  t  |   d k	 rt  |   d k s6 t  |  d k rg  } x^ t t |   t j t j |     D]5 \ } } | d k	 r | j |  qd | j |  qd Wt |  } g  } x^ t t |  t j t j |    D]5 \ } } | d k	 r | j |  q | j |  q Wt |  } t	 t
 t  |    } | j d  g | } t j |  d | d g  } t j t j | d | | d d g  } t j t j | |  | d  | d  | d  St |   rt j |  |  }	 n t j |  |  }	 |	 S(   sh  Multiplies 2 tensors (and/or variables) and returns a *tensor*.

    When attempting to multiply a nD tensor
    with a nD tensor, it reproduces the Theano behavior.
    (e.g. `(2, 3) * (4, 3, 5) -> (2, 4, 5)`)

    # Arguments
        x: Tensor or variable.
        y: Tensor or variable.

    # Returns
        A tensor, dot product of `x` and `y`.

    # Examples
    ```python
        # dot product between tensors
        >>> x = K.placeholder(shape=(2, 3))
        >>> y = K.placeholder(shape=(3, 4))
        >>> xy = K.dot(x, y)
        >>> xy
        <tf.Tensor 'MatMul_9:0' shape=(2, 4) dtype=float32>
    ```

    ```python
        # dot product between tensors
        >>> x = K.placeholder(shape=(32, 28, 3))
        >>> y = K.placeholder(shape=(3, 4))
        >>> xy = K.dot(x, y)
        >>> xy
        <tf.Tensor 'MatMul_9:0' shape=(32, 28, 4) dtype=float32>
    ```

    ```python
        # Theano-like behavior example
        >>> x = K.random_uniform_variable(shape=(2, 3), low=0, high=1)
        >>> y = K.ones((4, 3, 5))
        >>> xy = K.dot(x, y)
        >>> K.int_shape(xy)
        (2, 4, 5)
    ```
    i   iit   permN(   Rk   R   t   zipRp   R   t   unstackRU   Rb   R[   t   listRi   t   popt   reshapet	   transposet   matmulRF   t   sparse_tensor_dense_matmul(
   RA   t   yt   x_shapeRo   t   st   y_shapet   y_permute_dimt   xtt   ytt   out(    (    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyt   dot  s.    *644+c         C   s_  t  | t  r | | f } n  t |   d k r t |  d k r | d | d k r{ t j t j |  |  | d  } q7t j t j t j |  d d g  |  | d  } n | d k	 r| d t |   d k r d n t } | d t |  d k rt n d } n d } d } t j	 |  | d | d | } t |  d k r[t
 | d  } n  | S(   s  Batchwise dot product.

    `batch_dot` is used to compute dot product of `x` and `y` when
    `x` and `y` are data in batch, i.e. in a shape of
    `(batch_size, :)`.
    `batch_dot` results in a tensor or variable with less dimensions
    than the input. If the number of dimensions is reduced to 1,
    we use `expand_dims` to make sure that ndim is at least 2.

    # Arguments
        x: Keras tensor or variable with `ndim >= 2`.
        y: Keras tensor or variable with `ndim >= 2`.
        axes: list of (or single) int with target dimensions.
            The lengths of `axes[0]` and `axes[1]` should be the same.

    # Returns
        A tensor with shape equal to the concatenation of `x`'s shape
        (less the dimension that was summed over) and `y`'s shape
        (less the batch dimension and the dimension that was summed over).
        If the final rank is 1, we reshape it to `(batch_size, 1)`.

    # Examples
        Assume `x = [[1, 2], [3, 4]]` and `y = [[5, 6], [7, 8]]`
        `batch_dot(x, y, axes=1) = [[17, 53]]` which is the main diagonal
        of `x.dot(y.T)`, although we never have to calculate the off-diagonal
        elements.

        Shape inference:
        Let `x`'s shape be `(100, 20)` and `y`'s shape be `(100, 30, 20)`.
        If `axes` is (1, 2), to find the output shape of resultant tensor,
            loop through each dimension in `x`'s shape and `y`'s shape:

        * `x.shape[0]` : 100 : append to output shape
        * `x.shape[1]` : 20 : do not append to output shape,
            dimension 1 of `x` has been summed over. (`dot_axes[0]` = 1)
        * `y.shape[0]` : 100 : do not append to output shape,
            always ignore first dimension of `y`
        * `y.shape[1]` : 30 : append to output shape
        * `y.shape[2]` : 20 : do not append to output shape,
            dimension 2 of `y` has been summed over. (`dot_axes[1]` = 2)
        `output_shape` = `(100, 30)`

    ```python
        >>> x_batch = K.ones(shape=(32, 20, 1))
        >>> y_batch = K.ones(shape=(32, 30, 20))
        >>> xy_batch_dot = K.batch_dot(x_batch, y_batch, axes=[1, 2])
        >>> K.int_shape(xy_batch_dot)
        (32, 1, 30)
    ```
    i   i    i   t	   adjoint_at	   adjoint_bN(   RC   R   Rk   R   t
   reduce_sumt   multiplyR   R   R.   R   RQ   (   RA   R   t   axesR   t   adj_xt   adj_y(    (    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyt	   batch_dotR  s    3$%7&)c         C   s   t  j |   S(   s  Transposes a tensor and returns it.

    # Arguments
        x: Tensor or variable.

    # Returns
        A tensor.

    # Examples
    ```python
        >>> var = K.variable([[1, 2, 3], [4, 5, 6]])
        >>> K.eval(var)
        array([[ 1.,  2.,  3.],
               [ 4.,  5.,  6.]], dtype=float32)
        >>> var_transposed = K.transpose(var)
        >>> K.eval(var_transposed)
        array([[ 1.,  4.],
               [ 2.,  5.],
               [ 3.,  6.]], dtype=float32)
    ```

    ```python
        >>> input = K.placeholder((2, 3))
        >>> input
        <tf.Tensor 'Placeholder_11:0' shape=(2, 3) dtype=float32>
        >>> input_transposed = K.transpose(input)
        >>> input_transposed
        <tf.Tensor 'transpose_4:0' shape=(3, 2) dtype=float32>

    ```
    (   R   R   (   RA   (    (    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyR     s     c         C   s   t  j |  |  S(   s   Retrieves the elements of indices `indices` in the tensor `reference`.

    # Arguments
        reference: A tensor.
        indices: An integer tensor of indices.

    # Returns
        A tensor of same type as `reference`.
    (   R   t   gather(   t	   referenceRJ   (    (    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyR     s    
c         C   s   t  |  t  r t |   }  n  t  |  t  rv xk t |   D]5 \ } } | d k	 r: | d k  r: | | |  | <q: q: Wn% |  d k	 r |  d k  r |  | ;}  n  |  S(   s   Converts negative axes to positive values.

    # Arguments
        axis: Integer axis (possibly negative).
        ndim: Rank of the tensor considered.

    # Returns
        Positive integer axis.
    i    N(   RC   R[   R   t	   enumerateR   (   t   axisRk   Ro   t   a(    (    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyt   _normalize_axis  s    
c         C   s.   t  | t |    } t j |  d | d | S(   s  Maximum value in a tensor.

    # Arguments
        x: A tensor or variable.
        axis: An integer, the axis to find maximum values.
        keepdims: A boolean, whether to keep the dimensions or not.
            If `keepdims` is `False`, the rank of the tensor is reduced
            by 1. If `keepdims` is `True`,
            the reduced dimension is retained with length 1.

    # Returns
        A tensor with maximum values of `x`.
    t   reduction_indicest	   keep_dims(   R   Rk   R   t
   reduce_max(   RA   R   t   keepdims(    (    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyt   max  s    c         C   s.   t  | t |    } t j |  d | d | S(   s  Minimum value in a tensor.

    # Arguments
        x: A tensor or variable.
        axis: An integer, the axis to find minimum values.
        keepdims: A boolean, whether to keep the dimensions or not.
            If `keepdims` is `False`, the rank of the tensor is reduced
            by 1. If `keepdims` is `True`,
            the reduced dimension is retained with length 1.

    # Returns
        A tensor with miminum values of `x`.
    R   R   (   R   Rk   R   t
   reduce_min(   RA   R   R   (    (    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyt   min  s    c         C   s.   t  | t |    } t j |  d | d | S(   s  Sum of the values in a tensor, alongside the specified axis.

    # Arguments
        x: A tensor or variable.
        axis: An integer, the axis to sum over.
        keepdims: A boolean, whether to keep the dimensions or not.
            If `keepdims` is `False`, the rank of the tensor is reduced
            by 1. If `keepdims` is `True`,
            the reduced dimension is retained with length 1.

    # Returns
        A tensor with sum of `x`.
    R   R   (   R   Rk   R   R   (   RA   R   R   (    (    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyt   sum  s    c         C   s.   t  | t |    } t j |  d | d | S(   s  Multiplies the values in a tensor, alongside the specified axis.

    # Arguments
        x: A tensor or variable.
        axis: An integer, the axis to compute the product.
        keepdims: A boolean, whether to keep the dimensions or not.
            If `keepdims` is `False`, the rank of the tensor is reduced
            by 1. If `keepdims` is `True`,
            the reduced dimension is retained with length 1.

    # Returns
        A tensor with the product of elements of `x`.
    R   R   (   R   Rk   R   t   reduce_prod(   RA   R   R   (    (    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyR     s    c         C   s   t  | t |    } |  j j t j k rB t j |  t    }  n  t j |  d | d t	 } t j
 |  |  } t j | d | d | S(   s  Variance of a tensor, alongside the specified axis.

    # Arguments
        x: A tensor or variable.
        axis: An integer, the axis to compute the variance.
        keepdims: A boolean, whether to keep the dimensions or not.
            If `keepdims` is `False`, the rank of the tensor is reduced
            by 1. If `keepdims` is `True`,
            the reduced dimension is retained with length 1.

    # Returns
        A tensor with the variance of elements of `x`.
    R   R   (   R   Rk   R   t
   base_dtypeR   R   R@   R   t   reduce_meanR.   t   square(   RA   R   R   t   mt   devs_squared(    (    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyt   var)  s    c         C   s   t  j t |  d | d |  S(   s  Standard deviation of a tensor, alongside the specified axis.

    # Arguments
        x: A tensor or variable.
        axis: An integer, the axis to compute the standard deviation.
        keepdims: A boolean, whether to keep the dimensions or not.
            If `keepdims` is `False`, the rank of the tensor is reduced
            by 1. If `keepdims` is `True`,
            the reduced dimension is retained with length 1.

    # Returns
        A tensor with the standard deviation of elements of `x`.
    R   R   (   R   t   sqrtR   (   RA   R   R   (    (    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyt   stdA  s    c         C   s[   t  | t |    } |  j j t j k rB t j |  t    }  n  t j |  d | d | S(   s  Mean of a tensor, alongside the specified axis.

    # Arguments
        x: A tensor or variable.
        axis: A list of integer. Axes to compute the mean.
        keepdims: A boolean, whether to keep the dimensions or not.
            If `keepdims` is `False`, the rank of the tensor is reduced
            by 1 for each entry in `axis`. If `keep_dims` is `True`,
            the reduced dimensions are retained with length 1.

    # Returns
        A tensor with the mean of elements of `x`.
    R   R   (	   R   Rk   R   R   R   R   R@   R   R   (   RA   R   R   (    (    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyR   R  s    c         C   sC   t  | t |    } t j |  t j  }  t j |  d | d | S(   s  Bitwise reduction (logical OR).

    # Arguments
        x: Tensor or variable.
        axis: axis along which to perform the reduction.
        keepdims: whether the drop or broadcast the reduction axes.

    # Returns
        A uint8 tensor (0s and 1s).
    R   R   (   R   Rk   R   R@   R   t
   reduce_any(   RA   R   R   (    (    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyt   anyf  s    c         C   sC   t  | t |    } t j |  t j  }  t j |  d | d | S(   s  Bitwise reduction (logical AND).

    # Arguments
        x: Tensor or variable.
        axis: axis along which to perform the reduction.
        keepdims: whether the drop or broadcast the reduction axes.

    # Returns
        A uint8 tensor (0s and 1s).
    R   R   (   R   Rk   R   R@   R   t
   reduce_all(   RA   R   R   (    (    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyt   allv  s    c         C   s%   t  | t |    } t j |  |  S(   s   Returns the index of the maximum value along an axis.

    # Arguments
        x: Tensor or variable.
        axis: axis along which to perform the reduction.

    # Returns
        A tensor.
    (   R   Rk   R   t   argmax(   RA   R   (    (    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyR     s    
c         C   s%   t  | t |    } t j |  |  S(   s   Returns the index of the minimum value along an axis.

    # Arguments
        x: Tensor or variable.
        axis: axis along which to perform the reduction.

    # Returns
        A tensor.
    (   R   Rk   R   t   argmin(   RA   R   (    (    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyR     s    
c         C   s   t  j |   S(   sj   Element-wise square.

    # Arguments
        x: Tensor or variable.

    # Returns
        A tensor.
    (   R   R   (   RA   (    (    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyR     s    	c         C   s   t  j |   S(   sr   Element-wise absolute value.

    # Arguments
        x: Tensor or variable.

    # Returns
        A tensor.
    (   R   t   abs(   RA   (    (    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyR     s    	c         C   sO   t  d |  j j  } t  t j |  j j  } t j |  | |  }  t j |   S(   so   Element-wise square root.

    # Arguments
        x: Tensor or variable.

    # Returns
        A tensor.
    g        (   RB   R   R   RO   t   infR   t   clip_by_valueR   (   RA   t   zeroR   (    (    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyR     s    	c         C   s   t  j |   S(   so   Element-wise exponential.

    # Arguments
        x: Tensor or variable.

    # Returns
        A tensor.
    (   R   t   exp(   RA   (    (    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyR     s    	c         C   s   t  j |   S(   sg   Element-wise log.

    # Arguments
        x: Tensor or variable.

    # Returns
        A tensor.
    (   R   t   log(   RA   (    (    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyR     s    	c         C   s   t  j |   S(   s   Element-wise rounding to the closest integer.

    In case of tie, the rounding mode used is "half to even".

    # Arguments
        x: Tensor or variable.

    # Returns
        A tensor.
    (   R   t   round(   RA   (    (    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyR     s    c         C   s   t  j |   S(   sh   Element-wise sign.

    # Arguments
        x: Tensor or variable.

    # Returns
        A tensor.
    (   R   t   sign(   RA   (    (    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyR     s    	c         C   s   t  j |  |  S(   s   Element-wise exponentiation.

    # Arguments
        x: Tensor or variable.
        a: Python integer.

    # Returns
        A tensor.
    (   R   t   pow(   RA   R   (    (    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyR     s    
c         C   sv   | d k	 r! | | k  r! | } n  | d k r9 t j } n  t | |  j j  } t | |  j j  } t j |  | |  S(   s   Element-wise value clipping.

    # Arguments
        x: Tensor or variable.
        min_value: Python float or integer.
        max_value: Python float or integer.

    # Returns
        A tensor.
    N(   R   RO   R   RB   R   R   R   R   (   RA   t	   min_valuet	   max_value(    (    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyt   clip  s    	c         C   s   t  j |  |  S(   s   Element-wise equality between two tensors.

    # Arguments
        x: Tensor or variable.
        y: Tensor or variable.

    # Returns
        A bool tensor.
    (   R   t   equal(   RA   R   (    (    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyR     s    
c         C   s   t  j |  |  S(   s   Element-wise inequality between two tensors.

    # Arguments
        x: Tensor or variable.
        y: Tensor or variable.

    # Returns
        A bool tensor.
    (   R   t	   not_equal(   RA   R   (    (    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyR   )  s    
c         C   s   t  j |  |  S(   s   Element-wise truth value of (x > y).

    # Arguments
        x: Tensor or variable.
        y: Tensor or variable.

    # Returns
        A bool tensor.
    (   R   t   greater(   RA   R   (    (    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyR   6  s    
c         C   s   t  j |  |  S(   s   Element-wise truth value of (x >= y).

    # Arguments
        x: Tensor or variable.
        y: Tensor or variable.

    # Returns
        A bool tensor.
    (   R   t   greater_equal(   RA   R   (    (    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyR   C  s    
c         C   s   t  j |  |  S(   s   Element-wise truth value of (x < y).

    # Arguments
        x: Tensor or variable.
        y: Tensor or variable.

    # Returns
        A bool tensor.
    (   R   t   less(   RA   R   (    (    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyR   P  s    
c         C   s   t  j |  |  S(   s   Element-wise truth value of (x <= y).

    # Arguments
        x: Tensor or variable.
        y: Tensor or variable.

    # Returns
        A bool tensor.
    (   R   t
   less_equal(   RA   R   (    (    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyR   ]  s    
c         C   s   t  j |  |  S(   s   Element-wise maximum of two tensors.

    # Arguments
        x: Tensor or variable.
        y: Tensor or variable.

    # Returns
        A tensor.
    (   R   t   maximum(   RA   R   (    (    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyR   j  s    
c         C   s   t  j |  |  S(   s   Element-wise minimum of two tensors.

    # Arguments
        x: Tensor or variable.
        y: Tensor or variable.

    # Returns
        A tensor.
    (   R   t   minimum(   RA   R   (    (    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyR   w  s    
c         C   s   t  j |   S(   su   Computes sin of x element-wise.

    # Arguments
        x: Tensor or variable.

    # Returns
        A tensor.
    (   R   t   sin(   RA   (    (    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyR     s    	c         C   s   t  j |   S(   su   Computes cos of x element-wise.

    # Arguments
        x: Tensor or variable.

    # Returns
        A tensor.
    (   R   t   cos(   RA   (    (    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyR     s    	gMbP?c      	   C   s{  t  j j |  | d d d d d t \ } } t |  t t |    d  k rs t  j j |  | | | | |  } n g  } xP t t |    D]< }	 |	 | k r | j	 d  q | j	 t  j
 |   |	  q Wt  j |  } t  j | |  }
 t  j | |  } | d k rd } n t  j | |  } | d k r;d } n t  j | |  } t  j j |  |
 | | | |  } | | | f S(   s  Computes mean and std for batch then apply batch_normalization on batch.

    # Arguments
        x: Input tensor or variable.
        gamma: Tensor by which to scale the input.
        beta: Tensor with which to center the input.
        reduction_axes: iterable of integers,
            axes over which to normalize.
        epsilon: Fuzz factor.

    # Returns
        A tuple length of 3, `(normalized_tensor, mean, variance)`.
    t   shiftR   R   ii   N(   R   t   nnt   momentsR   RW   t   sortedRi   Rk   t   batch_normalizationRb   RU   t   stackR   (   RA   t   gammat   betat   reduction_axest   epsilonR   R   t   normedt   target_shapeR   t   broadcast_meant   broadcast_vart   broadcast_gammat   broadcast_beta(    (    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyt   normalize_batch_in_training  s0    "			c         C   s   t  j j |  | | | | |  S(   s  Applies batch normalization on x given mean, var, beta and gamma.

    I.e. returns:
    `output = (x - mean) / (sqrt(var) + epsilon) * gamma + beta`

    # Arguments
        x: Input tensor or variable.
        mean: Mean of batch.
        var: Variance of batch.
        beta: Tensor with which to center the input.
        gamma: Tensor by which to scale the input.
        epsilon: Fuzz factor.

    # Returns
        A tensor.
    (   R   R   R   (   RA   R   R   R   R   R   (    (    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyR     s    c         C   s   | d k  r8 t  |  d  } | r/ | | ;} q8 d } n  t g  |  D] } t |  ^ qB  rm t j | |   St j g  |  D] } t |  ^ qz |  Sd S(   s   Concatenates a list of tensors alongside the specified axis.

    # Arguments
        tensors: list of tensors to concatenate.
        axis: concatenation axis.

    # Returns
        A tensor.
    i    N(   Rk   t   py_allRF   R   t   sparse_concatt   concatRH   (   t   tensorsR   t   rankRA   (    (    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyRP     s    
	%c         C   s   t  j |  |  S(   s   Reshapes a tensor to the specified shape.

    # Arguments
        x: Tensor or variable.
        shape: Target shape tuple.

    # Returns
        A tensor.
    (   R   R   (   RA   RU   (    (    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyR     s    
c         C   s   t  j |  d | S(   s   Permutes axes in a tensor.

    # Arguments
        x: Tensor or variable.
        pattern: A tuple of
            dimension indices, e.g. `(0, 2, 1)`.

    # Returns
        A tensor.
    R   (   R   R   (   RA   t   pattern(    (    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyt   permute_dimensions  s    c         C   s  | d k r t  |   } t j |   d } | t j t j | | g  j d   9} t |  d d d d g  }  t j j	 |  |  }  t |  d d d d g  }  |  j
 d	 d	 | d d	 k	 r | d | n d	 | d d	 k	 r | d | n d	 f  |  S| d k rt  |   } t j |   d d !} | t j t j | | g  j d   9} t j j	 |  |  }  |  j
 d	 | d d	 k	 r| d | n d	 | d d	 k	 r| d | n d	 d	 f  |  St d |   d	 S(
   s  Resizes the images contained in a 4D tensor.

    # Arguments
        x: Tensor or variable to resize.
        height_factor: Positive integer.
        width_factor: Positive integer.
        data_format: One of `"channels_first"`, `"channels_last"`.

    # Returns
        A tensor.

    # Raises
        ValueError: if `data_format` is neither
            `channels_last` or `channels_first`.
    t   channels_firsti   R9   i    i   i   t   channels_lasts   Invalid data_format:N(   Rp   R   RU   Rh   RO   t   arrayt   astypeR   t   imaget   resize_nearest_neighbort	   set_shapeR   R#   (   RA   t   height_factort   width_factort   data_formatt   original_shapet	   new_shape(    (    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyt   resize_images  s&    +-(+*+c         C   s   | d k rO t  |  | d d } t  | | d d } t  | | d d } | S| d k r t  |  | d d } t  | | d d } t  | | d d } | St d |   d	 S(
   s  Resizes the volume contained in a 5D tensor.

    # Arguments
        x: Tensor or variable to resize.
        depth_factor: Positive integer.
        height_factor: Positive integer.
        width_factor: Positive integer.
        data_format: One of `"channels_first"`, `"channels_last"`.

    # Returns
        A tensor.

    # Raises
        ValueError: if `data_format` is neither
            `channels_last` or `channels_first`.
    R   R   i   i   i   R   i   s   Invalid data_format:N(   t   repeat_elementsR#   (   RA   t   depth_factorR  R  R  t   output(    (    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyt   resize_volumes9  s    c         C   s   |  j    j   } | | d k rS t d t |  d t t |   d   n  t j d |  d | | d |  } g  | D] } t |  D] } | ^ q q| } t	 | |  S(   s  Repeats the elements of a tensor along an axis, like `np.repeat`.

    If `x` has shape `(s1, s2, s3)` and `axis` is `1`, the output
    will have shape `(s1, s2 * rep, s3)`.

    # Arguments
        x: Tensor or variable.
        rep: Python integer, number of times to repeat.
        axis: Axis along which to repeat.

    # Raises
        ValueError: In case `x.shape[axis]` is undefined.

    # Returns
        A tensor.
    s   Axis sR    of input tensor should have a defined dimension, but is None. Full tensor shape: sX   . Typically you need to pass a fully-defined `input_shape` argument to your first layer.R    t   num_or_size_splitsR   N(
   RM   t   as_listR   R#   t   strR[   R   t   splitRi   RP   (   RA   t   repR   R   t   splitsR   Rm   t   x_rep(    (    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyR
  X  s    .",c         C   sR   t  |   d k s t  t j |  d  }  t j d | d g  } t j |  |  S(   s	  Repeats a 2D tensor.

    if `x` has shape (samples, dim) and `n` is `2`,
    the output will have shape `(samples, 2, dim)`.

    # Arguments
        x: Tensor or variable.
        n: Python integer, number of times to repeat.

    # Returns
        A tensor.
    i   i   (   Rk   t   AssertionErrorR   RQ   R   t   tile(   RA   t   nR   (    (    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyt   repeatw  s    R9   c      	   C   sd   | d k r! |  d k  r! d }  n  t j |  d | d | d d } | d k r` t | |  } n  | S(   s  Creates a 1D tensor containing a sequence of integers.

    The function arguments use the same convention as
    Theano's arange: if only one argument is provided,
    it is in fact the "stop" argument.

    The default type of the returned tensor is `'int32'` to
    match TensorFlow's default.

    # Arguments
        start: Start value.
        stop: Stop value.
        step: Difference between two successive values.
        dtype: Integer dtype to use.

    # Returns
        An integer tensor.

    i    t   limitt   deltaR   t   arangeR9   N(   R   R   Ri   R@   (   t   startt   stopt   stepR   t   result(    (    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyR    s    	!c         C   s+   t  | t  r | g } n  t j |  |  S(   s   Creates a tensor by tiling `x` by `n`.

    # Arguments
        x: A tensor or variable
        n: A list of integer. The length must be the same as the number of
            dimensions in `x`.

    # Returns
        A tiled tensor.
    (   RC   R   R   R  (   RA   R  (    (    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyR    s    c         C   s   t  j |  d g  S(   s{   Flatten a tensor.

    # Arguments
        x: A tensor or variable.

    # Returns
        A tensor, reshaped into 1-D
    i(   R   R   (   RA   (    (    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyt   flatten  s    	c         C   s5   t  j |  t  j d t t |   d  g   }  |  S(   s   Turn a nD tensor into a 2D tensor with same 0th dimension.

    In other words, it flattens each data samples of a batch.

    # Arguments
        x: A tensor or variable.

    # Returns
        A tensor.
    ii   (   R   R   R   R   RU   (   RA   (    (    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyt   batch_flatten  s    1c         C   s   t  j |  |  S(   s   Adds a 1-sized dimension at index "dim".

    # Arguments
        x: A tensor or variable.
        axis: Position where to add a new axis.

    # Returns
        A tensor with expended dimensions.
    (   R   RQ   (   RA   R   (    (    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyRQ     s    
c         C   s   t  j |  | g  S(   s   Removes a 1-dimension from the tensor at index "axis".

    # Arguments
        x: A tensor or variable.
        axis: Axis to drop.

    # Returns
        A tensor with the same data as `x` but reduced dimensions.
    (   R   t   squeeze(   RA   R   (    (    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyR"    s    
c         C   sQ   t  |  d k s t  d d g | d | d g d d g g } t j |  |  S(   s   Pads the middle dimension of a 3D tensor.

    # Arguments
        x: Tensor or variable.
        padding: Tuple of 2 integers, how many zeros to
            add at the start and end of dim 1.

    # Returns
        A padded 3D tensor.
    i   i    i   (   Rr   R  R   t   pad(   RA   t   paddingR   (    (    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyt   temporal_padding  s    )c         C   s  t  |  d k s t  t  | d  d k s4 t  t  | d  d k sP t  | d k rh t   } n  | d d h k r t d t |    n  | d k r d d g d d g t | d  t | d  g } n2 d d g t | d  t | d  d d g g } t j |  |  S(   st  Pads the 2nd and 3rd dimensions of a 4D tensor.

    # Arguments
        x: Tensor or variable.
        padding: Tuple of 2 tuples, padding pattern.
        data_format: One of `channels_last` or `channels_first`.

    # Returns
        A padded 4D tensor.

    # Raises
        ValueError: if `data_format` is neither
            `channels_last` or `channels_first`.
    i   i    i   R   R   s   Unknown data_format N(	   Rr   R  R   R   R#   R  R   R   R#  (   RA   R$  R  R   (    (    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyt   spatial_2d_padding  s     			c         C   s  t  |  d k s t  t  | d  d k s4 t  t  | d  d k sP t  t  | d  d k sl t  | d k r t   } n  | d d h k r t d t |    n  | d k r!d d g d d g | d d | d d g | d d | d d g | d d | d d g g } nc d d g | d d | d d g | d d | d d g | d d | d d g d d g g } t j |  |  S(	   s  Pads 5D tensor with zeros along the depth, height, width dimensions.

    Pads these dimensions with respectively
    "padding[0]", "padding[1]" and "padding[2]" zeros left and right.

    For 'channels_last' data_format,
    the 2nd, 3rd and 4th dimension will be padded.
    For 'channels_first' data_format,
    the 3rd, 4th and 5th dimension will be padded.

    # Arguments
        x: Tensor or variable.
        padding: Tuple of 3 tuples, padding pattern.
        data_format: One of `channels_last` or `channels_first`.

    # Returns
        A padded 5D tensor.

    # Raises
        ValueError: if `data_format` is neither
            `channels_last` or `channels_first`.

    i   i    i   i   R   R   s   Unknown data_format N(   Rr   R  R   R   R#   R  R   R#  (   RA   R$  R  R   (    (    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyt   spatial_3d_padding  s(    		"	i    c         C   s   t  j |  d | S(   s   Stacks a list of rank `R` tensors into a rank `R+1` tensor.

    # Arguments
        x: List of tensors.
        axis: Axis along which to perform stacking.

    # Returns
        A tensor.
    R   (   R   R   (   RA   R   (    (    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyR   S  s    
c         C   s   t  j |  d | d d S(   s  Computes the one-hot representation of an integer tensor.

    # Arguments
        indices: nD integer tensor of shape
            `(batch_size, dim1, dim2, ... dim(n-1))`
        num_classes: Integer, number of classes to consider.

    # Returns
        (n + 1)D one hot representation of the input
        with shape `(batch_size, dim1, dim2, ... dim(n-1), num_classes)`

    # Returns
        The one-hot tensor.
    t   depthR   i(   R   t   one_hot(   RJ   t   num_classes(    (    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyR)  `  s    c         C   s+   t  | t  r | g } n  t j |  |  S(   s   Reverse a tensor along the specified axes.

    # Arguments
        x: Tensor to reverse.
        axes: Integer or iterable of integers.
            Axes to reverse.

    # Returns
        A tensor.
    (   RC   R   R   t   reverse(   RA   R   (    (    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyR+  r  s    c         C   s   |  j  d t    S(   sw   Returns the value of a variable.

    # Arguments
        x: input variable.

    # Returns
        A Numpy array.
    R1   (   Rt   R3   (   RA   (    (    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyt	   get_value  s    	c         C   s   |  r t    j |   Sg  Sd S(   s   Returns the value of more than one tensor variable.

    # Arguments
        ops: list of ops to run.

    # Returns
        A list of Numpy arrays.
    N(   R3   Rc   (   t   ops(    (    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyt   batch_get_value  s    	c         C   s   t  j |  } t |  j j j d  d  } t |  d  rR |  j } |  j } n9 t	 j
 | d | j } |  j |  } | |  _ | |  _ t   j | d i | | 6d S(   s   Sets the value of a variable, from a Numpy array.

    # Arguments
        x: Tensor to set to a new value.
        value: Value to set the tensor to, as a Numpy array
            (of the same shape).
    Rm   i    t   _assign_placeholderRU   t	   feed_dictN(   RO   t   asarrayR>   R   R   R  RN   R/  t
   _assign_opR   R   RU   R   R3   Rc   (   RA   R    Rv   t   assign_placeholdert	   assign_op(    (    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyt	   set_value  s    			c         C   s   |  r g  } i  } x |  D] \ } } t  j |  } t | j j j d  d  } t | d  rw | j } | j } n9 t	 j
 | d | j } | j |  } | | _ | | _ | j |  | | | <q Wt   j | d | n  d S(   s   Sets the values of many tensor variables at once.

    # Arguments
        tuples: a list of tuples `(tensor, value)`.
            `value` should be a Numpy array.
    Rm   i    R/  RU   R0  N(   RO   R1  R>   R   R   R  RN   R/  R2  R   R   RU   R   Rb   R3   Rc   (   t   tuplest
   assign_opsR0  RA   R    Rv   R3  R4  (    (    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyt   batch_set_value  s"    			c         C   s
   t  |   S(   sy   Returns the shape of a variable.

    # Arguments
        x: A variable.

    # Returns
        A tuple of integers.
    (   Rp   (   RA   (    (    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyt   get_variable_shape  s    	c         C   s   t  j |  |  g |  S(   s   Prints `message` and the tensor value when evaluated.

    # Arguments
        x: Tensor to print.
        message: Message to print jointly with the tensor.

    # Returns
        The same tensor `x`, unchanged.
    (   R   t   Print(   RA   t   message(    (    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyt   print_tensor  s    
t   Functionc           B   s#   e  Z d  Z d d  Z d   Z RS(   s   Runs a computation graph.

    # Arguments
        inputs: Feed placeholders to the computation graph.
        outputs: Output tensors to fetch.
        updates: Additional update ops to be run at function call.
    c      
   C   s   | p	 g  } t  | t t f  s0 t d   n  t  | t t f  sT t d   n  t  | t t f  sx t d   n  t |  |  _ t |  |  _ t j |  j  r g  } xR | D]J } t  | t  r | \ } } | j t j	 | |   q | j |  q Wt j
 |   |  _ Wd  QXd  S(   NsD   `inputs` to a TensorFlow backend function should be a list or tuple.sE   `outputs` of a TensorFlow backend function should be a list or tuple.sE   `updates` in a TensorFlow backend function should be a list or tuple.(   RC   R   R[   t	   TypeErrort   inputst   outputsR   t   control_dependenciesRb   R   t   groupt
   updates_op(   t   selfR?  R@  t   updatest   updates_opsR   t   pt   new_p(    (    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyt   __init__  s"    c   	      C   s   t  | t t f  s$ t d   n  i  } x t |  j |  D]| \ } } t |  r | j   } t j	 t j
 | j d  t j
 | j d  f d  } | | j | j f } n  | | | <q= Wt   } | j |  j |  j g d | } | t |  j   S(   Ns#   `inputs` should be a list or tuple.i   R0  (   RC   R   R[   R>  R   R?  RF   RI   RO   RP   RQ   RR   RS   RT   RU   R3   Rc   R@  RC  Rr   (	   RD  R?  R0  RE   R    R]   RJ   R1   t   updated(    (    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyt   __call__  s    		N(   t   __name__t
   __module__t   __doc__R   RI  RK  (    (    (    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyR=    s   c         K   sH   | r5 d t  |  d g } t j d j |   n  t |  | d | S(   s  Instantiates a Keras function.

    # Arguments
        inputs: List of placeholder tensors.
        outputs: List of output tensors.
        updates: List of update ops.
        **kwargs: Not used with TensorFlow.

    # Returns
        Output values as Numpy arrays.
    s!   Expected no kwargs, you passed %ss=   kwargs passed to function are ignored with Tensorflow backends   
RE  (   Rr   t   warningst   warnt   joinR=  (   R?  R@  RE  t   kwargst   msg(    (    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyt   function  s
    	c         C   s   t  j |  | d t S(   s   Returns the gradients of `variables` w.r.t. `loss`.

    # Arguments
        loss: Scalar tensor to minimize.
        variables: List of variables.

    # Returns
        A gradients tensor.
    t   colocate_gradients_with_ops(   R   t	   gradientsR.   (   t   lossRe   (    (    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyRV  2  s    
c         C   s   t  j |   S(   s   Returns `variables` but with zero gradient w.r.t. every other variable.

    # Arguments
        variables: List of variables.

    # Returns
        The same list of variables.
    (   R   t   stop_gradient(   Re   (    (    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyRX  ?  s    	c             sH  t  | j    } | d k  r- t d   n  d d g t t d |   }	 t j | |	  } | d k	 r | j t j	 k r t j
 | t j	  } n  t  | j    | d k r t |  } n  t j | |	  } n    d k r g    n  | r+| j   d st d   n  | }
 g  } g  } t j |  } | rB| j   n  | d k	 rt j |  } | rp| j   n  xt | |  D]:\ } }  | |
    \ } } t j | t j d t j |  d g   } | st |  } n
 | d } t j | | |  } g  } xg t |
 |  D]V \ } } t j | t j d t j |  d g   } | j t j | | |   qW| }
 | j |  | j |
  | d } | d } t j |  } qWqxA | D]9 }  | |
    \ } }
 | j |  | j |
  qW| d } | d } t j |  } n| rCt | d  } n  t |  }
 t j |  d   | d |    \ } } t j d | j d	  d
 d  } t j d | j d	  d
 d    j |   t j d d d d d } | d k	 ro|
 st d   n  | r$t | d  } n  t j d t j	 d	  d
 d    j |        f d   } n     f d   } t j d  f d   d | d | | f |
 d d d t  } | d } | d } | d } | j   } | j | d  } d d g t t d t  | j      }	 t j | |	  } | | | f S(   s  Iterates over the time dimension of a tensor.

    # Arguments
        step_function: RNN step function.
            Parameters:
                input: tensor with shape `(samples, ...)` (no time dimension),
                    representing input for the batch of samples at a certain
                    time step.
                states: list of tensors.
            Returns:
                output: tensor with shape `(samples, output_dim)`
                    (no time dimension).
                new_states: list of tensors, same length and shapes
                    as 'states'. The first state in the list must be the
                    output tensor at the previous timestep.
        inputs: tensor of temporal data of shape `(samples, time, ...)`
            (at least 3D).
        initial_states: tensor with shape (samples, output_dim)
            (no time dimension),
            containing the initial values for the states used in
            the step function.
        go_backwards: boolean. If True, do the iteration over
            the time dimension in reverse order.
        mask: binary tensor with shape `(samples, time, 1)`,
            with a zero for every element that is masked.
        constants: a list of constant values passed at each step.
        unroll: whether to unroll the RNN or to use a symbolic loop (`while_loop` or `scan` depending on backend).
        input_length: not relevant in the TensorFlow implementation.
            Must be specified if using unrolling with Theano.

    # Returns
        A tuple, `(last_output, outputs, new_states)`.

            last_output: the latest output of the rnn, of shape `(samples, ...)`
            outputs: tensor with shape `(samples, time, ...)` where each
                entry `outputs[s, t]` is the output of the step function
                at time `t` for sample `s`.
            new_states: list of tensors, latest states returned by
                the step function, of shape `(samples, ...)`.

    # Raises
        ValueError: if input dimension is less than 3.
        ValueError: if `unroll` is `True` but input timestep is not a fixed number.
        ValueError: if `mask` is provided (not `None`) but states is not provided
            (`len(states)` == 0).
    i   s   Input should be at least 3D.i   i    i   s/   Unrolling requires a fixed number of timesteps.iR   Rz   t   tensor_array_namet	   output_tat   input_taR9   R   t   times   No initial states provided! When using masking in an RNN, you should provide initial states (and your step function should return as its first state at time `t` the output at time `t-1`).t   mask_tac            s#   j  |   }  j  |   }  | t |  t     \ } } x0 t | |  D] \ } } | j | j    qS Wt j | t j d t j |  d g   }	 t j	 |	 | | d  } g  t
 t |   D]# }
 t j	 |	 | |
 | |
  ^ q } | j |  |  } |  d | f t |  S(   s0  RNN step function.

                # Arguments
                    time: Current timestep value.
                    output_ta_t: TensorArray.
                    *states: List of states.

                # Returns
                    Tuple: `(time + 1,output_ta_t) + tuple(new_states)`
                i   i    (   t   readR[   R   R  RM   R   R  R   RU   t   whereRi   Rr   t   write(   R\  t   output_ta_tt   statest   current_inputt   mask_tR  t
   new_statest   statet	   new_statet   tiled_mask_tRo   (   t	   constantsR[  R]  t   step_function(    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyt   _step  s    		%<c            s    j  |   }  | t |  t     \ } } x0 t | |  D] \ } } | j | j    qD W| j |  |  } |  d | f t |  S(   s0  RNN step function.

                # Arguments
                    time: Current timestep value.
                    output_ta_t: TensorArray.
                    *states: List of states.

                # Returns
                    Tuple: `(time + 1,output_ta_t) + tuple(new_states)`
                i   (   R^  R[   R   R  RM   R`  (   R\  Ra  Rb  Rc  R  Re  Rf  Rg  (   Ri  R[  Rj  (    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyRk  
	  s    	t   condc            s
   |    k  S(   N(    (   R\  Rm   (   t
   time_steps(    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyt   <lambda>	  s    t   bodyt	   loop_varst   parallel_iterationsi    t   swap_memoryN(   Rr   RM   R#   R   Ri   R   R   R   R   R   R@   RQ   R   R+  R   R  R   RU   R{   R_  Rb   R[   R   t   TensorArrayRh   R   t
   while_loopR.   R^  (    Rj  R?  t   initial_statest   go_backwardst   maskRi  t   unrollt   input_lengthRk   R   Rb  t   successive_statest   successive_outputst
   input_listt	   mask_listt   inpRd  R  Re  Rh  t   prev_outputt   return_statesRf  Rg  t   last_outputR@  Rm   RZ  R\  Rk  t   final_outputst	   last_time(    (   Ri  R[  R]  Rj  Rm  s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyt   rnnM  s    1		%
	%



											


+c            s   |  j  t j k r' t j |  d  }  n  t   sE  f d   } n  } t    si   f d   } n   } t j |  | |  } | S(   s  Switches between two operations depending on a scalar value.

    Note that both `then_expression` and `else_expression`
    should be symbolic tensors of the *same shape*.

    # Arguments
        condition: scalar tensor (`int` or `bool`).
        then_expression: either a tensor, or a callable that returns a tensor.
        else_expression: either a tensor, or a callable that returns a tensor.

    # Returns
        The selected tensor.
    R   c              s     S(   N(    (    (   t   then_expression(    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyt   then_expression_fnA	  s    c              s     S(   N(    (    (   t   else_expression(    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyt   else_expression_fnF	  s    (   R   R   R   R@   t   callableRl  (   t	   conditionR  R  R  R  RA   (    (   R  R  s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyt   switch0	  s    		c         C   s   | d k r t   } t } n t } | d k s< | t k rV t |   rO |    S|  Sn2 | d k sn | t k r t |  r |   S| Sn  t | |  |  }  | r t |  _ n  |  S(   sL  Selects `x` in train phase, and `alt` otherwise.

    Note that `alt` should have the *same shape* as `x`.

    # Arguments
        x: What to return in train phase
            (tensor or callable that returns a tensor).
        alt: What to return otherwise
            (tensor or callable that returns a tensor).
        training: Optional scalar tensor
            (or Python boolean, or Python integer)
            specifing the learning phase.

    # Returns
        Either `x` or `alt` based on the `training` flag.
        the `training` flag defaults to `K.learning_phase()`.
    i   i    N(   R   R"   R.   RW   R  R  RX   (   RA   t   altt   trainingt   uses_learning_phase(    (    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyt   in_train_phaseP	  s     		c         C   s   t  | |  d | S(   s  Selects `x` in test phase, and `alt` otherwise.

    Note that `alt` should have the *same shape* as `x`.

    # Arguments
        x: What to return in test phase
            (tensor or callable that returns a tensor).
        alt: What to return otherwise
            (tensor or callable that returns a tensor).
        training: Optional scalar tensor
            (or Python boolean, or Python integer)
            specifing the learning phase.

    # Returns
        Either `x` or `alt` based on `K.learning_phase`.
    R  (   R  (   RA   R  R  (    (    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyt   in_test_phase{	  s    g        c         C   s   | d k r" t  j j |   } n  t  j j |   }  | d k	 r t | |  j j  } t d |  j j  } t  j |  | |  }  n  | d k r t | |  j j  } |  | | 8}  n  |  S(   s  Rectified linear unit.

    With default values, it returns element-wise `max(x, 0)`.

    # Arguments
        x: A tensor or variable.
        alpha: A scalar, slope of negative section (default=`0.`).
        max_value: Saturation threshold.

    # Returns
        A tensor.
    g        N(   R   R   t   reluR   RB   R   R   R   (   RA   t   alphaR   t   negative_partR   (    (    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyR  	  s    g      ?c         C   sC   t  j j |   } | d k r" | St  j |  d k | | |  Sd S(   s   Exponential linear unit.

    # Arguments
        x: A tenor or variable to compute the activation function for.
        alpha: A scalar, slope of positive section.

    # Returns
        A tensor.
    i   i    N(   R   R   t   eluR_  (   RA   R  t   res(    (    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyR  	  s    
c         C   s   t  j j |   S(   sl   Softmax of a tensor.

    # Arguments
        x: A tensor or variable.

    # Returns
        A tensor.
    (   R   R   t   softmax(   RA   (    (    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyR  	  s    	c         C   s   t  j j |   S(   sm   Softplus of a tensor.

    # Arguments
        x: A tensor or variable.

    # Returns
        A tensor.
    (   R   R   t   softplus(   RA   (    (    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyR  	  s    	c         C   s   t  j j |   S(   sm   Softsign of a tensor.

    # Arguments
        x: A tensor or variable.

    # Returns
        A tensor.
    (   R   R   t   softsign(   RA   (    (    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyR  	  s    	c         C   s   | s |  t  j |  d t |  j    d d t :}  t t |  j j  } t  j	 |  | d |  }  t  j | t  j
 |   d t |  j    d St  j j d | d |   Sd S(   s  Categorical crossentropy between an output tensor and a target tensor.

    # Arguments
        output: A tensor resulting from a softmax
            (unless `from_logits` is True, in which
            case `output` is expected to be the logits).
        target: A tensor of the same shape as `output`.
        from_logits: Boolean, whether `output` is the
            result of a softmax, or is a tensor of logits.

    # Returns
        Output tensor.
    R   i   R   g      ?t   labelst   logitsN(   R   R   Rr   RM   R.   RB   R   R   R   R   R   R   t!   softmax_cross_entropy_with_logits(   R  t   targett   from_logitsR   (    (    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyt   categorical_crossentropy	  s    
c         C   s   | sF t  t |  j j  } t j |  | d |  }  t j |   }  n  |  j   } t t	 |  d  } t j
 |  d t | d  g  } t j j d | d |  } t |  d k r t j
 | t j |   d   S| Sd S(   s  Categorical crossentropy with integer targets.

    # Arguments
        output: A tensor resulting from a softmax
            (unless `from_logits` is True, in which
            case `output` is expected to be the logits).
        target: An integer tensor.
        from_logits: Boolean, whether `output` is the
            result of a softmax, or is a tensor of logits.

    # Returns
        Output tensor.
    i   R:   iR  R  i   N(   RB   R   R   R   R   R   R   RM   R@   R   R   R   R   t(   sparse_softmax_cross_entropy_with_logitsRr   RU   (   R  R  R  R   t   output_shapet   targetsR  R  (    (    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyt   sparse_categorical_crossentropy	  s    "	c         C   sg   | sN t  t |  j j  } t j |  | d |  }  t j |  d |   }  n  t j j d | d |   S(   sw  Binary crossentropy between an output tensor and a target tensor.

    # Arguments
        output: A tensor.
        target: A tensor with the same shape as `output`.
        from_logits: Whether `output` is expected to be a logits tensor.
            By default, we consider that `output`
            encodes a probability distribution.

    # Returns
        A tensor.
    i   R  R  (	   RB   R   R   R   R   R   R   R   t!   sigmoid_cross_entropy_with_logits(   R  R  R  R   (    (    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyt   binary_crossentropy!
  s    c         C   s   t  j j |   S(   sm   Element-wise sigmoid.

    # Arguments
        x: A tensor or variable.

    # Returns
        A tensor.
    (   R   R   t   sigmoid(   RA   (    (    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyR  :
  s    	c         C   sQ   d |  d }  t  d |  j j  } t  d |  j j  } t j |  | |  }  |  S(   s  Segment-wise linear approximation of sigmoid.

    Faster than sigmoid.
    Returns `0.` if `x < -2.5`, `1.` if `x > 2.5`.
    In `-2.5 <= x <= 2.5`, returns `0.2 * x + 0.5`.

    # Arguments
        x: A tensor or variable.

    # Returns
        A tensor.
    g?g      ?g        g      ?(   RB   R   R   R   R   (   RA   R   t   one(    (    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyt   hard_sigmoidF
  s
    c         C   s   t  j j |   S(   sj   Element-wise tanh.

    # Arguments
        x: A tensor or variable.

    # Returns
        A tensor.
    (   R   R   t   tanh(   RA   (    (    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyR  Z
  s    	c         C   sK   d | } | d k r+ t j j d  } n  t j j |  d | | d | S(   s  Sets entries in `x` to zero at random, while scaling the entire tensor.

    # Arguments
        x: tensor
        level: fraction of the entries in the tensor
            that will be set to 0.
        noise_shape: shape for randomly generated keep/drop flags,
            must be broadcastable to the shape of `x`
        seed: random seed to ensure determinism.

    # Returns
        A tensor.
    g      ?g    cAR}   N(   R   RO   R~   R   R   R   t   dropout(   RA   t   levelt   noise_shapeR}   t   retain_prob(    (    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyR  f
  s    
c         C   s;   | d k  r% | t  |  j    ;} n  t j j |  d | S(   s   Normalizes a tensor wrt the L2 norm alongside the specified axis.

    # Arguments
        x: Tensor or variable.
        axis: axis along which to perform normalization.

    # Returns
        A tensor.
    i    t   dim(   Rr   RM   R   R   t   l2_normalize(   RA   R   (    (    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyR  |
  s    
c         C   s   t  j j |  | |  S(   s  Returns whether the `targets` are in the top `k` `predictions`.

    # Arguments
        predictions: A tensor of shape `batch_size` x classes and type `float32`.
        targets: A tensor of shape batch_size and type `int32` or `int64`.
        k: An `int`, number of top elements to consider.

    # Returns
        A tensor of shape `batch_size` and type `bool`. `output_i` is `True` if
        `targets_i` is within top-k values of `predictions_i`
    (   R   R   t   in_top_k(   t   predictionsR  t   k(    (    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyR  
  s    c         C   s   | d k r1 | d | d | d | d f } n  | d d  k r} t j |   d f t | d  } t j t |   } n  | S(   NR   i    i   i   i   (   R   R   RU   R[   R   R   (   RA   RU   R  (    (    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyt   _preprocess_deconv_output_shape
  s    %$c         C   sL   t  |   d k r' t j |  d  }  n  | d k rH t j |  d  }  n  |  S(	   NR7   R6   R   i    i   i   i   (   i    i   i   i   (   R   R   R@   R   (   RA   R  (    (    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyt   _preprocess_conv2d_input
  s
    c         C   sL   t  |   d k r' t j |  d  }  n  | d k rH t j |  d	  }  n  |  S(
   NR7   R6   R   i    i   i   i   i   (   i    i   i   i   i   (   R   R   R@   R   (   RA   R  (    (    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyt   _preprocess_conv3d_input
  s
    c         C   sL   t  |   d k r' t j |  d  }  n  | d k rH t j |  d  }  n  |  S(	   NR7   R6   R   i   i   i   i    (   i   i   i   i    (   R   R   R@   R   (   t   kernelR  (    (    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyt   _preprocess_conv2d_kernel
  s
    c         C   sL   t  |   d k r' t j |  d  }  n  | d k rH t j |  d	  }  n  |  S(
   NR7   R6   R   i   i   i   i   i    (   i   i   i   i   i    (   R   R   R@   R   (   R  R  (    (    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyt   _preprocess_conv3d_kernel
  s
    c         C   s=   |  d k r d }  n$ |  d k r* d }  n t  d |    |  S(   Nt   samet   SAMEt   validt   VALIDs   Invalid border mode:(   R#   (   R$  (    (    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyt   _preprocess_padding
  s    		c         C   sI   | d k r! t  j |  d  }  n  t   d k rE t  j |  d  }  n  |  S(   NR   i    i   i   i   R7   (   i    i   i   i   (   R   R   R   R@   (   RA   R  (    (    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyt   _postprocess_conv2d_output
  s
    c         C   sI   | d k r! t  j |  d  }  n  t   d k rE t  j |  d  }  n  |  S(	   NR   i    i   i   i   i   R7   (   i    i   i   i   i   (   R   R   R   R@   (   RA   R  (    (    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyt   _postprocess_conv3d_output
  s
    R  c   	      C   s   | j    j   } | d k rN | | d d } t |  | d f  }  d } n  t |  } | d k ro d } n d } t j j d |  d	 | d
 | f d | f d | d |  }  |  S(   sn  1D convolution.

    # Arguments
        x: Tensor or variable.
        kernel: kernel tensor.
        strides: stride integer.
        padding: string, `"same"`, `"causal"` or `"valid"`.
        data_format: string, one of "channels_last", "channels_first".
        dilation_rate: integer dilate rate.

    # Returns
        A tensor, result of 1D convolution.
    t   causali    i   R  R   t   NWCt   NCWt   inputt   filtert   dilation_ratet   stridesR$  R  (   RM   R  R%  R  R   R   t   convolution(	   RA   R  R  R$  R  R  t   kernel_shapet   left_padt   tf_data_format(    (    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyt   conv1d
  s"    					c         C   s   | d k r t   } n  | d d h k rC t d t |    n  t |  |  }  t |  } t j j d |  d | d | d | d | d	 d
  }  t	 |  |  S(   s  2D convolution.

    # Arguments
        x: Tensor or variable.
        kernel: kernel tensor.
        strides: strides tuple.
        padding: string, `"same"` or `"valid"`.
        data_format: `"channels_last"` or `"channels_first"`.
            Whether to use Theano or TensorFlow data format
            for inputs/kernels/ouputs.
        dilation_rate: tuple of 2 integers.

    # Returns
        A tensor, result of 2D convolution.

    # Raises
        ValueError: if `data_format` is neither `channels_last` or `channels_first`.
    R   R   s   Unknown data_format R  R  R  R  R$  R  t   NHWCN(
   R   R   R#   R  R  R  R   R   R  R  (   RA   R  R  R$  R  R  (    (    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyt   conv2d
  s    	c         C   s   | d k r t   } n  | d d h k rC t d t |    n  t | t t f  rj t j |  } n  t	 |  |  }  t
 |  | |  } t |  } d | d } t j j |  | | | d | }  t |  |  }  |  S(	   sW  2D deconvolution (i.e. transposed convolution).

    # Arguments
        x: Tensor or variable.
        kernel: kernel tensor.
        output_shape: 1D int tensor for the output shape.
        strides: strides tuple.
        padding: string, `"same"` or `"valid"`.
        data_format: `"channels_last"` or `"channels_first"`.
            Whether to use Theano or TensorFlow data format
            for inputs/kernels/ouputs.

    # Returns
        A tensor, result of transposed 2D convolution.

    # Raises
        ValueError: if `data_format` is neither `channels_last` or `channels_first`.
    R   R   s   Unknown data_format i   R$  N(   i   (   i   (   R   R   R#   R  RC   R[   R   R   R   R  R  R  R   t   conv2d_transposeR  (   RA   R  R  R  R$  R  (    (    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyR  2  s    	c      
   C   s   | d k r t   } n  | d d h k rC t d t |    n  t |  |  }  t |  } d	 | d
 } t j j |  | | d | d | d | }  t	 |  |  S(   sk  2D convolution with separable filters.

    # Arguments
        x: input tensor
        depthwise_kernel: convolution kernel for the depthwise convolution.
        pointwise_kernel: kernel for the 1x1 convolution.
        strides: strides tuple (length 2).
        padding: padding mode, "valid" or "same".
        data_format: data format, "channels_first" or "channels_last".
        dilation_rate: tuple of integers,
            dilation rates for the separable convolution.

    # Returns
        Output tensor.

    # Raises
        ValueError: if `data_format` is neither `channels_last` or `channels_first`.
    R   R   s   Unknown data_format i   R  R$  t   rateN(   i   (   i   (
   R   R   R#   R  R  R  R   R   t   separable_conv2dR  (   RA   t   depthwise_kernelt   pointwise_kernelR  R$  R  R  (    (    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyR  X  s    	c         C   s   | d k r t   } n  | d d h k rC t d t |    n  t |  |  }  t |  } t j j d |  d | d | d | d | d	 d
  }  t	 |  |  S(   s  3D convolution.

    # Arguments
        x: Tensor or variable.
        kernel: kernel tensor.
        strides: strides tuple.
        padding: string, `"same"` or `"valid"`.
        data_format: `"channels_last"` or `"channels_first"`.
            Whether to use Theano or TensorFlow data format
            for inputs/kernels/ouputs.
        dilation_rate: tuple of 3 integers.

    # Returns
        A tensor, result of 3D convolution.

    # Raises
        ValueError: if `data_format` is neither `channels_last` or `channels_first`.
    R   R   s   Unknown data_format R  R  R  R  R$  R  t   NDHWCN(
   R   R   R#   R  R  R  R   R   R  R  (   RA   R  R  R$  R  R  (    (    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyt   conv3d|  s    	R   c         C   s   | d	 k r t   } n  | d d h k rC t d t |    n  t |  } d
 | d } d | d } t |  |  }  | d k r t j j |  | | d | }  n< | d k r t j j	 |  | | d | }  n t d |   t
 |  |  S(   s  2D Pooling.

    # Arguments
        x: Tensor or variable.
        pool_size: tuple of 2 integers.
        strides: tuple of 2 integers.
        padding: one of `"valid"`, `"same"`.
        data_format: one of `"channels_first"`, `"channels_last"`.
        pool_mode: one of `"max"`, `"avg"`.

    # Returns
        A tensor, result of 2D pooling.

    # Raises
        ValueError: if `data_format` is neither `channels_last` or `channels_first`.
        ValueError: if `pool_mode` is neither `max` or `avg`.
    R   R   s   Unknown data_format i   R   R$  t   avgs   Invalid pooling mode:N(   i   (   i   (   i   (   i   (   R   R   R#   R  R  R  R   R   t   max_poolt   avg_poolR  (   RA   t	   pool_sizeR  R$  R  t	   pool_mode(    (    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyt   pool2d  s    !!c         C   s   | d	 k r t   } n  | d d h k rC t d t |    n  t |  } d
 | d } d | d } t |  |  }  | d k r t j j |  | | d | }  n< | d k r t j j	 |  | | d | }  n t d |   t
 |  |  S(   s  3D Pooling.

    # Arguments
        x: Tensor or variable.
        pool_size: tuple of 3 integers.
        strides: tuple of 3 integers.
        padding: one of `"valid"`, `"same"`.
        data_format: one of `"channels_first"`, `"channels_last"`.
        pool_mode: one of `"max"`, `"avg"`.

    # Returns
        A tensor, result of 3D pooling.

    # Raises
        ValueError: if `data_format` is neither
            `channels_last` or `channels_first`.
        ValueError: if `pool_mode` is neither `max` or `avg`.
    R   R   s   Unknown data_format i   R   R$  R  s   Invalid pooling mode:N(   i   (   i   (   i   (   i   (   R   R   R#   R  R  R  R   R   t
   max_pool3dt
   avg_pool3dR  (   RA   R  R  R$  R  R  (    (    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyt   pool3d  s    !!c      	   C   s  | d k r t   } n  | d d h k rC t d t |    n  t |   d k r | d k r |  t | d t |  d d d d f  7}  q| d k r|  t | d d d d t |  d f  7}  qnt |   d k rE| d k r|  t | d t |  d d d f  7}  q| d k rt j j	 |  | d d	 }  qn t |   d
 k r| d k r|  t | d t |  d d f  7}  q| d k r|  t | d d t |  d f  7}  qn t j j	 |  |  }  |  S(   sZ  Adds a bias vector to a tensor.

    # Arguments
        x: Tensor or variable.
        bias: Bias tensor to add.
        data_format: Data format for 3D, 4D or 5D tensors:
            one of "channels_first", "channels_last".

    # Returns
        Output tensor.

    # Raises
        ValueError: In case of invalid `data_format` argument.
    R   R   s   Unknown data_format i   i   i    i   R  R  i   N(
   R   R   R#   R  Rk   R   Rp   R   R   t   bias_add(   RA   t   biasR  (    (    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyR    s,    /2,),c      
   C   s^   | d k r t   } n  | d k r9 t j j d  } n  t j |  d | d | d | d | S(   s  Returns a tensor with normal distribution of values.

    # Arguments
        shape: A tuple of integers, the shape of tensor to create.
        mean: A float, mean of the normal distribution to draw samples.
        stddev: A float, standard deviation of the normal distribution
            to draw samples.
        dtype: String, dtype of returned tensor.
        seed: Integer, random seed.

    # Returns
        A tensor.
    g    cAR   t   stddevR   R}   N(   R   R   RO   R~   R   R   t   random_normal(   RU   R   R  R   R}   (    (    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyR     s    c      
   C   s^   | d k r t   } n  | d k r9 t j j d  } n  t j |  d | d | d | d | S(   s  Returns a tensor with uniform distribution of values.

    # Arguments
        shape: A tuple of integers, the shape of tensor to create.
        minval: A float, lower boundary of the uniform distribution
            to draw samples.
        maxval: A float, upper boundary of the uniform distribution
            to draw samples.
        dtype: String, dtype of returned tensor.
        seed: Integer, random seed.

    # Returns
        A tensor.
    g    cAt   minvalt   maxvalR   R}   N(   R   R   RO   R~   R   R   t   random_uniform(   RU   R  R  R   R}   (    (    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyR  6  s    c         C   s   | d k r t   } n  | d k r9 t j j d  } n  t j t j |  d | d | | k t j |  d | t j	 |  d |  S(   sV  Returns a tensor with random binomial distribution of values.

    # Arguments
        shape: A tuple of integers, the shape of tensor to create.
        p: A float, `0. <= p <= 1`, probability of binomial distribution.
        dtype: String, dtype of returned tensor.
        seed: Integer, random seed.

    # Returns
        A tensor.
    g    cAR   R}   N(
   R   R   RO   R~   R   R   R_  R  Rx   Rw   (   RU   RG  R   R}   (    (    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyt   random_binomialM  s    $c         C   sX   | d k r t   } n  | d k r9 t j j d  } n  t j |  | | d | d | S(   sH  Returns a tensor with truncated random normal distribution of values.

    The generated values follow a normal distribution
    with specified mean and standard deviation,
    except that values whose magnitude is more than
    two standard deviations from the mean are dropped and re-picked.

    # Arguments
        shape: A tuple of integers, the shape of tensor to create.
        mean: Mean of the values.
        stddev: Standard deviation of the values.
        dtype: String, dtype of returned tensor.
        seed: Integer, random seed.

    # Returns
        A tensor.
    g    cAR   R}   N(   R   R   RO   R~   R   R   t   truncated_normal(   RU   R   R  R   R}   (    (    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyR  b  s
    c            s  t  j |     t  j   d g  } t  j   d g      f d   } t  j t  j d   d g d  t  j  } t j | | d | d d } | d d  d d d  f } t  j t  j	 t  j
 d   d  |     } t  j | |  } t  j t  j t  j	 t  j
 d   d    t   d    } t  j | |  }	 t  j t  j t |	 | g d d d d	 g   }
 t  j |  |
  } t  j t  j |
  | t  j     S(
   s   Converts CTC labels from dense to sparse.

    # Arguments
        labels: dense CTC labels.
        label_lengths: length of the labels.

    # Returns
        A sparse tensor representation of the lablels.
    i    i   c            s/   t  j t  j   d  d  t  j  |  k  S(   Ni   i    (   R   RQ   Ri   t   fill(   Rm   Rc  (   t   label_shapet   max_num_labels_tns(    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyt   range_less_than  s    "t   initializerRq  NR   i   i(   R   RU   R   R@   R  R   R   t   scanR   R  Ri   t   boolean_maskR   R+  RP   t	   gather_ndRD   t   to_int64(   R  t   label_lengthst   num_batches_tnsR  t   initt
   dense_maskt   label_arrayt	   label_indt   batch_arrayt	   batch_indRJ   t   vals_sparse(    (   R  R  s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyt   ctc_label_dense_to_sparse  s"    
+%	%3c         C   s   t  j t  j |   } t  j t  j |   } t  j t |  |   } t  j t  j | d d d d g d  } t  j t j d | d | d |  d  S(	   s}  Runs CTC loss algorithm on each batch element.

    # Arguments
        y_true: tensor `(samples, max_string_length)`
            containing the truth labels.
        y_pred: tensor `(samples, time_steps, num_categories)`
            containing the prediction, or output of the softmax.
        input_length: tensor `(samples, 1)` containing the sequence length for
            each batch item in `y_pred`.
        label_length: tensor `(samples, 1)` containing the sequence length for
            each batch item in `y_true`.

    # Returns
        Tensor with shape (samples,1) containing the
            CTC loss of each element.
    R   i   i    i   g:0yE>R?  R  t   sequence_length(	   R   t   to_int32R"  R  R   R   RQ   t   ctct   ctc_loss(   t   y_truet   y_predRy  t   label_lengtht   sparse_labels(    (    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyt   ctc_batch_cost  s    +id   c   	   	   C   s   t  j t  j |  d d d d g d  }  t  j |  } | ra t j d |  d |  \ } } n* t j d |  d | d | d	 |  \ } } g  | D]* } t  j | j | j	 | j
 d
 d ^ q } | | f S(   s  Decodes the output of a softmax.

    Can use either greedy search (also known as best path)
    or a constrained dictionary search.

    # Arguments
        y_pred: tensor `(samples, time_steps, num_categories)`
            containing the prediction, or output of the softmax.
        input_length: tensor `(samples, )` containing the sequence length for
            each batch item in `y_pred`.
        greedy: perform much faster best-path search if `true`.
            This does not use a dictionary.
        beam_width: if `greedy` is `false`: a beam search decoder will be used
            with a beam of this width.
        top_paths: if `greedy` is `false`,
            how many of the most probable paths will be returned.

    # Returns
        Tuple:
            List: if `greedy` is `true`, returns a list of one element that
                contains the decoded sequence.
                If `false`, returns the `top_paths` most probable
                decoded sequences.
                Important: blank labels are returned as `-1`.
            Tensor `(top_paths, )` that contains
                the log probability of each decoded sequence.
    R   i   i    i   g:0yE>R?  R  t
   beam_widtht	   top_pathst   default_valuei(   R   R   R   R  R  t   ctc_greedy_decodert   ctc_beam_search_decodert   sparse_to_denseRJ   RL   RK   (	   R  Ry  t   greedyR  R  t   decodedt   log_probt   stt   decoded_dense(    (    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyt
   ctc_decode  s    +		4c         C   s   t  j |  | d | S(   sV  Map the function fn over the elements elems and return the outputs.

    # Arguments
        fn: Callable that will be called upon each element in elems
        elems: tensor
        name: A string name for the map node in the graph

    # Returns
        Tensor with first dimension equal to the elems and second depending on
        fn
    R   (   R   t   map_fn(   t   fnt   elemsR   (    (    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyR    s    c         C   s   t  j |  | d | d | S(   s  Reduce elems using fn to combine them from left to right.

    # Arguments
        fn: Callable that will be called upon each element in elems and an
            accumulator, for instance `lambda acc, x: acc + x`
        elems: tensor
        initializer: The first value used (`elems[0]` in case of None)
        name: A string name for the foldl node in the graph

    # Returns
        Same type and shape as initializer
    R  R   (   R   t   foldl(   R  R  R  R   (    (    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyR    s    c         C   s   t  j |  | d | d | S(   s  Reduce elems using fn to combine them from right to left.

    # Arguments
        fn: Callable that will be called upon each element in elems and an
            accumulator, for instance `lambda acc, x: acc + x`
        elems: tensor
        initializer: The first value used (`elems[-1]` in case of None)
        name: A string name for the foldr node in the graph

    # Returns
        Same type and shape as initializer
    R  R   (   R   t   foldr(   R  R  R  R   (    (    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyR    s    (   i   i   (   i   i   (   i   i   (   i   i   (   i   i   (   i   i   (   i   i   (   i   i   (   i   i   (   i   i   (   i   i   (   i   i   i   (   i   i   i   (   i   i   (   i   i   i   (   t
   tensorflowR   t   tensorflow.python.trainingR    t   tensorflow.python.opsR   R   R   R   R  t   collectionsR   t   numpyRO   R*   RO  t   commonR   R   R   R	   R
   R   R   R   t   py_sumR   R   R   R   RW   R   R   R   R   R!   R"   R$   R3   R4   R>   RB   RF   RH   t
   name_scopeR_   R0   Rh   R   RU   Rp   Rk   R   Rt   Rw   Rx   Ry   R{   R|   R   R   R   R@   R   R   R   R   R   R   R   R   R   R   R   R   R   R   R   R   R   R   R   R   R   R   R   R   R   R   R   R   R   R   R   R   R   R   R   R   R   R   R   RP   R   R   R	  R  R
  R  R  R  R   R!  RQ   R"  R%  R&  R'  R   R)  R+  R,  R.  R5  R8  R9  R<  t   objectR=  RT  RV  RX  R  R  R  R  R  R  R  R  R  R  R  R  R  R  R  R  R  R  R  R  R  R  R  R  R  R  R  R  R  R  R  R  R  R  R  R  R  R  R  R  R.   R  R  R  R  (    (    (    s?   /tmp/pip-build-isqEY4/keras/keras/backend/tensorflow_backend.pyt   <module>   s`  							"						.	(					%%		#					FG	#																					.			&							#4							2				 +			"						
					
				#'%#''(* 	%	0