o
    i eM                     @   s   d Z ddlm  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 edG dd deejZedG dd deZdS )zFully connected RNN layer.    N)activations)backend)constraints)initializers)regularizers)
base_layer)	InputSpec)	rnn_utils)RNN)DropoutRNNCellMixin)tf_utils)
tf_logging)keras_exportzkeras.layers.SimpleRNNCellc                       sn   e Zd ZdZ													d fd	d
	Zej fddZdddZdddZ	 fddZ
  ZS )SimpleRNNCella  Cell class for SimpleRNN.

    See [the Keras RNN API guide](https://www.tensorflow.org/guide/keras/rnn)
    for details about the usage of RNN API.

    This class processes one step within the whole time sequence input, whereas
    `tf.keras.layer.SimpleRNN` processes the whole sequence.

    Args:
      units: Positive integer, dimensionality of the output space.
      activation: Activation function to use.
        Default: hyperbolic tangent (`tanh`).
        If you pass `None`, no activation is applied
        (ie. "linear" activation: `a(x) = x`).
      use_bias: Boolean, (default `True`), whether the layer uses a bias vector.
      kernel_initializer: Initializer for the `kernel` weights matrix,
        used for the linear transformation of the inputs. Default:
        `glorot_uniform`.
      recurrent_initializer: Initializer for the `recurrent_kernel`
        weights matrix, used for the linear transformation of the recurrent
        state.  Default: `orthogonal`.
      bias_initializer: Initializer for the bias vector. Default: `zeros`.
      kernel_regularizer: Regularizer function applied to the `kernel` weights
        matrix. Default: `None`.
      recurrent_regularizer: Regularizer function applied to the
        `recurrent_kernel` weights matrix. Default: `None`.
      bias_regularizer: Regularizer function applied to the bias vector.
        Default: `None`.
      kernel_constraint: Constraint function applied to the `kernel` weights
        matrix. Default: `None`.
      recurrent_constraint: Constraint function applied to the
        `recurrent_kernel` weights matrix. Default: `None`.
      bias_constraint: Constraint function applied to the bias vector. Default:
        `None`.
      dropout: Float between 0 and 1. Fraction of the units to drop for the
        linear transformation of the inputs. Default: 0.
      recurrent_dropout: Float between 0 and 1. Fraction of the units to drop
        for the linear transformation of the recurrent state. Default: 0.

    Call arguments:
      inputs: A 2D tensor, with shape of `[batch, feature]`.
      states: A 2D tensor with shape of `[batch, units]`, which is the state
        from the previous time step. For timestep 0, the initial state provided
        by user will be feed to cell.
      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.

    Examples:

    ```python
    inputs = np.random.random([32, 10, 8]).astype(np.float32)
    rnn = tf.keras.layers.RNN(tf.keras.layers.SimpleRNNCell(4))

    output = rnn(inputs)  # The output has shape `[32, 4]`.

    rnn = tf.keras.layers.RNN(
        tf.keras.layers.SimpleRNNCell(4),
        return_sequences=True,
        return_state=True)

    # whole_sequence_output has shape `[32, 10, 4]`.
    # final_state has shape `[32, 4]`.
    whole_sequence_output, final_state = rnn(inputs)
    ```
    tanhTglorot_uniform
orthogonalzerosN        c                    s  |dkrt d| dtjj r|dd| _n|dd| _t jd	i | || _	t
|| _|| _t|| _t|| _t|| _t|| _t|| _t|	| _t|
| _t|| _t|| _tdtd|| _tdtd|| _| j	| _| j	| _d S )
Nr   zQReceived an invalid value for argument `units`, expected a positive integer, got .enable_caching_deviceTFg      ?r    ) 
ValueErrortfcompatv1#executing_eagerly_outside_functionspop_enable_caching_devicesuper__init__unitsr   get
activationuse_biasr   kernel_initializerrecurrent_initializerbias_initializerr   kernel_regularizerrecurrent_regularizerbias_regularizerr   kernel_constraintrecurrent_constraintbias_constraintminmaxdropoutrecurrent_dropout
state_sizeoutput_size)selfr!   r#   r$   r%   r&   r'   r(   r)   r*   r+   r,   r-   r0   r1   kwargs	__class__r   N/var/www/myenv/lib/python3.10/site-packages/keras/src/layers/rnn/simple_rnn.pyr    j   s<   zSimpleRNNCell.__init__c                    s   t  | t| }| j|d | jfd| j| j| j|d| _	| j| j| jfd| j
| j| j|d| _| jrG| j| jfd| j| j| j|d| _nd | _d| _d S )Nkernel)shapenameinitializerregularizer
constraintcaching_devicerecurrent_kernelbiasT)r   buildr	   r@   
add_weightr!   r%   r(   r+   r:   r&   r)   r,   rA   r$   r'   r*   r-   rB   built)r4   input_shapedefault_caching_devicer6   r   r8   rC      s:   


	
zSimpleRNNCell.buildc           
      C   s   t j|r
