B
    ӻd                 @   s   d 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 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mZ ddlmZ ddlmZ ddlmZ G dd deZG dd dee
ZedG dd deZdS )zConvolutional-recurrent layers.    N)activations)backend)constraints)initializers)regularizers)Layer)	InputSpec)DropoutRNNCellMixin)RNN)
conv_utils)generic_utils)tf_utils)	array_ops)keras_exportc                   sZ   e Zd ZdZd fdd	Zejdd Zejdd Zd	d
 Z	dddZ
dddZ  ZS )	ConvRNN2Da]  Base class for convolutional-recurrent layers.

  Args:
    cell: A RNN cell instance. A RNN cell is a class that has:
      - a `call(input_at_t, states_at_t)` method, returning
        `(output_at_t, states_at_t_plus_1)`. The call method of the
        cell can also take the optional argument `constants`, see
        section "Note on passing external constants" below.
      - a `state_size` attribute. This can be a single integer
        (single state) in which case it is
        the number of channels of the recurrent state
        (which should be the same as the number of channels of the cell
        output). This can also be a list/tuple of integers
        (one size per state). In this case, the first entry
        (`state_size[0]`) should be the same as
        the size of the cell output.
    return_sequences: Boolean. Whether to return the last output.
      in the output sequence, or the full sequence.
    return_state: Boolean. Whether to return the last state
      in addition to the output.
    go_backwards: Boolean (default False).
      If True, process the input sequence backwards and return the
      reversed sequence.
    stateful: Boolean (default False). If True, the last state
      for each sample at index i in a batch will be used as initial
      state for the sample of index i in the following batch.
    input_shape: Use this argument to specify the shape of the
      input when this layer is the first one in a model.

  Call arguments:
    inputs: A 5D tensor.
    mask: Binary tensor of shape `(samples, timesteps)` indicating whether
      a given timestep should be masked.
    training: Python boolean indicating whether the layer should behave in
      training mode or in inference mode. This argument is passed to the cell
      when calling it. This is for use with cells that use dropout.
    initial_state: List of initial state tensors to be passed to the first
      call of the cell.
    constants: List of constant tensors to be passed to the cell at each
      timestep.

  Input shape:
    5D tensor with shape:
    `(samples, timesteps, channels, rows, cols)`
    if data_format='channels_first' or 5D tensor with shape:
    `(samples, timesteps, rows, cols, channels)`
    if data_format='channels_last'.

  Output shape:
    - If `return_state`: a list of tensors. The first tensor is
      the output. The remaining tensors are the last states,
      each 4D tensor with shape:
      `(samples, filters, new_rows, new_cols)`
      if data_format='channels_first'
      or 4D tensor with shape:
      `(samples, new_rows, new_cols, filters)`
      if data_format='channels_last'.
      `rows` and `cols` values might have changed due to padding.
    - If `return_sequences`: 5D tensor with shape:
      `(samples, timesteps, filters, new_rows, new_cols)`
      if data_format='channels_first'
      or 5D tensor with shape:
      `(samples, timesteps, new_rows, new_cols, filters)`
      if data_format='channels_last'.
    - Else, 4D tensor with shape:
      `(samples, filters, new_rows, new_cols)`
      if data_format='channels_first'
      or 4D tensor with shape:
      `(samples, new_rows, new_cols, filters)`
      if data_format='channels_last'.

  Masking:
    This layer supports masking for input data with a variable number
    of timesteps.

  Note on using statefulness in RNNs:
    You can set RNN layers to be 'stateful', which means that the states
    computed for the samples in one batch will be reused as initial states
    for the samples in the next batch. This assumes a one-to-one mapping
    between samples in different successive batches.
    To enable statefulness:
      - Specify `stateful=True` in the layer constructor.
      - Specify a fixed batch size for your model, by passing
         - If sequential model:
            `batch_input_shape=(...)` to the first layer in your model.
         - If functional model with 1 or more Input layers:
            `batch_shape=(...)` to all the first layers in your model.
            This is the expected shape of your inputs
            *including the batch size*.
            It should be a tuple of integers,
            e.g. `(32, 10, 100, 100, 32)`.
            Note that the number of rows and columns should be specified
            too.
      - Specify `shuffle=False` when calling fit().
    To reset the states of your model, call `.reset_states()` on either
    a specific layer, or on your entire model.

  Note on specifying the initial state of RNNs:
    You can specify the initial state of RNN layers symbolically by
    calling them with the keyword argument `initial_state`. The value of
    `initial_state` should be a tensor or list of tensors representing
    the initial state of the RNN layer.
    You can specify the initial state of RNN layers numerically by
    calling `reset_states` with the keyword argument `states`. The value of
    `states` should be a numpy array or list of numpy arrays representing
    the initial state of the RNN layer.

  Note on passing external constants to RNNs:
    You can pass "external" constants to the cell using the `constants`
    keyword argument of `RNN.__call__` (as well as `RNN.call`) method. This
    requires that the `cell.call` method accepts the same keyword argument
    `constants`. Such constants can be used to condition the cell
    transformation on additional static inputs (not changing over time),
    a.k.a. an attention mechanism.
  Fc                s^   |rt dt|ttfr"t dtt| j||||||f| tddg| _d | _	d | _
