o
    i e                     @   s   d Z ddlmZ ddlmZ ddlmZ ddlm  mZ ddl	m
Z
 ddlmZ ddlmZ ed	G d
d dejZdddZdS )zThis API defines FeatureColumn for sequential input.

NOTE: This API is a work in progress and will likely be changing frequently.
    )absolute_import)division)print_functionN)backend)base_feature_layer)keras_exportz#keras.experimental.SequenceFeaturesc                       s@   e Zd ZdZd fdd	Zedd Zdd	 Zdd
dZ  Z	S )SequenceFeaturesa  A layer for sequence input.

    All `feature_columns` must be sequence dense columns with the same
    `sequence_length`. The output of this method can be fed into sequence
    networks, such as RNN.

    The output of this method is a 3D `Tensor` of shape `[batch_size, T, D]`.
    `T` is the maximum sequence length for this batch, which could differ from
    batch to batch.

    If multiple `feature_columns` are given with `Di` `num_elements` each, their
    outputs are concatenated. So, the final `Tensor` has shape
    `[batch_size, T, D0 + D1 + ... + Dn]`.

    Example:

    ```python

    import tensorflow as tf

    # Behavior of some cells or feature columns may depend on whether we are in
    # training or inference mode, e.g. applying dropout.
    training = True
    rating = tf.feature_column.sequence_numeric_column('rating')
    watches = tf.feature_column.sequence_categorical_column_with_identity(
        'watches', num_buckets=1000)
    watches_embedding = tf.feature_column.embedding_column(watches,
                                                dimension=10)
    columns = [rating, watches_embedding]

    features = {
     'rating': tf.sparse.from_dense([[1.0,1.1, 0, 0, 0],
                                                 [2.0,2.1,2.2, 2.3, 2.5]]),
     'watches': tf.sparse.from_dense([[2, 85, 0, 0, 0],[33,78, 2, 73, 1]])
    }

    sequence_input_layer = tf.keras.experimental.SequenceFeatures(columns)
    sequence_input, sequence_length = sequence_input_layer(
       features, training=training)
    sequence_length_mask = tf.sequence_mask(sequence_length)
    hidden_size = 32
    rnn_cell = tf.keras.layers.SimpleRNNCell(hidden_size)
    rnn_layer = tf.keras.layers.RNN(rnn_cell)
    outputs, state = rnn_layer(sequence_input, mask=sequence_length_mask)
    ```
    TNc                    s&   t  jd|||tjjjd| dS )a   "Constructs a SequenceFeatures layer.

        Args:
          feature_columns: An iterable of dense sequence columns. Valid columns
            are
            - `embedding_column` that wraps a
              `sequence_categorical_column_with_*`
            - `sequence_numeric_column`.
          trainable: Boolean, whether the layer's variables will be updated via
            gradient descent during training.
          name: Name to give to the SequenceFeatures.
          **kwargs: Keyword arguments to construct a layer.

        Raises:
          ValueError: If any of the `feature_columns` is not a
            `SequenceDenseColumn`.
        )feature_columns	trainablenameexpected_column_typeN )super__init__tf__internal__feature_columnSequenceDenseColumn)selfr	   r
   r   kwargs	__class__r   _/var/www/myenv/lib/python3.10/site-packages/keras/src/feature_column/sequence_feature_column.pyr   R   s   
zSequenceFeatures.__init__c                 C   s   dS )NTr   )r   r   r   r   _is_feature_layerl   s   z"SequenceFeatures._is_feature_layerc                 C   s   |d |d |fS )Nr      r   )r   input_shapetotal_elementsr   r   r   _target_shapep   s   zSequenceFeatures._target_shapec           	   
   C   s   t |ts
td||du rt }tjj|}g }g }| j	D ]F}t
|j6 z|j|| j|d\}}W n tyH   ||| j\}}Y nw || || || W d   n1 saw   Y  q t|| j	 t|}| ||fS )a  Returns sequence input corresponding to the `feature_columns`.

        Args:
          features: A dict mapping keys to tensors.
          training: Python boolean or None, indicating whether to the layer is
            being run in training mode. This argument is passed to the call
            method of any `FeatureColumn` that takes a `training` argument. For
            example, if a `FeatureColumn` performed dropout, the column could
            expose a `training` argument to control whether the dropout should
            be applied. If `None`, becomes `tf.keras.backend.learning_phase()`.
            Defaults to `None`.


        Returns:
          An `(input_layer, sequence_length)` tuple where:
          - input_layer: A float `Tensor` of shape `[batch_size, T, D]`.
              `T` is the maximum sequence length for this batch, which could
              differ from batch to batch. `D` is the sum of `num_elements` for
              all `feature_columns`.
          - sequence_length: An int `Tensor` of shape `[batch_size]`. The
            sequence length for each example.

        Raises:
          ValueError: If features are not a dictionary.
        z/We expected a dictionary here. Instead we got: N)training)
isinstancedict
ValueErrorr   learning_phaser   r   r   FeatureTransformationCache_feature_columns
name_scoper   get_sequence_dense_tensor_state_manager	TypeErrorappend_process_dense_tensorkfc"_verify_static_batch_size_equality_assert_all_equal_and_return_verify_and_concat_tensors)	r   featuresr   transformation_cacheoutput_tensorssequence_lengthscolumndense_tensorsequence_lengthr   r   r   calls   sP   


zSequenceFeatures.call)TNN)
__name__
__module____qualname____doc__r   propertyr   r   r6   __classcell__r   r   r   r   r   !   s    /
r   c              	   C   s   t |pdU t| dkr| d W  d   S g }| dd D ]}|tjj| d | q!t| t	| d W  d   W  d   S 1 sOw   Y  W d   dS 1 s_w   Y  dS )z=Asserts that all tensors are equal and returns the first one.assert_all_equalr   r   N)
r   r%   lenr)   r   compatv1assert_equalcontrol_dependenciesidentity)tensorsr   assert_equal_opstr   r   r   r-      s   "r-   r7   )r;   
__future__r   r   r   tensorflow.compat.v2r@   v2r   	keras.srcr   keras.src.feature_columnr   r+    tensorflow.python.util.tf_exportr   _BaseFeaturesLayerr   r-   r   r   r   r   <module>   s    