|d n|}| ||}| ||}|d ur&t|| | j}nt|| j}| jd ur9t	|| j}|d urA|| }|t|| j
 }| jd urT| |}t j|r]|gn|}	||	fS )Nr   )r   nest	is_nestedget_dropout_mask_for_cell#get_recurrent_dropout_mask_for_cellr   dotr:   rB   bias_addrA   r#   )
r4   inputsstatestrainingprev_outputdp_maskrec_dp_maskhoutput	new_stater   r   r8   call   s"   


zSimpleRNNCell.callc                 C   s   t | |||S N)r	   #generate_zero_filled_state_for_cell)r4   rN   
batch_sizedtyper   r   r8   get_initial_state   s   zSimpleRNNCell.get_initial_statec                    s   | j t| j| jt| jt| jt| jt	| j
t	| jt	| jt| jt| jt| j| j| jd}|t|  t  }tt| t|  S )N)r!   r#   r$   r%   r&   r'   r(   r)   r*   r+   r,   r-   r0   r1   )r!   r   	serializer#   r$   r   r%   r&   r'   r   r(   r)   r*   r   r+   r,   r-   r0   r1   updater	    config_for_enable_caching_devicer   
get_configdictlistitemsr4   configbase_configr6   r   r8   r`      s8   





zSimpleRNNCell.get_config)r   Tr   r   r   NNNNNNr   r   rX   NNN)__name__
__module____qualname____doc__r    r   shape_type_conversionrC   rW   r\   r`   __classcell__r   r   r6   r8   r   %   s*    F6
 