d S )Nz1Unrolling isn't possible with convolutional RNNs.z=It is not possible at the moment tostack convolutional cells.   )ndim)	TypeError
isinstancelisttuplesuperr   __init__r   
input_specstates_num_constants)selfcellreturn_sequencesreturn_statego_backwardsstatefulZunrollkwargs)	__class__ h/var/www/html/venv/lib/python3.7/site-packages/tensorflow/python/keras/layers/convolutional_recurrent.pyr      s    zConvRNN2D.__init__c                sp  t trd | j  jdkr4d d n jdkrNd d tj jd  j jd  j	d dtj jd  j jd  j	d d jdkrd d  j
f }n" jdkrd d  j
f }| js|d d |dd   }| jrl|g} jdkr@| fd	d
tdD 7 }n, jdkrl| fdd
tdD 7 }|S )Nr   channels_first      channels_last   )paddingZstrideZdilation   c                s   g | ]}d   j fqS )r   )filters).0_)r   colsinput_shaperowsr$   r%   
<listcomp>   s   z2ConvRNN2D.compute_output_shape.<locals>.<listcomp>c                s   g | ]}d   j fqS )r   )r-   )r.   r/   )r   r0   r1   r2   r$   r%   r3      s   )r   r   r   data_formatr   Zconv_output_lengthkernel_sizer+   stridesdilation_rater-   r   r   range)r   r1   Zoutput_shaper$   )r   r0   r1   r2   r%   compute_output_shape   sD    





