o
    i e"                     @   s   d 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m  m	Z
 ddlmZ ddlmZ G dd	 d	eZd
d Zdd Zdd ZdS )z+This API defines FeatureColumn abstraction.    )absolute_import)division)print_functionN)Layer)serialization_libc                       sj   e Zd ZdZ	d fdd	Z fddZdd Zd	d
 Zdd Zdd Z	 fddZ
edddZ  ZS )_BaseFeaturesLayerah  Base class for DenseFeatures and SequenceFeatures.

    Defines common methods and helpers.

    Args:
      feature_columns: An iterable containing the FeatureColumns to use as
        inputs to your model.
      expected_column_type: Expected class for provided feature columns.
      trainable:  Boolean, whether the layer's variables will be updated via
        gradient descent during training.
      name: Name to give to the DenseFeatures.
      **kwargs: Keyword arguments to construct a layer.

    Raises:
      ValueError: if an item in `feature_columns` doesn't match
        `expected_column_type`.
    Nc                    sf   t  jd||d| t|| _tjj| | j| _	|| _
| jD ]}t||s0td||q!d S )N)name	trainablezItems of feature_columns must be a {}. You can wrap a categorical column with an embedding_column or indicator_column. Given: {} )super__init___normalize_feature_columns_feature_columnstf__internal__feature_columnStateManagerr	   _state_manager_partitioner
isinstance
ValueErrorformat)selffeature_columnsexpected_column_typer	   r   partitionerkwargscolumn	__class__r
   Z/var/www/myenv/lib/python3.10/site-packages/keras/src/feature_column/base_feature_layer.pyr   4   s    	


z_BaseFeaturesLayer.__init__c              
      s   | j D ]=}tjjj| j| jd( tjjt|j || j	 W d    n1 s,w   Y  W d    n1 s;w   Y  qt
 d  d S )N)r   )r   r   compatv1variable_scoper   r   (_sanitize_column_name_for_variable_scopecreate_stater   r   build)r   _r   r   r
   r    r&   M   s   
z_BaseFeaturesLayer.buildc                 C   s   t d)a  Computes expected output shape of the dense tensor of the layer.

        Args:
          input_shape: Tensor or array with batch shape.
          num_elements: Size of the last dimension of the output.

        Returns:
          Tuple with output shape.
        zCalling an abstract method.)NotImplementedError)r   input_shapenum_elementsr
   r
   r    _output_shapeX   s   
z _BaseFeaturesLayer._output_shapec                 C   s*   d}| j D ]	}||j 7 }q| ||S )Nr   )r   variable_shaper*   _target_shape)r   r)   total_elementsr   r
   r
   r    compute_output_shaped   s   
z'_BaseFeaturesLayer.compute_output_shapec                 C   s*   |j  }| t||}tj||dS )a  Reshapes the dense tensor output of a column based on expected shape.

        Args:
          column: A DenseColumn or SequenceDenseColumn object.
          tensor: A dense tensor obtained from the same column.

        Returns:
          Reshaped dense tensor.
        )shape)r,   r*   r-   r   r0   reshape)r   r   tensorr*   target_shaper
   r
   r    _process_dense_tensorj   s   

z(_BaseFeaturesLayer._process_dense_tensorc                 C   s   t || j t|dS )z>Verifies and concatenates the dense output of several columns.)"_verify_static_batch_size_equalityr   r   concat)r   output_tensorsr
   r
   r    _verify_and_concat_tensorsx   s   z-_BaseFeaturesLayer._verify_and_concat_tensorsc                    sN   dd | j D }d|i}t| j|d< t  }tt| t|  S )Nc                 S   s   g | ]	}t jj|qS r
   )r   r   r   serialize_feature_column).0fcr
   r
   r    
<listcomp>   s    z1_BaseFeaturesLayer.get_config.<locals>.<listcomp>r   r   )	r   r   serialize_keras_objectr   r   
get_configdictlistitems)r   column_configsconfigbase_configr   r
   r    r?      s   
z_BaseFeaturesLayer.get_configc                    sJ   |  }i   fdd|d D |d< t|d |d< | di |S )Nc                    s   g | ]}t jj| qS r
   )r   r   r   deserialize_feature_column)r;   ccolumns_by_namecustom_objectsr
   r    r=      s    z2_BaseFeaturesLayer.from_config.<locals>.<listcomp>r   r   r
   )copyr   deserialize_keras_object)clsrD   rJ   	config_cpr
   rH   r    from_config   s   
z_BaseFeaturesLayer.from_configN)__name__
__module____qualname____doc__r   r&   r+   r/   r4   r9   r?   classmethodrO   __classcell__r
   r
   r   r    r   !   s    r   c                 C   s   t d}|d| S )zASanitizes user-provided feature names for use as variable scopes.z[^A-Za-z0-9_.\-]r'   )recompilesub)r   invalid_charr
   r
   r    r$      s   
r$   c                 C   s   d}t dt| D ]5}tjjtj| | jd }|jdur>|du r)|}|}q	|	|s>t
d|| j|| j||q	dS )zVerify equality between static batch sizes.

    Args:
      tensors: iterable of input tensors.
      columns: Corresponding feature columns.

    Raises:
      ValueError: in case of mismatched batch sizes.
    Nr   zcBatch size (first dimension) of each feature must be same. Batch size of columns ({}, {}): ({}, {}))rangelenr   r!   r"   	Dimensiondimension_valuer0   valueis_compatible_withr   r   r   )tensorscolumnsexpected_batch_sizei
batch_sizebath_size_column_indexr
   r
   r    r6      s*   


r6   c                 C   s   t | tjjjr| g} t | tjjrt| } t | t	rt
d| D ]}t |tjjjs5t
dt||q!| s<t
di }| D ]}|j|v rRt
d|||j |||j< q@t| dd dS )a  Normalizes the `feature_columns` input.

    This method converts the `feature_columns` to list type as best as it can.
    In addition, verifies the type and other parts of feature_columns, required
    by downstream library.

    Args:
      feature_columns: The raw feature columns, usually passed by users.

    Returns:
      The normalized feature column list.

    Raises:
      ValueError: for any invalid inputs, such as empty, duplicated names, etc.
    z4Expected feature_columns to be iterable, found dict.zFItems of feature_columns must be a FeatureColumn. Given (type {}): {}.z"feature_columns must not be empty.zDuplicate feature column name found for columns: {} and {}. This usually means that these columns refer to same base feature. Either one must be discarded or a duplicated but renamed item must be inserted in features dict.c                 S   s   | j S rP   )r   )xr
   r
   r    <lambda>   s    z,_normalize_feature_columns.<locals>.<lambda>)key)r   r   r   r   FeatureColumncollectionsabcIteratorrA   r@   r   r   typer   sorted)r   r   name_to_columnr
   r
   r    r      s4   


r   )rT   
__future__r   r   r   rk   rW   tensorflow.compat.v2r!   v2r   keras.src.engine.base_layerr   keras.src.savingr   r   r$   r6   r   r
   r
   r
   r    <module>   s   | 