r   zkeras.layers.SimpleRNNc                       s  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 fd*d+Zed,d- Z  ZS )0	SimpleRNNa6  Fully-connected RNN where the output is to be fed back to input.

    See [the Keras RNN API guide](https://www.tensorflow.org/guide/keras/rnn)
    for details about the usage of RNN API.

    Args:
      units: Positive integer, dimensionality of the output space.
      activation: Activation function to use.
        Default: hyperbolic tangent (`tanh`).
        If you pass None, no activation is applied
        (ie. "linear" activation: `a(x) = x`).
      use_bias: Boolean, (default `True`), whether the layer uses a bias vector.
      kernel_initializer: Initializer for the `kernel` weights matrix,
        used for the linear transformation of the inputs. Default:
        `glorot_uniform`.
      recurrent_initializer: Initializer for the `recurrent_kernel`
        weights matrix, used for the linear transformation of the recurrent
        state.  Default: `orthogonal`.
      bias_initializer: Initializer for the bias vector. Default: `zeros`.
      kernel_regularizer: Regularizer function applied to the `kernel` weights
        matrix. Default: `None`.
      recurrent_regularizer: Regularizer function applied to the
        `recurrent_kernel` weights matrix. Default: `None`.
      bias_regularizer: Regularizer function applied to the bias vector.
        Default: `None`.
      activity_regularizer: Regularizer function applied to the output of the
        layer (its "activation"). Default: `None`.
      kernel_constraint: Constraint function applied to the `kernel` weights
        matrix. Default: `None`.
      recurrent_constraint: Constraint function applied to the
        `recurrent_kernel` weights matrix.  Default: `None`.
      bias_constraint: Constraint function applied to the bias vector. Default:
        `None`.
      dropout: Float between 0 and 1.
        Fraction of the units to drop for the linear transformation of the
        inputs. Default: 0.
      recurrent_dropout: Float between 0 and 1.
        Fraction of the units to drop for the linear transformation of the
        recurrent state. Default: 0.
      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 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.
      unroll: Boolean (default False).
        If True, the network will be unrolled,
        else a symbolic loop will be used.
        Unrolling can speed-up a RNN,
        although it tends to be more memory-intensive.
        Unrolling is only suitable for short sequences.

    Call arguments:
      inputs: A 3D tensor, with shape `[batch, timesteps, feature]`.
      mask: Binary tensor of shape `[batch, timesteps]` indicating whether
        a given timestep should be masked. An individual `True` entry indicates
        that the corresponding timestep should be utilized, while a `False`
        entry indicates that the corresponding timestep should be ignored.
      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` is used.
      initial_state: List of initial state tensors to be passed to the first
        call of the cell.

    Examples:

    ```python
    inputs = np.random.random([32, 10, 8]).astype(np.float32)
    simple_rnn = tf.keras.layers.SimpleRNN(4)

    output = simple_rnn(inputs)  # The output has shape `[32, 4]`.

    simple_rnn = tf.keras.layers.SimpleRNN(
        4, return_sequences=True, return_state=True)

    # whole_sequence_output has shape `[32, 10, 4]`.
    # final_state has shape `[32, 4]`.
    whole_sequence_output, final_state = simple_rnn(inputs)
    ```
    r   Tr   r   r   Nr   Fc                    s   d|v r| d td d|v rd| di}ni }t|fi d|d|d|d|d|d	|d
|d|	d|d|d|d|d|d|dd|dddd|}t j|f|||||d| t|
| _t	ddg| _
d S )NimplementationzhThe `implementation` argument in `SimpleRNN` has been deprecated. Please remove it from your layer call.r   r#   r$   r%   r&   r'   r(   r)   r*   r+   r,   r-   r0   r1   r[   	trainableTr<   simple_rnn_cell)return_sequencesreturn_statego_backwardsstatefulunroll   )ndim)r   loggingwarningr   r"   r   r    r   activity_regularizerr   
input_spec)r4   r!   r#   r$   r%   r&   r'   r(   r)   r*   r{   r+   r,   r-   r0   r1   rr   rs   rt   ru   rv   r5   cell_kwargscellr6   r   r8   r    U  st   

	

	zSimpleRNN.__init__c                    s   t  j||||dS )N)maskrP   initial_state)r   rW   )r4   rN   r   rP   r   r6   r   r8   rW     s   zSimpleRNN.callc                 C      | j jS rX   )r~   r!   r4   r   r   r8   r!        zSimpleRNN.unitsc                 C   r   rX   )r~   r#   r   r   r   r8   r#     r   zSimpleRNN.activationc                 C   r   rX   )r~   r$   r   r   r   r8   r$     r   zSimpleRNN.use_biasc                 C   r   rX   )r~   r%   r   r   r   r8   r%     r   zSimpleRNN.kernel_initializerc                 C   r   rX   )r~   r&   r   r   r   r8   r&     r   zSimpleRNN.recurrent_initializerc                 C   r   rX   )r~   r'   r   r   r   r8   r'     r   zSimpleRNN.bias_initializerc                 C   r   rX   )r~   r(   r   r   r   r8   r(     r   zSimpleRNN.kernel_regularizerc                 C   r   rX   )r~   r)   r   r   r   r8   r)     r   zSimpleRNN.recurrent_regularizerc                 C   r   rX   )r~   r*   r   r   r   r8   r*     r   zSimpleRNN.bias_regularizerc                 C   r   rX   )r~   r+   r   r   r   r8   r+     r   zSimpleRNN.kernel_constraintc                 C   r   rX   )r~   r,   r   r   r   r8   r,     r   zSimpleRNN.recurrent_constraintc                 C   r   rX   )r~   r-   r   r   r   r8   r-     r   zSimpleRNN.bias_constraintc                 C   r   rX   )r~   r0   r   r   r   r8   r0     r   zSimpleRNN.dropoutc                 C   r   rX   )r~   r1   r   r   r   r8   r1     r   zSimpleRNN.recurrent_dropoutc                    s   | j t| j| jt| jt| jt| jt	| j
t	| jt	| jt	| jt| jt| jt| j| j| jd}t  }|t| j |d= tt| t|  S )N)r!   r#   r$   r%   r&   r'   r(   r)   r*   r{   r+   r,   r-   r0   r1   r~   )r!   r   r]   r#   r$   r   r%   r&   r'   r   r(   r)   r*   r{   r   r+   r,   r-   r0   r1   r   r`   r^   r	   r_   r~   ra   rb   rc   rd   r6   r   r8   r`     s@   





zSimpleRNN.get_configc                 C   s    d|v r	| d | di |S )Nro   r   )r   )clsre   r   r   r8   from_config  s   
zSimpleRNN.from_config)r   Tr   r   r   NNNNNNNr   r   FFFFFrg   )rh   ri   rj   rk   r    rW   propertyr!   r#   r$   r%   r&   r'   r(   r)   r*   r+   r,   r-   r0   r1   r`   classmethodr   rm   r   r   r6   r8   rn      sl    YE













#rn   )rk   tensorflow.compat.v2r   v2r   	keras.srcr   r   r   r   r   keras.src.enginer   keras.src.engine.input_specr   keras.src.layers.rnnr	   keras.src.layers.rnn.base_rnnr
   +keras.src.layers.rnn.dropout_rnn_cell_mixinr   keras.src.utilsr   tensorflow.python.platformr   ry    tensorflow.python.util.tf_exportr   BaseRandomLayerr   rn   r   r   r   r8   <module>   s(    X