zConvRNN2D.compute_output_shapec                s  | j d k	r|| j  d  }nd }t|tr2|d }| jr@|d nd }t|d f|dd  d| jd< t| jtr|d f|dd   }|d k	r| j|g|  n| j| t	| jj
drt| jj
}n
| jj
g}| jd k	r@| jjdkrd n| jjdkrd	  fd
d| jD |kr~tddd | jD | jj
n>| jjdkr`dd |D | _n| jjdkr~dd |D | _| jr|   d| _d S )Nr   r*   r   )shape__len__r&   r,   r)   r'   c                s   g | ]}|j   qS r$   )r:   )r.   spec)ch_dimr$   r%   r3      s    z#ConvRNN2D.build.<locals>.<listcomp>zAn initial_state was passed that is not compatible with `cell.state_size`. Received `state_spec`={}; However `cell.state_size` is {}c             S   s   g | ]
}|j qS r$   )r:   )r.   r<   r$   r$   r%   r3     s    c             S   s   g | ]}t d |d d fdqS )N)r:   )r   )r.   dimr$   r$   r%   r3   	  s   c             S   s   g | ]}t d d d |fdqS )N)r:   )r   )r.   r>   r$   r$   r%   r3     s   T)r   r   r   r!   r   r   r   r   buildhasattr
state_sizeZ
state_specr4   
ValueErrorformatreset_statesbuilt)r   r1   Zconstants_shapeZ
batch_sizeZstep_input_shaperA   r$   )r=   r%   r?      sD    

 

zConvRNN2D.buildc                s   t | t j dd t| jj}| jj|d< | jj t	t
| j| jjd t| jjdrx fdd| jjD S  gS d S )Nr,   )axis)r+   r;   c                s   g | ]} qS r$   r$   )r.   r/   )initial_stater$   r%   r3     s    z/ConvRNN2D.get_initial_state.<locals>.<listcomp>)r   Z
zeros_likesumr   r   kernel_shaper-   
input_convr   zerosr   dtyper+   r@   rA   )r   inputsr:   r$   )rH   r%   get_initial_state  s    

zConvRNN2D.get_initial_stateNc          	      s   |||\}}}t|tr&|d }t|d }i  tjjdrP| d< |r|tjjdslt	d fdd}n fdd}tj
||||j||d	\}}	}
jrd
d tj|
D }| jr|	}n|}jrt|
ttfs|
g}
nt|
}
|g|
 S |S d S )Nr   r,   training	constantsz#RNN cell does not support constantsc                s:   |j  d  }|d j   }jj| |fd|i S )NrQ   )r   r   call)rN   r   rQ   )r"   r   r$   r%   step:  s    zConvRNN2D.call.<locals>.stepc                s   j j| |f S )N)r   rR   )rN   r   )r"   r   r$   r%   rS   ?  s    )rQ   r    maskZinput_lengthc             S   s   g | ]\}}t ||qS r$   )r   update)r.   Z
self_statestater$   r$   r%   r3   K  s   z"ConvRNN2D.call.<locals>.<listcomp>)Z_process_inputsr   r   r   Z	int_shaper   has_argr   rR   rB   Zrnnr    r!   zipr   Z
add_updater   r   r   )r   rN   rT   rP   rH   rQ   Z	timestepsrS   Zlast_outputoutputsr   Zupdatesoutputr$   )r"   r   r%   rR   #  sB    


zConvRNN2D.callc                s@  j stdjd j}|jr2d jrRd d dd  d krbtdfdd j	d d krt
jjdr fd	d
jjD _	nt jjg_	n||d kr4t
jjdrxTtj	jjD ]\}}t|t | qW n tj	d t jj nt|ttfsJ|g}t|tj	krtdj d ttj	 d d tt| d t| xtt|j	D ]\}\}}t
jjdrڈjj| }njj}|j |kr*tdt| d j d t | d t|j t|| qW d S )NzLayer must be stateful.r   r,   r*   a  If a RNN is stateful, it needs to know its batch size. Specify the batch size of your input tensors: 
- If using a Sequential model, specify the batch size by passing a `batch_input_shape` argument to your first layer.
- If using the functional API, specify the time dimension by passing a `batch_shape` argument to your Input layer.
The same thing goes for the number of rows and columns.c                s@   t } jjdkr| |d< n jjdkr4| |d< ntt|S )Nr&   r,   r)   r'   )r   r   r4   KeyErrorr   )Znb_channelsresult)r   state_shaper$   r%   get_tuple_shapev  s    

z/ConvRNN2D.reset_states.<locals>.get_tuple_shaper;   c                s   g | ]}t  |qS r$   )r   rL   )r.   r>   )r^   r$   r%   r3     s   z*ConvRNN2D.reset_states.<locals>.<listcomp>zLayer z	 expects z	 states, zbut it received z state values. Input received: zState z is incompatible with layer z: expected shape=z, found shape=)r!   AttributeErrorr   r:   r9   r   r   concatenaterB   r   r@   r   rA   r   rL   rX   	set_valuenpr   r   r   lennamestr	enumerate)r   r   r1   rV   r>   indexvaluer$   )r^   r   r]   r%   rD   ^  sF    


>6zConvRNN2D.reset_states)FFFFF)NNNN)N)__name__
__module____qualname____doc__r   r   Zshape_type_conversionr9   r?   rO   rR   rD   __classcell__r$   r$   )r#   r%   r   %   s   s    )5   
6r   c                   sR   e Zd ZdZd fdd	Zdd ZdddZdddZdd Z fddZ	  Z
S )ConvLSTM2DCella  Cell class for the ConvLSTM2D layer.

  Args:
    filters: Integer, the dimensionality of the output space
      (i.e. the number of output filters in the convolution).
    kernel_size: An integer or tuple/list of n integers, specifying the
      dimensions of the convolution window.
    strides: An integer or tuple/list of n integers,
      specifying the strides of the convolution.
      Specifying any stride value != 1 is incompatible with specifying
      any `dilation_rate` value != 1.
    padding: One of `"valid"` or `"same"` (case-insensitive).
      `"valid"` means no padding. `"same"` results in padding evenly to 
      the left/right or up/down of the input such that output has the same 
      height/width dimension as the input.
    data_format: A string,
      one of `channels_last` (default) or `channels_first`.
      It defaults to the `image_data_format` value found in your
      Keras config file at `~/.keras/keras.json`.
      If you never set it, then it will be "channels_last".
    dilation_rate: An integer or tuple/list of n integers, specifying
      the dilation rate to use for dilated convolution.
      Currently, specifying any `dilation_rate` value != 1 is
      incompatible with specifying any `strides` value != 1.
    activation: Activation function to use.
      If you don't specify anything, no activation is applied
      (ie. "linear" activation: `a(x) = x`).
    recurrent_activation: Activation function to use
      for the recurrent step.
    use_bias: Boolean, whether the layer uses a bias vector.
    kernel_initializer: Initializer for the `kernel` weights matrix,
      used for the linear transformation of the inputs.
    recurrent_initializer: Initializer for the `recurrent_kernel`
      weights matrix,
      used for the linear transformation of the recurrent state.
    bias_initializer: Initializer for the bias vector.
    unit_forget_bias: Boolean.
      If True, add 1 to the bias of the forget gate at initialization.
      Use in combination with `bias_initializer="zeros"`.
      This is recommended in [Jozefowicz et al., 2015](
        http://www.jmlr.org/proceedings/papers/v37/jozefowicz15.pdf)
    kernel_regularizer: Regularizer function applied to
      the `kernel` weights matrix.
    recurrent_regularizer: Regularizer function applied to
      the `recurrent_kernel` weights matrix.
    bias_regularizer: Regularizer function applied to the bias vector.
    kernel_constraint: Constraint function applied to
      the `kernel` weights matrix.
    recurrent_constraint: Constraint function applied to
      the `recurrent_kernel` weights matrix.
    bias_constraint: Constraint function applied to the bias vector.
    dropout: Float between 0 and 1.
      Fraction of the units to drop for
      the linear transformation of the inputs.
    recurrent_dropout: Float between 0 and 1.
      Fraction of the units to drop for
      the linear transformation of the recurrent state.

  Call arguments:
    inputs: A 4D tensor.
    states:  List of state tensors corresponding to the previous timestep.
    training: Python boolean indicating whether the layer should behave in
      training mode or in inference mode. Only relevant when `dropout` or
      `recurrent_dropout` is used.
  r,   r,   validNtanhhard_sigmoidTglorot_uniform
orthogonalrL           c                s&  t t| jf | || _t|dd| _t|dd| _t|| _	t
|| _t|dd| _t|| _t|| _|	| _t|
| _t|| _t|| _|| _t|| _t|| _t|| _t|| _t|| _t|| _tdt d|| _!tdt d|| _"| j| jf| _#d S )Nr*   r5   r6   r7   g      ?g        )$r   rn   r   r-   r   Znormalize_tupler5   r6   Znormalize_paddingr+   Znormalize_data_formatr4   r7   r   get
activationrecurrent_activationuse_biasr   kernel_initializerrecurrent_initializerbias_initializerunit_forget_biasr   kernel_regularizerrecurrent_regularizerbias_regularizerr   kernel_constraintrecurrent_constraintbias_constraintminmaxdropoutrecurrent_dropoutrA   )r   r-   r5   r6   r+   r4   r7   rw   rx   ry   rz   r{   r|   r}   r~   r   r   r   r   r   r   r   r"   )r#   r$   r%   r     s0    zConvLSTM2DCell.__init__c                s    j dkrd}nd}|| d kr(td|| } j| jd f }| _ j j jd f } j| jd j jd _	 j| j
d j jd _ jr܈ jr fd	d
}n j} j jd fd| j jd _nd  _d _d S )Nr&   r,   rG   zDThe channel dimension of the inputs should be defined. Found `None`.r(   kernel)r:   initializerrd   regularizer
constraintrecurrent_kernelc                sN   t  j jff||td jff|| j jd ff||gS )NZonesr*   )r   r`   r|   r-   r   rv   )r/   argsr"   )r   r$   r%   r|   9  s    z.ConvLSTM2DCell.build.<locals>.bias_initializerbias)r:   rd   r   r   r   T)r4   rB   r5   r-   rJ   Z
add_weightrz   r~   r   r   r{   r   r   r   ry   r}   r|   r   r   r   rE   )r   r1   Zchannel_axisZ	input_dimrJ   Zrecurrent_kernel_shaper|   r$   )r   r%   r?     s@    

zConvLSTM2DCell.buildc       )      C   s&  |d }|d }| j ||dd}| j||dd}d| j  k rFdk r|n n2||d  }||d  }	||d  }
||d  }n|}|}	|}
|}d| j  k rdk rn n2||d  }||d  }||d  }||d  }n|}|}|}|}tj| jddd\}}}}tj| jddd\}}}}| jr<t| j	d\}}}}nd	\}}}}| j
|||| jd
}| j
|	||| jd
}| j
|
||| jd
}| j
|||| jd
}| ||} | ||}!| ||}"| ||}#| ||  }$| ||! }%|%| |$| ||"   }&| ||# }'|'| |& }(|(|(|&gfS )Nr   r,   r(   )countg      ?r*   r'   )rF   )NNNN)r+   )Zget_dropout_mask_for_cellZ#get_recurrent_dropout_mask_for_cellr   r   r   splitr   r   ry   r   rK   r+   recurrent_convrx   rw   ))r   rN   r   rP   Zh_tm1Zc_tm1Zdp_maskZrec_dp_maskZinputs_iZinputs_fZinputs_cZinputs_oZh_tm1_iZh_tm1_fZh_tm1_cZh_tm1_oZkernel_iZkernel_fZkernel_cZkernel_oZrecurrent_kernel_iZrecurrent_kernel_fZrecurrent_kernel_cZrecurrent_kernel_oZbias_iZbias_fZbias_cZbias_oZx_iZx_fZx_cZx_oZh_iZh_fZh_cZh_oifcohr$   r$   r%   rR   K  sT    zConvLSTM2DCell.callc             C   s:   t j||| j|| j| jd}|d k	r6t j||| jd}|S )N)r6   r+   r4   r7   )r4   )r   conv2dr6   r4   r7   Zbias_add)r   xwbr+   conv_outr$   r$   r%   rK     s    

zConvLSTM2DCell.input_convc             C   s   t j||dd| jd}|S )N)r,   r,   Zsame)r6   r+   r4   )r   r   r4   )r   r   r   r   r$   r$   r%   r     s    

zConvLSTM2DCell.recurrent_convc                s   | j | j| j| j| j| jt| jt| j	| j
t| jt| jt| j| jt| jt| jt| jt| jt| jt| j| j| jd}tt|  }tt| t|  S )N)r-   r5   r6   r+   r4   r7   rw   rx   ry   rz   r{   r|   r}   r~   r   r   r   r   r   r   r   ) r-   r5   r6   r+   r4   r7   r   	serializerw   rx   ry   r   rz   r{   r|   r}   r   r~   r   r   r   r   r   r   r   r   r   rn   
get_configdictr   items)r   configbase_config)r#   r$   r%   r     s<    




zConvLSTM2DCell.get_config)ro   rp   Nro   rq   rr   Trs   rt   rL   TNNNNNNru   ru   )N)Nrp   )ri   rj   rk   rl   r   r?   rR   rK   r   r   rm   r$   r$   )r#   r%   rn     s2   A                  /
<

rn   zkeras.layers.ConvLSTM2Dc                   sD  e Zd ZdZd? fdd	Zd@ fdd	Zedd Zedd Zedd Z	edd Z
edd Zedd Zedd Zedd  Zed!d" Zed#d$ Zed%d& Zed'd( Zed)d* Zed+d, Zed-d. Zed/d0 Zed1d2 Zed3d4 Zed5d6 Zed7d8 Zed9d: Z fd;d<Zed=d> Z  ZS )A
ConvLSTM2DaN  2D Convolutional LSTM layer.

  A convolutional LSTM is similar to an LSTM, but the input transformations
  and recurrent transformations are both convolutional. This layer is typically
  used to process timeseries of images (i.e. video-like data).

  It is known to perform well for weather data forecasting,
  using inputs that are timeseries of 2D grids of sensor values.
  It isn't usually applied to regular video data, due to its high computational
  cost.

  Args:
    filters: Integer, the dimensionality of the output space
      (i.e. the number of output filters in the convolution).
    kernel_size: An integer or tuple/list of n integers, specifying the
      dimensions of the convolution window.
    strides: An integer or tuple/list of n integers,
      specifying the strides of the convolution.
      Specifying any stride value != 1 is incompatible with specifying
      any `dilation_rate` value != 1.
    padding: One of `"valid"` or `"same"` (case-insensitive).
      `"valid"` means no padding. `"same"` results in padding evenly to
      the left/right or up/down of the input such that output has the same
      height/width dimension as the input.
    data_format: A string,
      one of `channels_last` (default) or `channels_first`.
      The ordering of the dimensions in the inputs.
      `channels_last` corresponds to inputs with shape
      `(batch, time, ..., channels)`
      while `channels_first` corresponds to
      inputs with shape `(batch, time, channels, ...)`.
      It defaults to the `image_data_format` value found in your
      Keras config file at `~/.keras/keras.json`.
      If you never set it, then it will be "channels_last".
    dilation_rate: An integer or tuple/list of n integers, specifying
      the dilation rate to use for dilated convolution.
      Currently, specifying any `dilation_rate` value != 1 is
      incompatible with specifying any `strides` value != 1.
    activation: Activation function to use.
      By default hyperbolic tangent activation function is applied
      (`tanh(x)`).
    recurrent_activation: Activation function to use
      for the recurrent step.
    use_bias: Boolean, whether the layer uses a bias vector.
    kernel_initializer: Initializer for the `kernel` weights matrix,
      used for the linear transformation of the inputs.
    recurrent_initializer: Initializer for the `recurrent_kernel`
      weights matrix,
      used for the linear transformation of the recurrent state.
    bias_initializer: Initializer for the bias vector.
    unit_forget_bias: Boolean.
      If True, add 1 to the bias of the forget gate at initialization.
      Use in combination with `bias_initializer="zeros"`.
      This is recommended in [Jozefowicz et al., 2015](
        http://www.jmlr.org/proceedings/papers/v37/jozefowicz15.pdf)
    kernel_regularizer: Regularizer function applied to
      the `kernel` weights matrix.
    recurrent_regularizer: Regularizer function applied to
      the `recurrent_kernel` weights matrix.
    bias_regularizer: Regularizer function applied to the bias vector.
    activity_regularizer: Regularizer function applied to.
    kernel_constraint: Constraint function applied to
      the `kernel` weights matrix.
    recurrent_constraint: Constraint function applied to
      the `recurrent_kernel` weights matrix.
    bias_constraint: Constraint function applied to the bias vector.
    return_sequences: Boolean. Whether to return the last output
      in the output sequence, or the full sequence. (default False)
    return_state: Boolean Whether to return the last state
      in addition to the output. (default False)
    go_backwards: Boolean (default False).
      If True, process the input sequence backwards.
    stateful: Boolean (default False). If True, the last state
      for each sample at index i in a batch will be used as initial
      state for the sample of index i in the following batch.
    dropout: Float between 0 and 1.
      Fraction of the units to drop for
      the linear transformation of the inputs.
    recurrent_dropout: Float between 0 and 1.
      Fraction of the units to drop for
      the linear transformation of the recurrent state.

  Call arguments:
    inputs: A 5D float tensor (see input shape description below).
    mask: Binary tensor of shape `(samples, timesteps)` indicating whether
      a given timestep should be masked.
    training: Python boolean indicating whether the layer should behave in
      training mode or in inference mode. This argument is passed to the cell
      when calling it. This is only relevant if `dropout` or `recurrent_dropout`
      are set.
    initial_state: List of initial state tensors to be passed to the first
      call of the cell.

  Input shape:
    - If data_format='channels_first'
        5D tensor with shape:
        `(samples, time, channels, rows, cols)`
    - If data_format='channels_last'
        5D tensor with shape:
        `(samples, time, rows, cols, channels)`

  Output shape:
    - If `return_state`: a list of tensors. The first tensor is
      the output. The remaining tensors are the last states,
      each 4D tensor with shape:
      `(samples, filters, new_rows, new_cols)`
      if data_format='channels_first'
      or 4D tensor with shape:
      `(samples, new_rows, new_cols, filters)`
      if data_format='channels_last'.
      `rows` and `cols` values might have changed due to padding.
    - If `return_sequences`: 5D tensor with shape:
      `(samples, timesteps, filters, new_rows, new_cols)`
      if data_format='channels_first'
      or 5D tensor with shape:
      `(samples, timesteps, new_rows, new_cols, filters)`
      if data_format='channels_last'.
    - Else, 4D tensor with shape:
      `(samples, filters, new_rows, new_cols)`
      if data_format='channels_first'
      or 4D tensor with shape:
      `(samples, new_rows, new_cols, filters)`
      if data_format='channels_last'.

  Raises:
    ValueError: in case of invalid constructor arguments.

  References:
    - [Shi et al., 2015](http://arxiv.org/abs/1506.04214v1)
    (the current implementation does not include the feedback loop on the
    cells output).

  Example:

  ```python
  steps = 10
  height = 32
  width = 32
  input_channels = 3
  output_channels = 6

  inputs = tf.keras.Input(shape=(steps, height, width, input_channels))
  layer = tf.keras.layers.ConvLSTM2D(filters=output_channels, kernel_size=3)
  outputs = layer(inputs)
  ```
  r,   r,   rp   Nrq   rr   Trs   rt   rL   F        c                sl   t |||||||||	|
||||||||||||dd}tt| j|f||||d| t|| _d S )NrM   )r-   r5   r6   r+   r4   r7   rw   rx   ry   rz   r{   r|   r}   r~   r   r   r   r   r   r   r   rM   )r   r   r    r!   )rn   rv   r   r   r   r   activity_regularizer)r   r-   r5   r6   r+   r4   r7   rw   rx   ry   rz   r{   r|   r}   r~   r   r   r   r   r   r   r   r   r    r!   r   r   r"   r   )r#   r$   r%   r   M  s:    zConvLSTM2D.__init__c                s   t t| j||||dS )N)rT   rP   rH   )r   r   rR   )r   rN   rT   rP   rH   )r#   r$   r%   rR     s    zConvLSTM2D.callc             C   s   | j jS )N)r   r-   )r   r$   r$   r%   r-     s    zConvLSTM2D.filtersc             C   s   | j jS )N)r   r5   )r   r$   r$   r%   r5     s    zConvLSTM2D.kernel_sizec             C   s   | j jS )N)r   r6   )r   r$   r$   r%   r6     s    zConvLSTM2D.stridesc             C   s   | j jS )N)r   r+   )r   r$   r$   r%   r+     s    zConvLSTM2D.paddingc             C   s   | j jS )N)r   r4   )r   r$   r$   r%   r4     s    zConvLSTM2D.data_formatc             C   s   | j jS )N)r   r7   )r   r$   r$   r%   r7     s    zConvLSTM2D.dilation_ratec             C   s   | j jS )N)r   rw   )r   r$   r$   r%   rw     s    zConvLSTM2D.activationc             C   s   | j jS )N)r   rx   )r   r$   r$   r%   rx     s    zConvLSTM2D.recurrent_activationc             C   s   | j jS )N)r   ry   )r   r$   r$   r%   ry     s    zConvLSTM2D.use_biasc             C   s   | j jS )N)r   rz   )r   r$   r$   r%   rz     s    zConvLSTM2D.kernel_initializerc             C   s   | j jS )N)r   r{   )r   r$   r$   r%   r{     s    z ConvLSTM2D.recurrent_initializerc             C   s   | j jS )N)r   r|   )r   r$   r$   r%   r|     s    zConvLSTM2D.bias_initializerc             C   s   | j jS )N)r   r}   )r   r$   r$   r%   r}     s    zConvLSTM2D.unit_forget_biasc             C   s   | j jS )N)r   r~   )r   r$   r$   r%   r~     s    zConvLSTM2D.kernel_regularizerc             C   s   | j jS )N)r   r   )r   r$   r$   r%   r     s    z ConvLSTM2D.recurrent_regularizerc             C   s   | j jS )N)r   r   )r   r$   r$   r%   r     s    zConvLSTM2D.bias_regularizerc             C   s   | j jS )N)r   r   )r   r$   r$   r%   r     s    zConvLSTM2D.kernel_constraintc             C   s   | j jS )N)r   r   )r   r$   r$   r%   r     s    zConvLSTM2D.recurrent_constraintc             C   s   | j jS )N)r   r   )r   r$   r$   r%   r     s    zConvLSTM2D.bias_constraintc             C   s   | j jS )N)r   r   )r   r$   r$   r%   r     s    zConvLSTM2D.dropoutc             C   s   | j jS )N)r   r   )r   r$   r$   r%   r     s    zConvLSTM2D.recurrent_dropoutc                s   | j | j| j| j| j| jt| jt| j	| j
t| jt| jt| j| jt| jt| jt| jt| jt| jt| jt| j| j| jd}tt|  }|d= tt|  t|   S )N)r-   r5   r6   r+   r4   r7   rw   rx   ry   rz   r{   r|   r}   r~   r   r   r   r   r   r   r   r   r   )!r-   r5   r6   r+   r4   r7   r   r   rw   rx   ry   r   rz   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     sB    




zConvLSTM2D.get_configc             C   s
   | f |S )Nr$   )clsr   r$   r$   r%   from_config  s    zConvLSTM2D.from_config)r   rp   Nr   rq   rr   Trs   rt   rL   TNNNNNNNFFFFr   r   )NNN) ri   rj   rk   rl   r   rR   propertyr-   r5   r6   r+   r4   r7   rw   rx   ry   rz   r{   r|   r}   r~   r   r   r   r   r   r   r   r   classmethodr   rm   r$   r$   )r#   r%   r     sd                            #r   )rl   numpyrb   Ztensorflow.python.kerasr   r   r   r   r   Z)tensorflow.python.keras.engine.base_layerr   Z)tensorflow.python.keras.engine.input_specr   Z(tensorflow.python.keras.layers.recurrentr	   r
   Ztensorflow.python.keras.utilsr   r   r   Ztensorflow.python.opsr   Z tensorflow.python.util.tf_exportr   r   rn   r   r$   r$   r$   r%   <module>   s0        