
    AVhw                    z   d Z ddlZddlZddl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 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% 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l0m1Z1 ddl0m2Z3 ddl0m4Z4 dd l5m6Z6 dd!l7m8Z8 dd"l7m9Z9 dd#l7m:Z: dd$l;m<Z< dd%l=m>Z> dd&l?m@Z@ dZAd'ZBd(ZCd)ZD G d* d+eE      ZF e>d,g -       G d. d/eF             ZGd0 ZH e@j                  eC       e>d1g -       e8j                  deD      d2                      ZK e@j                  eC       e>d3       e8j                  deD      	 	 	 	 	 	 	 dd4                     ZL e@j                  eC       e>d5g-       e8j                  deD      	 	 	 	 	 	 	 	 dd6                     ZM e@j                  eC       e>d7g -       e8j                  deD      	 	 	 	 	 	 	 	 dd8                     ZN e@j                  eC       e>d9       e8j                  deD      d:dej                  dfd;                     ZP e@j                  eC       e>d<       e8j                  deD      d=                      ZQ e@j                  eC       e>d>       e8j                  deD      ej                  fd?                     ZS e@j                  eC       e>d@g-       e8j                  deD      dddej                  fdA                     ZT e@j                  eC       e>d@g -       e8j                  deD      dej                  dddfdB                     ZU e@j                  eC       e>dC       e8j                  deD      	 	 	 ddD                     ZV e@j                  eC       e>dE       e8j                  deD      ddF                     ZW e@j                  eC       e>dG       e8j                  deD      dH                      ZX e@j                  eC       e>dI       e8j                  deD      ej                  fdJ                     ZY e@j                  eC       e>dK       e8j                  ddL      ddM                     ZZ e>dNg -       G dO dPej                               Z\dQ Z]dR Z^dS Z_ G dT dUej                        Z`dV Za e>dWg -      ej                   G dX dYej                                      Zc e>dZg -       G d[ d\eE             Zddd]Zed^ Zfej                   G d_ d`e\ej                   ej                  d`da                   Ziej                   G db dce\e`ej                  ej                   ej                  dcdd                   Zkej                   G de dfe\ecej                  ej                   ej                  dfdg                   Zmdh Zn G di dje1j                        Zpej                   G dk dle\ecej                  ej                   ej                  dldm                   Zqdn Zrej                   G do dpe`ej                   ej                  dpdq                   Zsej                   G dr dse`ej                   ej                  dsdt                   Ztej                   G du dve`ej                   ej                  dvdw                   Zuej                   G dx dye`ej                   ej                  dydz                   Zvej                   G d{ d|e`ej                   ej                  d|d}                   Zwej                   G d~ de`ej                   ej                  dd                   Zxd Zyd Zzd Z{ej                   G d de\ecej                  ej                   ej                  dd                   Z|d Z}ej                   G d de`ej                   ej                  dd                   Zd Zd Zd Zy)aw  This API defines FeatureColumn abstraction.

FeatureColumns provide a high level abstraction for ingesting and representing
features.

FeatureColumns can also be transformed into a generic input layer for
custom models using `input_layer`.

NOTE: Functions prefixed with "_" indicate experimental or private parts of
the API subject to change, and should not be relied upon!
    N)
lookup_ops)readers)context)feature_column)feature_column_v2_types)serialization)utils)dtypes)ops)sparse_tensor)tensor)tensor_shape)	array_ops)array_ops_stack)	check_ops)cond)embedding_ops)init_ops)math_ops)parsing_ops)
sparse_ops)
string_ops)variable_scope)	variables)gfile)
tf_logging)autotrackable)base)data_structures)checkpoint_utils)deprecation)nest)
tf_inspect)collections_abc)	tf_export)doc_controlsz`The old _FeatureColumn APIs are being deprecated. Please use the new FeatureColumn APIs instead.a      Warning: tf.feature_column is not recommended for new code. Instead,
    feature preprocessing can be done directly using either [Keras preprocessing
    layers](https://www.tensorflow.org/guide/migrate/migrating_feature_columns)
    or through the one-stop utility [`tf.keras.utils.FeatureSpace`](https://www.tensorflow.org/api_docs/python/tf/keras/utils/FeatureSpace)
    built on top of them. See the [migration guide](https://tensorflow.org/guide/migrate)
    for details.
    zUse Keras preprocessing layers instead, either directly or via the `tf.keras.utils.FeatureSpace` utility. Each of `tf.feature_column.*` has a functional equivalent in `tf.keras.layers` for feature preprocessing when training a Keras model.c                   >    e Zd ZdZ	 	 	 	 d	dZd Zd Zd Zd Zd Z	y)
StateManagera  Manages the state associated with FeatureColumns.

  Some `FeatureColumn`s create variables or resources to assist their
  computation. The `StateManager` is responsible for creating and storing these
  objects since `FeatureColumn`s are supposed to be stateless configuration
  only.
  Nc                 &    ~~~~~~~t        d      )  Creates a new variable.

    Args:
      feature_column: A `FeatureColumn` object this variable corresponds to.
      name: variable name.
      shape: variable shape.
      dtype: The type of the variable. Defaults to `self.dtype` or `float32`.
      trainable: Whether this variable is trainable or not.
      use_resource: If true, we use resource variables. Otherwise we use
        RefVariable.
      initializer: initializer instance (callable).

    Returns:
      The created variable.
    zStateManager.create_variableNotImplementedError)selfr   nameshapedtype	trainableuse_resourceinitializers           b/home/dcms/DCMS/lib/python3.12/site-packages/tensorflow/python/feature_column/feature_column_v2.pycreate_variablezStateManager.create_variablee   s    . 	eUI|[
<
==    c                     ~~t        d      )zAdds an existing variable to the state.

    Args:
      feature_column: A `FeatureColumn` object to associate this variable with.
      var: The variable.
    zStateManager.add_variabler+   )r-   r   vars      r4   add_variablezStateManager.add_variable   s     	
9
::r6   c                     ~~t        d      )Returns an existing variable.

    Args:
      feature_column: A `FeatureColumn` object this variable corresponds to.
      name: variable name.
    zStateManager.get_varr+   r-   r   r.   s      r4   get_variablezStateManager.get_variable   s     	
4
55r6   c                     ~~~t        d      )a'  Creates a new resource.

    Resources can be things such as tables, variables, trackables, etc.

    Args:
      feature_column: A `FeatureColumn` object this resource corresponds to.
      name: Name of the resource.
      resource: The resource.

    Returns:
      The created resource.
    zStateManager.add_resourcer+   )r-   r   r.   resources       r4   add_resourcezStateManager.add_resource   s     	h
9
::r6   c                     ~~t        d      )zReturns true iff a resource with same name exists.

    Resources can be things such as tables, variables, trackables, etc.

    Args:
      feature_column: A `FeatureColumn` object this variable corresponds to.
      name: Name of the resource.
    zStateManager.has_resourcer+   r<   s      r4   has_resourcezStateManager.has_resource        	
9
::r6   c                     ~~t        d      )zReturns an already created resource.

    Resources can be things such as tables, variables, trackables, etc.

    Args:
      feature_column: A `FeatureColumn` object this variable corresponds to.
      name: Name of the resource.
    zStateManager.get_resourcer+   r<   s      r4   get_resourcezStateManager.get_resource   rC   r6   NTTN)
__name__
__module____qualname____doc__r5   r9   r=   r@   rB   rE    r6   r4   r(   r(   \   s3     ! $#'"&>4;6; 
;
;r6   r(   z(__internal__.feature_column.StateManager)v1c                   >    e Zd ZdZd Z	 	 	 	 d	dZd Zd Zd Zd Z	y)
_StateManagerImpla!  Manages the state of DenseFeatures and LinearLayer.

  Some `FeatureColumn`s create variables or resources to assist their
  computation. The `StateManager` is responsible for creating and storing these
  objects since `FeatureColumn`s are supposed to be stateless configuration
  only.
  c                    || _         || _        | j                  9t        | j                  d      s#t        j                         | j                  _        t        j                  d       | _        t        j                  d       | _	        y)zCreates an _StateManagerImpl object.

    Args:
      layer: The input layer this state manager is associated with.
      trainable: Whether by default, variables created are trainable or not.
    N
_resourcesc                      i S NrK   rK   r6   r4   <lambda>z,_StateManagerImpl.__init__.<locals>.<lambda>   s    R r6   c                      i S rR   rK   rK   r6   r4   rS   z,_StateManagerImpl.__init__.<locals>.<lambda>   s    " r6   )

_trainable_layerhasattrr   MappingrP   collectionsdefaultdict_cols_to_vars_map_cols_to_resources_map)r-   layerr1   s      r4   __init__z_StateManagerImpl.__init__   sd      DODK{{wt{{L'I.668dkk(44Z@D"-"9"9*"EDr6   Nc           
         || j                   |   v rt        d      t        j                  | j                        5  | j                  j                  ||||| j                  xr ||t        j                        }ddd       t        t        j                        r`|D ]Z  }	|dz   t        |	j                         j                  d         z   }
| j                  j                  |	|j                   dz   |
z          \ nFt        |t        j"                        r,| j                  j                  ||j                   dz   |z          || j                   |   |<   |S # 1 sw Y   xY w)r*   zVariable already exists.)r.   r/   r0   r3   r1   r2   getterN/r   )r[   
ValueError	trackable#no_manual_dependency_tracking_scoperV   
add_weightrU   r   r=   
isinstancer   PartitionedVariablestr_get_save_slice_info
var_offset_track_trackabler.   	Trackable)r-   r   r.   r/   r0   r1   r2   r3   r8   v	part_names              r4   r5   z!_StateManagerImpl.create_variable   sI   . t%%n55122 
	6	6t{{	C .KK""!OO1	#  ,, # 
.c. #y445 O!3JQ%;%;%=%H%H%K!LL	$$Q(;(;c(AI(MNO 
C,,	-$$S.*=*=*Cd*JK36D>*40J+. .s   ?EE c                 ^    || j                   |   v r| j                   |   |   S t        d      )r;   zVariable does not exist.)r[   rb   r<   s      r4   r=   z_StateManagerImpl.get_variable  s9     t%%n55##N3D99
/
00r6   c                    || j                   |   |<   | j                  t        |t        j                        r|j
                  | j                  j                  vr5t        j                         | j                  j                  |j
                  <   || j                  j                  |j
                     vr'|| j                  j                  |j
                     |<   yyyy)a0  Creates a new resource.

    Resources can be things such as tables, variables, trackables, etc.

    Args:
      feature_column: A `FeatureColumn` object this resource corresponds to.
      resource_name: Name of the resource.
      resource: The resource.

    Returns:
      The created resource.
    N)	r\   rV   rf   rc   rl   r.   rP   r   rX   )r-   r   resource_namer?   s       r4   r@   z_StateManagerImpl.add_resource  s     BJD/>{{:h	8K8K#L			DKK$:$:	:6E6M6M6O~223	dkk44^5H5HI	IEM~223MB 
J	 $Mr6   c                 $    || j                   |   v S )a  Returns true iff a resource with same name exists.

    Resources can be things such as tables, variables, trackables, etc.

    Args:
      feature_column: A `FeatureColumn` object this variable corresponds to.
      resource_name: Name of the resource.
    )r\   r-   r   rq   s      r4   rB   z_StateManagerImpl.has_resource)  s     D77GGGr6   c                 z    || j                   vs|| j                   |   vrt        d      | j                   |   |   S )zReturns an already created resource.

    Resources can be things such as tables, variables, trackables, etc.

    Args:
      feature_column: A `FeatureColumn` object this variable corresponds to.
      resource_name: Name of the resource.
    zResource does not exist.)r\   rb   rs   s      r4   rE   z_StateManagerImpl.get_resource4  sG     	d999T88HH122&&~6}EEr6   rF   )
rG   rH   rI   rJ   r^   r5   r=   r@   rB   rE   rK   r6   r4   rN   rN      s8    F$ ! $#'"&1f	1N.	HFr6   rN   c                 f   t        |      }i }t        j                  dd| j                               5  t	        |       }|D ]J  }t        j                  dt        |j                              5  |j                  ||      ||<   ddd       L 	 ddd       |S # 1 sw Y   axY w# 1 sw Y   |S xY w)a  Returns transformed features based on features columns passed in.

  Please note that most probably you would not need to use this function. Please
  check `input_layer` and `linear_model` to see whether they will
  satisfy your use case or not.

  Example:

  ```python
  # Define features and transformations
  crosses_a_x_b = crossed_column(
      columns=["sparse_feature_a", "sparse_feature_b"], hash_bucket_size=10000)
  price_buckets = bucketized_column(
      source_column=numeric_column("price"), boundaries=[...])

  columns = [crosses_a_x_b, price_buckets]
  features = tf.io.parse_example(..., features=make_parse_example_spec(columns))
  transformed = transform_features(features=features, feature_columns=columns)

  assertCountEqual(columns, transformed.keys())
  ```

  Args:
    features: A mapping from key to tensors. `FeatureColumn`s look up via these
      keys. For example `numeric_column('price')` will look at 'price' key in
      this dict. Values can be a `SparseTensor` or a `Tensor` depends on
      corresponding `FeatureColumn`.
    feature_columns: An iterable containing all the `FeatureColumn`s.
    state_manager: A StateManager object that holds the FeatureColumn state.

  Returns:
    A `dict` mapping `FeatureColumn` to `Tensor` and `SparseTensor` values.
  Ntransform_features)default_namevaluesrw   )_normalize_feature_columnsr   
name_scoperx   FeatureTransformationCache(_sanitize_column_name_for_variable_scoper.   get)featuresfeature_columnsstate_manageroutputstransformation_cachecolumns         r4   _transform_features_v2r   C  s    D /?/'
~~
-hoo6GI J5h?! J>>
?LN J /226=IJ JJJ 
.	J J	J 
.s#   ;B&/B
B&B#B&&B0z&feature_column.make_parse_example_specc           
      L   i }| D ]  }t        |t        j                        st        dj	                  |            |j
                  }t        j                  |      D ]1  \  }}||v s|||   k7  st        dj	                  ||||                |j                  |        |S )a  Creates parsing spec dictionary from input feature_columns.

  The returned dictionary can be used as arg 'features' in
  `tf.io.parse_example`.

  Typical usage example:

  ```python
  # Define features and transformations
  feature_a = tf.feature_column.categorical_column_with_vocabulary_file(...)
  feature_b = tf.feature_column.numeric_column(...)
  feature_c_bucketized = tf.feature_column.bucketized_column(
      tf.feature_column.numeric_column("feature_c"), ...)
  feature_a_x_feature_c = tf.feature_column.crossed_column(
      columns=["feature_a", feature_c_bucketized], ...)

  feature_columns = set(
      [feature_b, feature_c_bucketized, feature_a_x_feature_c])
  features = tf.io.parse_example(
      serialized=serialized_examples,
      features=tf.feature_column.make_parse_example_spec(feature_columns))
  ```

  For the above example, make_parse_example_spec would return the dict:

  ```python
  {
      "feature_a": parsing_ops.VarLenFeature(tf.string),
      "feature_b": parsing_ops.FixedLenFeature([1], dtype=tf.float32),
      "feature_c": parsing_ops.FixedLenFeature([1], dtype=tf.float32)
  }
  ```

  Args:
    feature_columns: An iterable containing all feature columns. All items
      should be instances of classes derived from `FeatureColumn`.

  Returns:
    A dict mapping each feature key to a `FixedLenFeature` or `VarLenFeature`
    value.

  Raises:
    ValueError: If any of the given `feature_columns` is not a `FeatureColumn`
      instance.
  z>All feature_columns must be FeatureColumn instances. Given: {}zHfeature_columns contain different parse_spec for key {}. Given {} and {})	rf   fc_typesFeatureColumnrb   formatparse_example_specsix	iteritemsupdate)r   resultr   configkeyvalues         r4   make_parse_example_spec_v2r   r  s    f & 	ffh445 ##)6&>3 3&&FmmF+ P
U	5F3K/ //5vc5&+/NP 	PP MM&	 
-r6   zfeature_column.embedding_columnc	                 T   ||dk  rt        dj                  |            |du |du k7  rt        d      |/t        |      s$t        dj                  | j                              |-t	        j
                  ddt        j                  |      z        }t        | ||||||||	      S )	a	  `DenseColumn` that converts from sparse, categorical input.

  Use this when your inputs are sparse, but you want to convert them to a dense
  representation (e.g., to feed to a DNN).

  Args:
    categorical_column: A `CategoricalColumn` created by a
      `categorical_column_with_*` function. This column produces the sparse IDs
      that are inputs to the embedding lookup.
    dimension: An integer specifying dimension of the embedding, must be > 0.
    combiner: A string specifying how to reduce if there are multiple entries in
      a single row. Currently 'mean', 'sqrtn' and 'sum' are supported, with
      'mean' the default. 'sqrtn' often achieves good accuracy, in particular
      with bag-of-words columns. Each of this can be thought as example level
      normalizations on the column. For more information, see
      `tf.embedding_lookup_sparse`.
    initializer: A variable initializer function to be used in embedding
      variable initialization. If not specified, defaults to
      `truncated_normal_initializer` with mean `0.0` and standard deviation
      `1/sqrt(dimension)`.
    ckpt_to_load_from: String representing checkpoint name/pattern from which to
      restore column weights. Required if `tensor_name_in_ckpt` is not `None`.
    tensor_name_in_ckpt: Name of the `Tensor` in `ckpt_to_load_from` from which
      to restore the column weights. Required if `ckpt_to_load_from` is not
      `None`.
    max_norm: If not `None`, embedding values are l2-normalized to this value.
    trainable: Whether or not the embedding is trainable. Default is True.
    use_safe_embedding_lookup: If true, uses safe_embedding_lookup_sparse
      instead of embedding_lookup_sparse. safe_embedding_lookup_sparse ensures
      there are no empty rows and all weights and ids are positive at the
      expense of extra compute cost. This only applies to rank 2 (NxM) shaped
      input tensors. Defaults to true, consider turning off if the above checks
      are not needed. Note that having empty rows will not trigger any error
      though the output result might be 0 or omitted.

  Returns:
    `DenseColumn` that converts from sparse input.

  Raises:
    ValueError: if `dimension` not > 0.
    ValueError: if exactly one of `ckpt_to_load_from` and `tensor_name_in_ckpt`
      is specified.
    ValueError: if `initializer` is specified and is not callable.
    RuntimeError: If eager execution is enabled.
  N   Invalid dimension {}.PMust specify both `ckpt_to_load_from` and `tensor_name_in_ckpt` or none of them.zGinitializer must be callable if specified. Embedding of column_name: {}        meanstddev	categorical_column	dimensioncombinerr3   ckpt_to_load_fromtensor_name_in_ckptmax_normr1   use_safe_embedding_lookup)	rb   r   callabler.   r   truncated_normal_initializermathsqrtEmbeddingColumnr   s	            r4   embedding_columnr     s    r Y]
,33I>
??4%8D%@A
 > ? ? (=
 44:F+00523 3 77TYYy113K 
+)- 9	
; 	;r6   z'feature_column.shared_embedding_columnsc
                 ~   t        j                         rt        d      ||dk  rt        dj	                  |            |du |du k7  rt        d      |t        |      st        d      |-t        j                  ddt        j                  |      z  	      }t        | d
       }
|
d   }|j                  }t        |t        j                        s$t        dj	                  |t        |                  t        |t        j                   t"        t        j$                  t&        f      rA|j(                  }t        |t        j                   t"        t        j$                  t&        f      rA|
dd D ]  }t        |t        j                   t"        t        j$                  t&        f      rA|j(                  }t        |t        j                   t"        t        j$                  t&        f      rAt        |t        |            s/t        dj	                  |t        |      |t        |                  ||j                  k7  st        dj	                  ||||j                               |sdj+                  d |
D              }|dz  }g }| D ]0  }|j-                  t        j.                  ||||||||||	
             2 |S )a  List of dense columns that convert from sparse, categorical input.

  This is similar to `embedding_column`, except that it produces a list of
  embedding columns that share the same embedding weights.

  Use this when your inputs are sparse and of the same type (e.g. watched and
  impression video IDs that share the same vocabulary), and you want to convert
  them to a dense representation (e.g., to feed to a DNN).

  Inputs must be a list of categorical columns created by any of the
  `categorical_column_*` function. They must all be of the same type and have
  the same arguments except `key`. E.g. they can be
  categorical_column_with_vocabulary_file with the same vocabulary_file. Some or
  all columns could also be weighted_categorical_column.

  Args:
    categorical_columns: List of categorical columns created by a
      `categorical_column_with_*` function. These columns produce the sparse IDs
      that are inputs to the embedding lookup. All columns must be of the same
      type and have the same arguments except `key`. E.g. they can be
      categorical_column_with_vocabulary_file with the same vocabulary_file.
      Some or all columns could also be weighted_categorical_column.
    dimension: An integer specifying dimension of the embedding, must be > 0.
    combiner: A string specifying how to reduce if there are multiple entries in
      a single row. Currently 'mean', 'sqrtn' and 'sum' are supported, with
      'mean' the default. 'sqrtn' often achieves good accuracy, in particular
      with bag-of-words columns. Each of this can be thought as example level
      normalizations on the column. For more information, see
      `tf.embedding_lookup_sparse`.
    initializer: A variable initializer function to be used in embedding
      variable initialization. If not specified, defaults to
      `truncated_normal_initializer` with mean `0.0` and standard deviation
      `1/sqrt(dimension)`.
    shared_embedding_collection_name: Optional name of the collection where
      shared embedding weights are added. If not given, a reasonable name will
      be chosen based on the names of `categorical_columns`. This is also used
      in `variable_scope` when creating shared embedding weights.
    ckpt_to_load_from: String representing checkpoint name/pattern from which to
      restore column weights. Required if `tensor_name_in_ckpt` is not `None`.
    tensor_name_in_ckpt: Name of the `Tensor` in `ckpt_to_load_from` from which
      to restore the column weights. Required if `ckpt_to_load_from` is not
      `None`.
    max_norm: If not `None`, each embedding is clipped if its l2-norm is larger
      than this value, before combining.
    trainable: Whether or not the embedding is trainable. Default is True.
    use_safe_embedding_lookup: If true, uses safe_embedding_lookup_sparse
      instead of embedding_lookup_sparse. safe_embedding_lookup_sparse ensures
      there are no empty rows and all weights and ids are positive at the
      expense of extra compute cost. This only applies to rank 2 (NxM) shaped
      input tensors. Defaults to true, consider turning off if the above checks
      are not needed. Note that having empty rows will not trigger any error
      though the output result might be 0 or omitted.

  Returns:
    A list of dense columns that converts from sparse input. The order of
    results follows the ordering of `categorical_columns`.

  Raises:
    ValueError: if `dimension` not > 0.
    ValueError: if any of the given `categorical_columns` is of different type
      or has different arguments than the others.
    ValueError: if exactly one of `ckpt_to_load_from` and `tensor_name_in_ckpt`
      is specified.
    ValueError: if `initializer` is specified and is not callable.
    RuntimeError: if eager execution is enabled.
  Kshared_embedding_columns are not supported when eager execution is enabled.Nr   r   r   *initializer must be callable if specified.r         ?r   c                     | j                   S rR   r.   xs    r4   rS   z*shared_embedding_columns.<locals>.<lambda>g  
    QVV r6   r   r   zXAll categorical_columns must be subclasses of _CategoricalColumn. Given: {}, of type: {}To use shared_embedding_column, all categorical_columns must have the same type, or be weighted_categorical_column or sequence column of the same type. Given column: {} of type: {} does not match given column: {} of type: {}zTo use shared_embedding_column, all categorical_columns must have the same number of buckets. ven column: {} with buckets: {} does  not match column: {} with buckets: {}_c              3   4   K   | ]  }|j                     y wrR   r   .0cs     r4   	<genexpr>z+shared_embedding_columns.<locals>.<genexpr>       /O1/O   _shared_embedding)
r   r3   r   r    shared_embedding_collection_namer   r   r   r1   r   )r   executing_eagerlyRuntimeErrorrb   r   r   r   r   r   r   sorted_num_bucketsrf   fc_old_CategoricalColumntype_WeightedCategoricalColumnWeightedCategoricalColumn_SequenceCategoricalColumnSequenceCategoricalColumnr   joinappend_SharedEmbeddingColumn)categorical_columnsr   r   r3   r   r   r   r   r1   r   sorted_columnsc0num_bucketsr   r   r   s                   r4   shared_embedding_columnsr     s   ^  
 / 0 0 Y]
,33I>
??4%8D%@A
 > ? ? (=
A
BB77dii	224K
 -3CD.a"+	B11	2
	!!'DH!57 7 	

+
+
#

+
+
#	%	& 
		B 	

+
+
#

+
+
#	%	& !" 3a
	--%--%		'( 

a 	--%--%		'( ab"# $*6"d2h47#C	E E
 ann$228&+q!..323 3!3, 
*'*xx/O/O'O$$(;;$&# Bf
MM%%%#-M/ 3&?
	ABB 
-r6   z feature_column.shared_embeddingsc
                 v   t        j                         rt        d      ||dk  rt        dj	                  |            |du |du k7  rt        d      |t        |      st        d      |-t        j                  ddt        j                  |      z  	      }t        | d
       }
|
d   }|j                  }t        |t              s$t        dj	                  |t        |                  t        |t        t         f      r#|j"                  }t        |t        t         f      r#|
dd D ]  }t        |t        t         f      r#|j"                  }t        |t        t         f      r#t        |t        |            s/t        dj	                  |t        |      |t        |                  ||j                  k7  st        dj	                  ||||j                               |sdj%                  d |
D              }|dz  }t'        ||||||||	      }g }| D ]  }|j)                   ||||              |S )ay  List of dense columns that convert from sparse, categorical input.

  This is similar to `embedding_column`, except that it produces a list of
  embedding columns that share the same embedding weights.

  Use this when your inputs are sparse and of the same type (e.g. watched and
  impression video IDs that share the same vocabulary), and you want to convert
  them to a dense representation (e.g., to feed to a DNN).

  Inputs must be a list of categorical columns created by any of the
  `categorical_column_*` function. They must all be of the same type and have
  the same arguments except `key`. E.g. they can be
  categorical_column_with_vocabulary_file with the same vocabulary_file. Some or
  all columns could also be weighted_categorical_column.

  Args:
    categorical_columns: List of categorical columns created by a
      `categorical_column_with_*` function. These columns produce the sparse IDs
      that are inputs to the embedding lookup. All columns must be of the same
      type and have the same arguments except `key`. E.g. they can be
      categorical_column_with_vocabulary_file with the same vocabulary_file.
      Some or all columns could also be weighted_categorical_column.
    dimension: An integer specifying dimension of the embedding, must be > 0.
    combiner: A string specifying how to reduce if there are multiple entries in
      a single row. Currently 'mean', 'sqrtn' and 'sum' are supported, with
      'mean' the default. 'sqrtn' often achieves good accuracy, in particular
      with bag-of-words columns. Each of this can be thought as example level
      normalizations on the column. For more information, see
      `tf.embedding_lookup_sparse`.
    initializer: A variable initializer function to be used in embedding
      variable initialization. If not specified, defaults to
      `truncated_normal_initializer` with mean `0.0` and standard deviation
      `1/sqrt(dimension)`.
    shared_embedding_collection_name: Optional collective name of these columns.
      If not given, a reasonable name will be chosen based on the names of
      `categorical_columns`.
    ckpt_to_load_from: String representing checkpoint name/pattern from which to
      restore column weights. Required if `tensor_name_in_ckpt` is not `None`.
    tensor_name_in_ckpt: Name of the `Tensor` in `ckpt_to_load_from` from which
      to restore the column weights. Required if `ckpt_to_load_from` is not
      `None`.
    max_norm: If not `None`, each embedding is clipped if its l2-norm is larger
      than this value, before combining.
    trainable: Whether or not the embedding is trainable. Default is True.
    use_safe_embedding_lookup: If true, uses safe_embedding_lookup_sparse
      instead of embedding_lookup_sparse. safe_embedding_lookup_sparse ensures
      there are no empty rows and all weights and ids are positive at the
      expense of extra compute cost. This only applies to rank 2 (NxM) shaped
      input tensors. Defaults to true, consider turning off if the above checks
      are not needed. Note that having empty rows will not trigger any error
      though the output result might be 0 or omitted.

  Returns:
    A list of dense columns that converts from sparse input. The order of
    results follows the ordering of `categorical_columns`.

  Raises:
    ValueError: if `dimension` not > 0.
    ValueError: if any of the given `categorical_columns` is of different type
      or has different arguments than the others.
    ValueError: if exactly one of `ckpt_to_load_from` and `tensor_name_in_ckpt`
      is specified.
    ValueError: if `initializer` is specified and is not callable.
    RuntimeError: if eager execution is enabled.
  r   Nr   r   r   r   r   r   r   c                     | j                   S rR   r   r   s    r4   rS   z-shared_embedding_columns_v2.<locals>.<lambda>  r   r6   r   r   zWAll categorical_columns must be subclasses of CategoricalColumn. Given: {}, of type: {}r   zTo use shared_embedding_column, all categorical_columns must have the same number of buckets. Given column: {} with buckets: {} does  not match column: {} with buckets: {}r   c              3   4   K   | ]  }|j                     y wrR   r   r   s     r4   r   z.shared_embedding_columns_v2.<locals>.<genexpr>   r   r   r   )r   r   r   )r   r   r   rb   r   r   r   r   r   r   r   r   rf   CategoricalColumnr   r   r   r   r   SharedEmbeddingColumnCreatorr   )r   r   r   r3   r   r   r   r   r1   r   r   r   r   r   column_creatorr   r   s                    r4   shared_embedding_columns_v2r     sl   `  
 / 0 0 Y]
,33I>
??4%8D%@A
 > ? ? (=
A
BB77dii	224K
 -3CD.a"+	B)	*
	!!'DH!57 7 	213LMN			B 	213LMN!" 2a
Q24MN
O


a Q24MN
Oab"# $*6"d2h47#C	E E
 amm#228&+q!--312 22  
*'*xx/O/O'O$$(;;$//1D9>!.
 &# Nf
MM%8	MNN
 
-r6   zfeature_column.numeric_column)r   c                 H   t        ||       }|j                  s'|j                  st        dj	                  ||             t        j                  ||||       }|%t        |      st        dj	                  |            t        j                  |        t        | ||||      S )a  Represents real valued or numerical features.

  Example:

  Assume we have data with two features `a` and `b`.

  >>> data = {'a': [15, 9, 17, 19, 21, 18, 25, 30],
  ...    'b': [5.0, 6.4, 10.5, 13.6, 15.7, 19.9, 20.3 , 0.0]}

  Let us represent the features `a` and `b` as numerical features.

  >>> a = tf.feature_column.numeric_column('a')
  >>> b = tf.feature_column.numeric_column('b')

  Feature column describe a set of transformations to the inputs.

  For example, to "bucketize" feature `a`, wrap the `a` column in a
  `feature_column.bucketized_column`.
  Providing `5` bucket boundaries, the bucketized_column api
  will bucket this feature in total of `6` buckets.

  >>> a_buckets = tf.feature_column.bucketized_column(a,
  ...    boundaries=[10, 15, 20, 25, 30])

  Create a `DenseFeatures` layer which will apply the transformations
  described by the set of `tf.feature_column` objects:

  >>> feature_layer = tf.keras.layers.DenseFeatures([a_buckets, b])
  >>> print(feature_layer(data))
  tf.Tensor(
  [[ 0.   0.   1.   0.   0.   0.   5. ]
   [ 1.   0.   0.   0.   0.   0.   6.4]
   [ 0.   0.   1.   0.   0.   0.  10.5]
   [ 0.   0.   1.   0.   0.   0.  13.6]
   [ 0.   0.   0.   1.   0.   0.  15.7]
   [ 0.   0.   1.   0.   0.   0.  19.9]
   [ 0.   0.   0.   0.   1.   0.  20.3]
   [ 0.   0.   0.   0.   0.   1.   0. ]], shape=(8, 7), dtype=float32)

  Args:
    key: A unique string identifying the input feature. It is used as the column
      name and the dictionary key for feature parsing configs, feature `Tensor`
      objects, and feature columns.
    shape: An iterable of integers specifies the shape of the `Tensor`. An
      integer can be given which means a single dimension `Tensor` with given
      width. The `Tensor` representing the column will have the shape of
      [batch_size] + `shape`.
    default_value: A single value compatible with `dtype` or an iterable of
      values compatible with `dtype` which the column takes on during
      `tf.Example` parsing if data is missing. A default value of `None` will
      cause `tf.io.parse_example` to fail if an example does not contain this
      column. If a single value is provided, the same value will be applied as
      the default value for every item. If an iterable of values is provided,
      the shape of the `default_value` should be equal to the given `shape`.
    dtype: defines the type of values. Default value is `tf.float32`. Must be a
      non-quantized, real integer or floating point type.
    normalizer_fn: If not `None`, a function that can be used to normalize the
      value of the tensor after `default_value` is applied for parsing.
      Normalizer function takes the input `Tensor` as its argument, and returns
      the output `Tensor`. (e.g. lambda x: (x - 3.0) / 4.2). Please note that
      even though the most common use case of this function is normalization, it
      can be used for any kind of Tensorflow transformations.

  Returns:
    A `NumericColumn`.

  Raises:
    TypeError: if any dimension in shape is not an int
    ValueError: if any dimension in shape is not a positive integer
    TypeError: if `default_value` is an iterable but not compatible with `shape`
    TypeError: if `default_value` is not compatible with `dtype`.
    ValueError: if `dtype` is not convertible to `tf.float32`.
  z6dtype must be convertible to float. dtype: {}, key: {}z+normalizer_fn must be a callable. Given: {})r/   default_valuer0   normalizer_fn)_check_shape
is_integeris_floatingrb   r   fc_utilscheck_default_valuer   	TypeErrorassert_key_is_stringNumericColumnr   r/   r   r0   r   s        r4   numeric_columnr   1  s    b uc
"%


e//
 **0&*<> >..umUCP-x'>
5<<]KM M $		!!
# #r6   z feature_column.bucketized_columnc                    t        | t        t        j                  f      st	        dj                  |             t        | j                        dkD  rt	        dj                  |             |st	        d      t        |t              st        |t              st	        d      t        t        |      dz
        D ]  }||   ||dz      k\  st	        d       t        | t        |            S )a  Represents discretized dense input bucketed by `boundaries`.

  Buckets include the left boundary, and exclude the right boundary. Namely,
  `boundaries=[0., 1., 2.]` generates buckets `(-inf, 0.)`, `[0., 1.)`,
  `[1., 2.)`, and `[2., +inf)`.

  For example, if the inputs are

  ```python
  boundaries = [0, 10, 100]
  input tensor = [[-5, 10000]
                  [150,   10]
                  [5,    100]]
  ```

  then the output will be

  ```python
  output = [[0, 3]
            [3, 2]
            [1, 3]]
  ```

  Example:

  ```python
  price = tf.feature_column.numeric_column('price')
  bucketized_price = tf.feature_column.bucketized_column(
      price, boundaries=[...])
  columns = [bucketized_price, ...]
  features = tf.io.parse_example(
      ..., features=tf.feature_column.make_parse_example_spec(columns))
  dense_tensor = tf.keras.layers.DenseFeatures(columns)(features)
  ```

  A `bucketized_column` can also be crossed with another categorical column
  using `crossed_column`:

  ```python
  price = tf.feature_column.numeric_column('price')
  # bucketized_column converts numerical feature to a categorical one.
  bucketized_price = tf.feature_column.bucketized_column(
      price, boundaries=[...])
  # 'keywords' is a string feature.
  price_x_keywords = tf.feature_column.crossed_column(
      [bucketized_price, 'keywords'], 50K)
  columns = [price_x_keywords, ...]
  features = tf.io.parse_example(
      ..., features=tf.feature_column.make_parse_example_spec(columns))
  dense_tensor = tf.keras.layers.DenseFeatures(columns)(features)
  linear_model = tf.keras.experimental.LinearModel(units=...)(dense_tensor)
  ```

  Args:
    source_column: A one-dimensional dense column which is generated with
      `numeric_column`.
    boundaries: A sorted list or tuple of floats specifying the boundaries.

  Returns:
    A `BucketizedColumn`.

  Raises:
    ValueError: If `source_column` is not a numeric column, or if it is not
      one-dimensional.
    ValueError: If `boundaries` is not a sorted list or tuple.
  zIsource_column must be a column generated with numeric_column(). Given: {}r   z7source_column must be one-dimensional column. Given: {}zboundaries must not be empty.z!boundaries must be a sorted list.)rf   r   r   _NumericColumnrb   r   lenr/   listtuplerangeBucketizedColumn)source_column
boundariesis      r4   bucketized_columnr     s    L 
MM63H3H#I	J
	F=)+ + 			!
 !!'!68 8	
4
55
Z
&*Z*G
8
99Z1$% <a!}
1q5)):;;< 
-z):	;;r6   z2feature_column.categorical_column_with_hash_bucketc                 
   |t        dj                  |             |dk  rt        dj                  ||             t        j                  |        t        j                  |dj                  |              t        | ||      S )a.  Represents sparse feature where ids are set by hashing.

  Use this when your sparse features are in string or integer format, and you
  want to distribute your inputs into a finite number of buckets by hashing.
  output_id = Hash(input_feature_string) % bucket_size for string type input.
  For int type input, the value is converted to its string representation first
  and then hashed by the same formula.

  For input dictionary `features`, `features[key]` is either `Tensor` or
  `SparseTensor`. If `Tensor`, missing values can be represented by `-1` for int
  and `''` for string, which will be dropped by this feature column.

  Example:

  ```python
  import tensorflow as tf
  keywords = tf.feature_column.categorical_column_with_hash_bucket("keywords",
  10000)
  columns = [keywords]
  features = {'keywords': tf.constant([['Tensorflow', 'Keras', 'RNN', 'LSTM',
  'CNN'], ['LSTM', 'CNN', 'Tensorflow', 'Keras', 'RNN'], ['CNN', 'Tensorflow',
  'LSTM', 'Keras', 'RNN']])}
  linear_prediction, _, _ = tf.compat.v1.feature_column.linear_model(features,
  columns)

  # or
  import tensorflow as tf
  keywords = tf.feature_column.categorical_column_with_hash_bucket("keywords",
  10000)
  keywords_embedded = tf.feature_column.embedding_column(keywords, 16)
  columns = [keywords_embedded]
  features = {'keywords': tf.constant([['Tensorflow', 'Keras', 'RNN', 'LSTM',
  'CNN'], ['LSTM', 'CNN', 'Tensorflow', 'Keras', 'RNN'], ['CNN', 'Tensorflow',
  'LSTM', 'Keras', 'RNN']])}
  input_layer = tf.keras.layers.DenseFeatures(columns)
  dense_tensor = input_layer(features)
  ```

  Args:
    key: A unique string identifying the input feature. It is used as the column
      name and the dictionary key for feature parsing configs, feature `Tensor`
      objects, and feature columns.
    hash_bucket_size: An int > 1. The number of buckets.
    dtype: The type of features. Only string and integer types are supported.

  Returns:
    A `HashedCategoricalColumn`.

  Raises:
    ValueError: `hash_bucket_size` is not greater than 1.
    ValueError: `dtype` is neither string nor integer.
  z%hash_bucket_size must be set. key: {}r   zBhash_bucket_size must be at least 1. hash_bucket_size: {}, key: {}column_name: {}prefix)rb   r   r   r   assert_string_or_intHashedCategoricalColumnr   hash_bucket_sizer0   s      r4   #categorical_column_with_hash_bucketr     s    t 
?FFsK
LL
 55;V)3601 1 $
.?.F.Fs.KL	 &6	>>r6   z6feature_column.categorical_column_with_vocabulary_filec                 "    t        | |||||      S )a4  A `CategoricalColumn` with a vocabulary file.

  Use this when your inputs are in string or integer format, and you have a
  vocabulary file that maps each value to an integer ID. By default,
  out-of-vocabulary values are ignored. Use either (but not both) of
  `num_oov_buckets` and `default_value` to specify how to include
  out-of-vocabulary values.

  For input dictionary `features`, `features[key]` is either `Tensor` or
  `SparseTensor`. If `Tensor`, missing values can be represented by `-1` for int
  and `''` for string, which will be dropped by this feature column.

  Example with `num_oov_buckets`:
  File '/us/states.txt' contains 50 lines, each with a 2-character U.S. state
  abbreviation. All inputs with values in that file are assigned an ID 0-49,
  corresponding to its line number. All other values are hashed and assigned an
  ID 50-54.

  ```python
  import tensorflow as tf
  states = tf.feature_column.categorical_column_with_vocabulary_file(
    key='states', vocabulary_file='states.txt', vocabulary_size=5,
    num_oov_buckets=1)
  columns = [states]
  features = {'states':tf.constant([['california', 'georgia', 'michigan',
  'texas', 'new york'], ['new york', 'georgia', 'california', 'michigan',
  'texas']])}
  linear_prediction = tf.compat.v1.feature_column.linear_model(features,
  columns)
  ```

  Example with `default_value`:
  File '/us/states.txt' contains 51 lines - the first line is 'XX', and the
  other 50 each have a 2-character U.S. state abbreviation. Both a literal 'XX'
  in input, and other values missing from the file, will be assigned ID 0. All
  others are assigned the corresponding line number 1-50.

  ```python
  import tensorflow as tf
  states = tf.feature_column.categorical_column_with_vocabulary_file(
    key='states', vocabulary_file='states.txt', vocabulary_size=6,
    default_value=0)
  columns = [states]
  features = {'states':tf.constant([['california', 'georgia', 'michigan',
  'texas', 'new york'], ['new york', 'georgia', 'california', 'michigan',
  'texas']])}
  linear_prediction = tf.compat.v1.feature_column.linear_model(features,
  columns)
  ```

  And to make an embedding with either:

  ```python
  import tensorflow as tf
  states = tf.feature_column.categorical_column_with_vocabulary_file(
    key='states', vocabulary_file='states.txt', vocabulary_size=5,
    num_oov_buckets=1)
  columns = [tf.feature_column.embedding_column(states, 3)]
  features = {'states':tf.constant([['california', 'georgia', 'michigan',
  'texas', 'new york'], ['new york', 'georgia', 'california', 'michigan',
  'texas']])}
  input_layer = tf.keras.layers.DenseFeatures(columns)
  dense_tensor = input_layer(features)
  ```

  Args:
    key: A unique string identifying the input feature. It is used as the column
      name and the dictionary key for feature parsing configs, feature `Tensor`
      objects, and feature columns.
    vocabulary_file: The vocabulary file name.
    vocabulary_size: Number of the elements in the vocabulary. This must be no
      greater than length of `vocabulary_file`, if less than length, later
      values are ignored. If None, it is set to the length of `vocabulary_file`.
    num_oov_buckets: Non-negative integer, the number of out-of-vocabulary
      buckets. All out-of-vocabulary inputs will be assigned IDs in the range
      `[vocabulary_size, vocabulary_size+num_oov_buckets)` based on a hash of
      the input value. A positive `num_oov_buckets` can not be specified with
      `default_value`.
    default_value: The integer ID value to return for out-of-vocabulary feature
      values, defaults to `-1`. This can not be specified with a positive
      `num_oov_buckets`.
    dtype: The type of features. Only string and integer types are supported.

  Returns:
    A `CategoricalColumn` with a vocabulary file.

  Raises:
    ValueError: `vocabulary_file` is missing or cannot be opened.
    ValueError: `vocabulary_size` is missing or < 1.
    ValueError: `num_oov_buckets` is a negative integer.
    ValueError: `num_oov_buckets` and `default_value` are both specified.
    ValueError: `dtype` is neither string nor integer.
  )*categorical_column_with_vocabulary_file_v2)r   vocabulary_filevocabulary_sizenum_oov_bucketsr   r0   s         r4   'categorical_column_with_vocabulary_filer   4  s#    L 
4C4CU4A4C
E Er6   c           	         |st        dj                  |             ||j                  d      rd}|t        j                  |      st        dj                  |             |dk(  rNt        j                  |d      }|j                  dd       }t        j                         rC|j                         }n2t        j                  |d	
      5 }t        d |D              }ddd       t        j                  d|| |       t        |t         j"                        s|dk  rt        dj                  |             |r<|t        dj                  |             |dk  rt        dj                  ||             t%        j&                  |dj                  |              t%        j(                  |        t+        | |||dn||dn|||      S # 1 sw Y   xY w)a  A `CategoricalColumn` with a vocabulary file.

  Use this when your inputs are in string or integer format, and you have a
  vocabulary file that maps each value to an integer ID. By default,
  out-of-vocabulary values are ignored. Use either (but not both) of
  `num_oov_buckets` and `default_value` to specify how to include
  out-of-vocabulary values.

  For input dictionary `features`, `features[key]` is either `Tensor` or
  `SparseTensor`. If `Tensor`, missing values can be represented by `-1` for int
  and `''` for string, which will be dropped by this feature column.

  Example with `num_oov_buckets`:
  File `'/us/states.txt'` contains 50 lines, each with a 2-character U.S. state
  abbreviation. All inputs with values in that file are assigned an ID 0-49,
  corresponding to its line number. All other values are hashed and assigned an
  ID 50-54.

  ```python
  states = categorical_column_with_vocabulary_file(
      key='states', vocabulary_file='/us/states.txt', vocabulary_size=50,
      num_oov_buckets=5)
  columns = [states, ...]
  features = tf.io.parse_example(..., features=make_parse_example_spec(columns))
  linear_prediction = linear_model(features, columns)
  ```

  Example with `default_value`:
  File `'/us/states.txt'` contains 51 lines - the first line is `'XX'`, and the
  other 50 each have a 2-character U.S. state abbreviation. Both a literal
  `'XX'` in input, and other values missing from the file, will be assigned
  ID 0. All others are assigned the corresponding line number 1-50.

  ```python
  states = categorical_column_with_vocabulary_file(
      key='states', vocabulary_file='/us/states.txt', vocabulary_size=51,
      default_value=0)
  columns = [states, ...]
  features = tf.io.parse_example(..., features=make_parse_example_spec(columns))
  linear_prediction, _, _ = linear_model(features, columns)
  ```

  And to make an embedding with either:

  ```python
  columns = [embedding_column(states, 3),...]
  features = tf.io.parse_example(..., features=make_parse_example_spec(columns))
  dense_tensor = input_layer(features, columns)
  ```

  Args:
    key: A unique string identifying the input feature. It is used as the column
      name and the dictionary key for feature parsing configs, feature `Tensor`
      objects, and feature columns.
    vocabulary_file: The vocabulary file name.
    vocabulary_size: Number of the elements in the vocabulary. This must be no
      greater than length of `vocabulary_file`, if less than length, later
      values are ignored. If None, it is set to the length of `vocabulary_file`.
    dtype: The type of features. Only string and integer types are supported.
    default_value: The integer ID value to return for out-of-vocabulary feature
      values, defaults to `-1`. This can not be specified with a positive
      `num_oov_buckets`.
    num_oov_buckets: Non-negative integer, the number of out-of-vocabulary
      buckets. All out-of-vocabulary inputs will be assigned IDs in the range
      `[vocabulary_size, vocabulary_size+num_oov_buckets)` based on a hash of
      the input value. A positive `num_oov_buckets` can not be specified with
      `default_value`.
    file_format: The format of the vocabulary file. The format is 'text' by
      default unless `vocabulary_file` is a string which ends in 'tfrecord.gz'.
      Accepted alternative value for `file_format` is 'tfrecord_gzip'.

  Returns:
    A `CategoricalColumn` with a vocabulary file.

  Raises:
    ValueError: `vocabulary_file` is missing or cannot be opened.
    ValueError: `vocabulary_size` is missing or < 1.
    ValueError: `num_oov_buckets` is a negative integer.
    ValueError: `num_oov_buckets` and `default_value` are both specified.
    ValueError: `dtype` is neither string nor integer.
  zMissing vocabulary_file in {}.Nztfrecord.gztfrecord_gzipz%vocabulary_file in {} does not exist.GZIPr   c                     | dz   S Nr   rK   )r   r   s     r4   rS   z<categorical_column_with_vocabulary_file_v2.<locals>.<lambda>	  s
    !a% r6   rb)modec              3       K   | ]  }d   yw)r   NrK   )r   r   s     r4   r   z=categorical_column_with_vocabulary_file_v2.<locals>.<genexpr>  s     ^Aa^s   z]vocabulary_size = %d in %s is inferred from the number of elements in the vocabulary_file %s.r   zInvalid vocabulary_size in {}.;Can't specify both num_oov_buckets and default_value in {}.!Invalid num_oov_buckets {} in {}.r   r   )r   r   r   r   r   r0   file_format)rb   r   endswithr   Existsr   TFRecordDatasetreducer   r   numpyGFilesumlogginginforf   
tensor_libTensorr   r   r   VocabularyFileCategoricalColumn)	r   r   r   r0   r   r   r
  dsfs	            r4   r   r     s   z 

5<<SA
BB_55mD!K<<(>EEcJKKo%""?F;b		!%78o		"	"	$)//1;;T2 ,a^^+,LL	%&5sOM
 
OZ%6%6	7Oa<O
5<<SA
BB 
H
O
O  :AA
3  ! !
.?.F.Fs.KL
$	(
%%*2a'/B]
 ', ,s   GGz6feature_column.categorical_column_with_vocabulary_listc                    |t        |      dk  rt        dj                  ||             t        t        |            t        |      k7  rt        dj                  ||             t	        j
                  t        j                  |      j                        }|r?|dk7  rt        dj                  |             |dk  rt        dj                  ||             t        j                  |dj                  |       	       ||}n5|j                  |j                  k7  rt        d
j                  |||             t        j                  |dj                  |       	       t        j                  |        t        | t        |      |||      S )a  A `CategoricalColumn` with in-memory vocabulary.

  Use this when your inputs are in string or integer format, and you have an
  in-memory vocabulary mapping each value to an integer ID. By default,
  out-of-vocabulary values are ignored. Use either (but not both) of
  `num_oov_buckets` and `default_value` to specify how to include
  out-of-vocabulary values.

  For input dictionary `features`, `features[key]` is either `Tensor` or
  `SparseTensor`. If `Tensor`, missing values can be represented by `-1` for int
  and `''` for string, which will be dropped by this feature column.

  Example with `num_oov_buckets`:
  In the following example, each input in `vocabulary_list` is assigned an ID
  0-3 corresponding to its index (e.g., input 'B' produces output 2). All other
  inputs are hashed and assigned an ID 4-5.

  ```python
  colors = categorical_column_with_vocabulary_list(
      key='colors', vocabulary_list=('R', 'G', 'B', 'Y'),
      num_oov_buckets=2)
  columns = [colors, ...]
  features = tf.io.parse_example(..., features=make_parse_example_spec(columns))
  linear_prediction, _, _ = linear_model(features, columns)
  ```

  Example with `default_value`:
  In the following example, each input in `vocabulary_list` is assigned an ID
  0-4 corresponding to its index (e.g., input 'B' produces output 3). All other
  inputs are assigned `default_value` 0.


  ```python
  colors = categorical_column_with_vocabulary_list(
      key='colors', vocabulary_list=('X', 'R', 'G', 'B', 'Y'), default_value=0)
  columns = [colors, ...]
  features = tf.io.parse_example(..., features=make_parse_example_spec(columns))
  linear_prediction, _, _ = linear_model(features, columns)
  ```

  And to make an embedding with either:

  ```python
  columns = [embedding_column(colors, 3),...]
  features = tf.io.parse_example(..., features=make_parse_example_spec(columns))
  dense_tensor = input_layer(features, columns)
  ```

  Args:
    key: A unique string identifying the input feature. It is used as the column
      name and the dictionary key for feature parsing configs, feature `Tensor`
      objects, and feature columns.
    vocabulary_list: An ordered iterable defining the vocabulary. Each feature
      is mapped to the index of its value (if present) in `vocabulary_list`.
      Must be castable to `dtype`.
    dtype: The type of features. Only string and integer types are supported. If
      `None`, it will be inferred from `vocabulary_list`.
    default_value: The integer ID value to return for out-of-vocabulary feature
      values, defaults to `-1`. This can not be specified with a positive
      `num_oov_buckets`.
    num_oov_buckets: Non-negative integer, the number of out-of-vocabulary
      buckets. All out-of-vocabulary inputs will be assigned IDs in the range
      `[len(vocabulary_list), len(vocabulary_list)+num_oov_buckets)` based on a
      hash of the input value. A positive `num_oov_buckets` can not be specified
      with `default_value`.

  Returns:
    A `CategoricalColumn` with in-memory vocabulary.

  Raises:
    ValueError: if `vocabulary_list` is empty, or contains duplicate keys.
    ValueError: `num_oov_buckets` is a negative integer.
    ValueError: `num_oov_buckets` and `default_value` are both specified.
    ValueError: if `dtype` is not integer or string.
  r   z5vocabulary_list {} must be non-empty, column_name: {}z5Duplicate keys in vocabulary_list {}, column_name: {}r	  r  r   r  zcolumn_name: {} vocabularyr   z>dtype {} and vocabulary dtype {} do not match, column_name: {}r   r   vocabulary_listr0   r   r   )r   rb   r   setr
   as_dtypenparrayr0   r   r   r   r   VocabularyListCategoricalColumnr   )r   r  r0   r   r   vocabulary_dtypes         r4   'categorical_column_with_vocabulary_listr"  *  s   f 3#7!#;
?FFS	"# # 	_	#o"66
?FFS	"# # __RXXo%>%D%DE
H
O
O  :AA
3  ! !
;BB3GI
]E+666
HOO#S	*+ + .?.F.Fs.KL
$	(
O,!%
' 'r6   z/feature_column.categorical_column_with_identityc                     |dk  rt        dj                  ||             |&|dk  s||k\  rt        dj                  |||             t        j                  |        t	        | ||      S )a	  A `CategoricalColumn` that returns identity values.

  Use this when your inputs are integers in the range `[0, num_buckets)`, and
  you want to use the input value itself as the categorical ID. Values outside
  this range will result in `default_value` if specified, otherwise it will
  fail.

  Typically, this is used for contiguous ranges of integer indexes, but
  it doesn't have to be. This might be inefficient, however, if many of IDs
  are unused. Consider `categorical_column_with_hash_bucket` in that case.

  For input dictionary `features`, `features[key]` is either `Tensor` or
  `SparseTensor`. If `Tensor`, missing values can be represented by `-1` for int
  and `''` for string, which will be dropped by this feature column.

  In the following examples, each input in the range `[0, 1000000)` is assigned
  the same value. All other inputs are assigned `default_value` 0. Note that a
  literal 0 in inputs will result in the same default ID.

  Linear model:

  ```python
  import tensorflow as tf
  video_id = tf.feature_column.categorical_column_with_identity(
      key='video_id', num_buckets=1000000, default_value=0)
  columns = [video_id]
  features = {'video_id': tf.sparse.from_dense([[2, 85, 0, 0, 0],
  [33,78, 2, 73, 1]])}
  linear_prediction = tf.compat.v1.feature_column.linear_model(features,
  columns)
  ```

  Embedding for a DNN model:

  ```python
  import tensorflow as tf
  video_id = tf.feature_column.categorical_column_with_identity(
      key='video_id', num_buckets=1000000, default_value=0)
  columns = [tf.feature_column.embedding_column(video_id, 9)]
  features = {'video_id': tf.sparse.from_dense([[2, 85, 0, 0, 0],
  [33,78, 2, 73, 1]])}
  input_layer = tf.keras.layers.DenseFeatures(columns)
  dense_tensor = input_layer(features)
  ```

  Args:
    key: A unique string identifying the input feature. It is used as the column
      name and the dictionary key for feature parsing configs, feature `Tensor`
      objects, and feature columns.
    num_buckets: Range of inputs and outputs is `[0, num_buckets)`.
    default_value: If set, values outside of range `[0, num_buckets)` will be
      replaced with this value. If not set, values >= num_buckets will cause a
      failure while values < 0 will be dropped.

  Returns:
    A `CategoricalColumn` that returns identity values.

  Raises:
    ValueError: if `num_buckets` is less than one.
    ValueError: if `default_value` is not in range `[0, num_buckets)`.
  r   z"num_buckets {} < 1, column_name {}r   z5default_value {} not in range [0, {}), column_name {}r   number_bucketsr   )rb   r   r   r   IdentityCategoricalColumn)r   r   r   s      r4    categorical_column_with_identityr'    s    B 1_
9@@S  }q'8'4'C
?FF;	-. . $	"
k
H Hr6   zfeature_column.indicator_columnc                     t        | t        t        j                  f      st	        dj                  |             t        |       S )a  Represents multi-hot representation of given categorical column.

  - For DNN model, `indicator_column` can be used to wrap any
    `categorical_column_*` (e.g., to feed to DNN). Consider to Use
    `embedding_column` if the number of buckets/unique(values) are large.

  - For Wide (aka linear) model, `indicator_column` is the internal
    representation for categorical column when passing categorical column
    directly (as any element in feature_columns) to `linear_model`. See
    `linear_model` for details.

  ```python
  name = indicator_column(categorical_column_with_vocabulary_list(
      'name', ['bob', 'george', 'wanda']))
  columns = [name, ...]
  features = tf.io.parse_example(..., features=make_parse_example_spec(columns))
  dense_tensor = input_layer(features, columns)

  dense_tensor == [[1, 0, 0]]  # If "name" bytes_list is ["bob"]
  dense_tensor == [[1, 0, 1]]  # If "name" bytes_list is ["bob", "wanda"]
  dense_tensor == [[2, 0, 0]]  # If "name" bytes_list is ["bob", "bob"]
  ```

  Args:
    categorical_column: A `CategoricalColumn` which is created by
      `categorical_column_with_*` or `crossed_column` functions.

  Returns:
    An `IndicatorColumn`.

  Raises:
    ValueError: If `categorical_column` is not CategoricalColumn type.
  zDUnsupported input type. Input must be a CategoricalColumn. Given: {})rf   r   r   r   rb   r   IndicatorColumnr   s    r4   indicator_columnr+    sJ    J 
&&(A(AB
D
	F-.0 0 
+	,,r6   z*feature_column.weighted_categorical_columnc                     ||j                   s&|j                  st        dj                  |            t	        | ||      S )a  Applies weight values to a `CategoricalColumn`.

  Use this when each of your sparse inputs has both an ID and a value. For
  example, if you're representing text documents as a collection of word
  frequencies, you can provide 2 parallel sparse input features ('terms' and
  'frequencies' below).

  Example:

  Input `tf.Example` objects:

  ```proto
  [
    features {
      feature {
        key: "terms"
        value {bytes_list {value: "very" value: "model"}}
      }
      feature {
        key: "frequencies"
        value {float_list {value: 0.3 value: 0.1}}
      }
    },
    features {
      feature {
        key: "terms"
        value {bytes_list {value: "when" value: "course" value: "human"}}
      }
      feature {
        key: "frequencies"
        value {float_list {value: 0.4 value: 0.1 value: 0.2}}
      }
    }
  ]
  ```

  ```python
  categorical_column = categorical_column_with_hash_bucket(
      column_name='terms', hash_bucket_size=1000)
  weighted_column = weighted_categorical_column(
      categorical_column=categorical_column, weight_feature_key='frequencies')
  columns = [weighted_column, ...]
  features = tf.io.parse_example(..., features=make_parse_example_spec(columns))
  linear_prediction, _, _ = linear_model(features, columns)
  ```

  This assumes the input dictionary contains a `SparseTensor` for key
  'terms', and a `SparseTensor` for key 'frequencies'. These 2 tensors must have
  the same indices and dense shape.

  Args:
    categorical_column: A `CategoricalColumn` created by
      `categorical_column_with_*` functions.
    weight_feature_key: String key for weight values.
    dtype: Type of weights, such as `tf.float32`. Only float and integer weights
      are supported.

  Returns:
    A `CategoricalColumn` composed of two sparse features: one represents id,
    the other represents weight (value) of the id feature in that example.

  Raises:
    ValueError: if `dtype` is not convertible to float.
  z%dtype {} is not convertible to float.r   weight_feature_keyr0   )r   r   rb   r   r   r-  s      r4   weighted_categorical_columnr/    sG    L mU--1B1B
<CCEJ
KK	"++
 r6   zfeature_column.crossed_columnzUse `tf.keras.layers.experimental.preprocessing.HashedCrossing` instead for feature crossing when preprocessing data to train a Keras model.c                    |r|dk  rt        dj                  |            | rt        |       dk  rt        dj                  |             | D ]  }t        |t        j
                        s:t        |t        t        j                  f      st        dj                  |            t        |t        t        j                  f      sxt        dj                  |             t        t        |       ||      S )a  Returns a column for performing crosses of categorical features.

  Crossed features will be hashed according to `hash_bucket_size`. Conceptually,
  the transformation can be thought of as:
    Hash(cartesian product of features) % `hash_bucket_size`

  For example, if the input features are:

  * SparseTensor referred by first key:

    ```python
    shape = [2, 2]
    {
        [0, 0]: "a"
        [1, 0]: "b"
        [1, 1]: "c"
    }
    ```

  * SparseTensor referred by second key:

    ```python
    shape = [2, 1]
    {
        [0, 0]: "d"
        [1, 0]: "e"
    }
    ```

  then crossed feature will look like:

  ```python
   shape = [2, 2]
  {
      [0, 0]: Hash64("d", Hash64("a")) % hash_bucket_size
      [1, 0]: Hash64("e", Hash64("b")) % hash_bucket_size
      [1, 1]: Hash64("e", Hash64("c")) % hash_bucket_size
  }
  ```

  Here is an example to create a linear model with crosses of string features:

  ```python
  keywords_x_doc_terms = crossed_column(['keywords', 'doc_terms'], 50K)
  columns = [keywords_x_doc_terms, ...]
  features = tf.io.parse_example(..., features=make_parse_example_spec(columns))
  linear_prediction = linear_model(features, columns)
  ```

  You could also use vocabulary lookup before crossing:

  ```python
  keywords = categorical_column_with_vocabulary_file(
      'keywords', '/path/to/vocabulary/file', vocabulary_size=1K)
  keywords_x_doc_terms = crossed_column([keywords, 'doc_terms'], 50K)
  columns = [keywords_x_doc_terms, ...]
  features = tf.io.parse_example(..., features=make_parse_example_spec(columns))
  linear_prediction = linear_model(features, columns)
  ```

  If an input feature is of numeric type, you can use
  `categorical_column_with_identity`, or `bucketized_column`, as in the example:

  ```python
  # vertical_id is an integer categorical feature.
  vertical_id = categorical_column_with_identity('vertical_id', 10K)
  price = numeric_column('price')
  # bucketized_column converts numerical feature to a categorical one.
  bucketized_price = bucketized_column(price, boundaries=[...])
  vertical_id_x_price = crossed_column([vertical_id, bucketized_price], 50K)
  columns = [vertical_id_x_price, ...]
  features = tf.io.parse_example(..., features=make_parse_example_spec(columns))
  linear_prediction = linear_model(features, columns)
  ```

  To use crossed column in DNN model, you need to add it in an embedding column
  as in this example:

  ```python
  vertical_id_x_price = crossed_column([vertical_id, bucketized_price], 50K)
  vertical_id_x_price_embedded = embedding_column(vertical_id_x_price, 10)
  dense_tensor = input_layer(features, [vertical_id_x_price_embedded, ...])
  ```

  Args:
    keys: An iterable identifying the features to be crossed. Each element can
      be either:
      * string: Will use the corresponding feature which must be of string type.
      * `CategoricalColumn`: Will use the transformed tensor produced by this
        column. Does not support hashed categorical column.
    hash_bucket_size: An int > 1. The number of buckets.
    hash_key: Specify the hash_key that will be used by the `FingerprintCat64`
      function to combine the crosses fingerprints on SparseCrossOp (optional).

  Returns:
    A `CrossedColumn`.

  Raises:
    ValueError: If `len(keys) < 2`.
    ValueError: If any of the keys is neither a string nor `CategoricalColumn`.
    ValueError: If any of the keys is `HashedCategoricalColumn`.
    ValueError: If `hash_bucket_size < 1`.
  r   z2hash_bucket_size must be > 1. hash_bucket_size: {}   z.keys must be a list with length > 1. Given: {}zuUnsupported key type. All keys must be either string, or categorical column except HashedCategoricalColumn. Given: {}zcategorical_column_with_hash_bucket is not supported for crossing. Hashing before crossing will increase probability of collision. Instead, use the feature name as a string. Given: {}keysr   hash_key)rb   r   r   rf   r   string_typesr   r   r   r   _HashedCategoricalColumnCrossedColumnr   )r3  r   r4  r   s       r4   crossed_columnr8  j  s   ^ 
-1
 ,,2F3C,DF F	TQ
8??EG G NcsC,,-s.0I0IJKfSk# # #*F,K,KLNAAGN NN 
;)9H
N Nr6   z'__internal__.feature_column.DenseColumnc                   X    e Zd ZdZej
                  d        Zej                  d        Zy)DenseColumnzRepresents a column which can be represented as `Tensor`.

  Some examples of this type are: numeric_column, embedding_column,
  indicator_column.
  c                      y)z=`TensorShape` of `get_dense_tensor`, without batch dimension.NrK   r-   s    r4   variable_shapezDenseColumn.variable_shape       	r6   c                      y)ad  Returns a `Tensor`.

    The output of this function will be used by model-builder-functions. For
    example the pseudo code of `input_layer` will be like:

    ```python
    def input_layer(features, feature_columns, ...):
      outputs = [fc.get_dense_tensor(...) for fc in feature_columns]
      return tf.concat(outputs)
    ```

    Args:
      transformation_cache: A `FeatureTransformationCache` object to access
        features.
      state_manager: A `StateManager` to create / access resources such as
        lookup tables.

    Returns:
      `Tensor` of shape [batch_size] + `variable_shape`.
    NrK   r-   r   r   s      r4   get_dense_tensorzDenseColumn.get_dense_tensor  s    , 	r6   N)	rG   rH   rI   rJ   abcabstractpropertyr=  abstractmethodrA  rK   r6   r4   r:  r:    s;     	 	 	 	r6   r:  c                 f    | D ],  }t        |t        j                        s y|j                  r, y y)z+Returns True if all feature columns are V2.FT)rf   r   r   _is_v2_column)r   r   s     r4   is_feature_column_v2rG    s5    ' nnh&<&<=''	
 
r6   c                 `    t        | t              rt        | ||||      S t        | |||      S )zGCreates a weighted sum for a dense/categorical column for linear_model.r   r   r   sparse_combiner
weight_var)r   r   r   rK  )rf   r   '_create_categorical_column_weighted_sum!_create_dense_column_weighted_sumrI  s        r4   _create_weighted_sumrN  !  sF     )*21#'  -1#	 r6   c                     | j                  ||      }| j                  j                         }t        j                  |      d   }t        j
                  |||f      }t        j                  ||d      S )z9Create a weighted sum of a dense column for linear_model.r   )r/   weighted_sumr   )rA  r=  num_elementsr   r/   reshaper   matmul)r   r   r   rK  r   rQ  
batch_sizes          r4   rM  rM  3  sh     ""#7G&&&335,v&q)*VJ+EF&	.	AAr6   c                   ~    e Zd ZdZ ej
                  dd      Zej                  d        Z	ej                  d        Zy)r   zyRepresents a categorical feature.

  A categorical feature typically handled with a `tf.sparse.SparseTensor` of
  IDs.
  IdWeightPair)	id_tensorweight_tensorc                      y)1Returns number of buckets in this sparse feature.NrK   r<  s    r4   r   zCategoricalColumn.num_bucketsG  r>  r6   c                      y)  Returns an IdWeightPair.

    `IdWeightPair` is a pair of `SparseTensor`s which represents ids and
    weights.

    `IdWeightPair.id_tensor` is typically a `batch_size` x `num_buckets`
    `SparseTensor` of `int64`. `IdWeightPair.weight_tensor` is either a
    `SparseTensor` of `float` or `None` to indicate all weights should be
    taken to be 1. If specified, `weight_tensor` must have exactly the same
    shape and indices as `sp_ids`. Expected `SparseTensor` is same as parsing
    output of a `VarLenFeature` which is a ragged matrix.

    Args:
      transformation_cache: A `FeatureTransformationCache` object to access
        features.
      state_manager: A `StateManager` to create / access resources such as
        lookup tables.
    NrK   r@  s      r4   get_sparse_tensorsz$CategoricalColumn.get_sparse_tensorsL  s    ( 	r6   N)rG   rH   rI   rJ   rY   
namedtuplerV  rB  rC  r   rD  r]  rK   r6   r4   r   r   =  sU     (''46, 	 	 	 	r6   r   c                 V   | j                  ||      }t        j                  |j                  t	        j
                  |j                        d   dg      }|j                  }|.t        j                  |t	        j
                  |      d   dg      }t        j                  ||||d      S )a  Create a weighted sum of a categorical column for linear_model.

  Note to maintainer: As implementation details, the weighted sum is
  implemented via embedding_lookup_sparse toward efficiency. Mathematically,
  they are the same.

  To be specific, conceptually, categorical column can be treated as multi-hot
  vector. Say:

  ```python
    x = [0 0 1]  # categorical column input
    w = [a b c]  # weights
  ```
  The weighted sum is `c` in this case, which is same as `w[2]`.

  Another example is

  ```python
    x = [0 1 1]  # categorical column input
    w = [a b c]  # weights
  ```
  The weighted sum is `b + c` in this case, which is same as `w[2] + w[3]`.

  For both cases, we can implement weighted sum via embedding_lookup with
  sparse_combiner = "sum".
  r   r	  rP  )sparse_weightsr   r.   )	r]  r   sparse_reshaperW  r   r/   rX  r   safe_embedding_lookup_sparse)r   r   r   rJ  rK  sparse_tensorsrW  rX  s           r4   rL  rL  c  s    > ,,-A-:<.''~//03R8:) !..---	6q92>@M 
	3	3"
 r6   z/__internal__.feature_column.SequenceDenseColumnc                   Z    e Zd ZdZ ej
                  dd      Zej                  d        Z	y)SequenceDenseColumnzRepresents dense sequence data.TensorSequenceLengthPairdense_tensorsequence_lengthc                      y)zReturns a `TensorSequenceLengthPair`.

    Args:
      transformation_cache: A `FeatureTransformationCache` object to access
        features.
      state_manager: A `StateManager` to create / access resources such as
        lookup tables.
    NrK   r@  s      r4   get_sequence_dense_tensorz-SequenceDenseColumn.get_sequence_dense_tensor  s     	r6   N)
rG   rH   rI   rJ   rY   r^  rf  rB  rD  rk  rK   r6   r4   re  re    s;     (3[33 "EG 		 		r6   re  z6__internal__.feature_column.FeatureTransformationCachec                   $    e Zd ZdZd ZddZd Zy)r|   a  Handles caching of transformations while building the model.

  `FeatureColumn` specifies how to digest an input column to the network. Some
  feature columns require data transformations. This class caches those
  transformations.

  Some features may be used in more than one place. For example, one can use a
  bucketized feature by itself and a cross with it. In that case we
  should create only one bucketization op instead of creating ops for each
  feature column separately. To handle re-use of transformed columns,
  `FeatureTransformationCache` caches all previously transformed columns.

  Example:
  We're trying to use the following `FeatureColumn`s:

  ```python
  bucketized_age = fc.bucketized_column(fc.numeric_column("age"), ...)
  keywords = fc.categorical_column_with_hash_buckets("keywords", ...)
  age_X_keywords = fc.crossed_column([bucketized_age, "keywords"])
  ... = linear_model(features,
                          [bucketized_age, keywords, age_X_keywords]
  ```

  If we transform each column independently, then we'll get duplication of
  bucketization (one for cross, one for bucketization itself).
  The `FeatureTransformationCache` eliminates this duplication.
  c                 <    |j                         | _        i | _        y)a  Creates a `FeatureTransformationCache`.

    Args:
      features: A mapping from feature column to objects that are `Tensor` or
        `SparseTensor`, or can be converted to same via
        `sparse_tensor.convert_to_tensor_or_sparse_tensor`. A `string` key
        signifies a base feature (not-transformed). A `FeatureColumn` key means
        that this `Tensor` is the output of an existing `FeatureColumn` which
        can be reused.
    N)copy	_features_feature_tensors)r-   r   s     r4   r^   z#FeatureTransformationCache.__init__  s     ]]_DNDr6   Nc                 v   || j                   v r| j                   |   S || j                  v r"| j                  |      }|| j                   |<   |S t        |t        j
                        rt        dj                  |            t        |t        j                        st        dj                  |            |}t        j                  d|       	 |j                  | ||      }|$t        dj                  |j                              || j                   |<   |S # t        $ r |j                  | |      }Y Tw xY w)a  Returns a `Tensor` for the given key.

    A `str` key is used to access a base feature (not-transformed). When a
    `FeatureColumn` is passed, the transformed feature is returned if it
    already exists, otherwise the given `FeatureColumn` is asked to provide its
    transformed output, which is then cached.

    Args:
      key: a `str` or a `FeatureColumn`.
      state_manager: A StateManager object that holds the FeatureColumn state.
      training: Boolean indicating whether to the column is being used in
        training mode. This argument is passed to the transform_feature method
        of any `FeatureColumn` that takes a `training` argument. For example, if
        a `FeatureColumn` performed dropout, it could expose a `training`
        argument to control whether the dropout should be applied.

    Returns:
      The transformed `Tensor` corresponding to the `key`.

    Raises:
      ValueError: if key is not found or a transformed `Tensor` cannot be
        computed.
    z)Feature {} is not in features dictionary.z="key" must be either a "str" or "FeatureColumn". Provided: {}zTransforming feature_column %s.)trainingzColumn {} is not supported.)rp  ro  _get_raw_feature_as_tensorrf   r   r5  rb   r   r   r   r   r  debugtransform_featurer.   )r-   r   r   rr  feature_tensorr   transformeds          r4   r~   zFeatureTransformationCache.get  s=   0 d###""3''
dnn66s;n#1dC #s''(BII#NOOc8112 %%+VC[2 2 FMM3V<
B,,
 - 2k 4;;FKKHII$/D&!  B,,T=AkBs   D D87D8c           	      <   | j                   |   }t        j                  |      d j                         j                  }|/|dk(  rt        dj                  |            |dk7  rS        S t        j                  t        j                  t        j                        dj                  |            g      5  t        j                  t        j                  dt        j                              fdfd      cddd       S # 1 sw Y   yxY w)	a  Gets the raw_feature (keyed by `key`) as `tensor`.

    The raw feature is converted to (sparse) tensor and maybe expand dim.

    For both `Tensor` and `SparseTensor`, the rank will be expanded (to 2) if
    the rank is 1. This supports dynamic rank also. For rank 0 raw feature, will
    error out as it is not supported.

    Args:
      key: A `str` key to access the raw feature.

    Returns:
      A `Tensor` or `SparseTensor`.

    Raises:
      ValueError: if the raw feature has rank 0.
    c                     t        | t        j                        r.t        j                  | t        j                  |       d   dg      S t        j                  | d      S )Nr   r   r	  )rf   sparse_tensor_libSparseTensorr   ra  r   r/   expand_dims)input_tensors    r4   r|  zJFeatureTransformationCache._get_raw_feature_as_tensor.<locals>.expand_dims$  sU    	L"3"@"@	A((*3//,*G*JA)NP 	P $$\266r6   Nr   z/Feature (key: {}) cannot have rank 0. Given: {}r   )messagec                              S rR   rK   )r|  rv  s   r4   rS   zGFeatureTransformationCache._get_raw_feature_as_tensor.<locals>.<lambda>=  s    +n- r6   c                       S rR   rK   )rv  s   r4   rS   zGFeatureTransformationCache._get_raw_feature_as_tensor.<locals>.<lambda>=  s    ~ r6   )ro  rz  "convert_to_tensor_or_sparse_tensor	get_shapendimsrb   r   r   control_dependenciesr   assert_positiver   rankr   r   equal)r-   r   raw_featurer  r|  rv  s       @@r4   rs  z5FeatureTransformationCache._get_raw_feature_as_tensor  s   $ ..%K&IIN7 ##%++D	=DD^%& 	&  $qy^Ik..II 
	!	!!!NN>*ELL^%	&# 
 G YY
..INN>:
;
-/EGG G Gs   ADDrR   )rG   rH   rI   rJ   r^   r~   rs  rK   r6   r4   r|   r|     s    86p/Gr6   r|   c           
         t        j                  |       } t        | t         j                        r| S t	        j
                  dd| |f      5  |S| j                  t        j                  k(  rd}n3| j                  j                  rd}n| j                  j                         }t        j                  || j                  d      }t        j                  t        j                  | |      d      }t        j                  |t        j                   | |d      t        j"                  | t        j$                  d	
            cddd       S # 1 sw Y   yxY w)a(  Converts a `Tensor` to a `SparseTensor`, dropping ignore_value cells.

  If `input_tensor` is already a `SparseTensor`, just return it.

  Args:
    input_tensor: A string or integer `Tensor`.
    ignore_value: Entries in `dense_tensor` equal to this value will be absent
      from the resulting `SparseTensor`. If `None`, default value of
      `dense_tensor`'s dtype will be used ('' for `str`, -1 for `int`).

  Returns:
    A `SparseTensor` with the same shape as `input_tensor`.

  Raises:
    ValueError: when `input_tensor`'s rank is `None`.
  Nto_sparse_input r	  ignore_valuer   indicesrx   dense_shape)out_typer.   r  rx   r  )rz  r  rf   r{  r   r{   r0   r
   stringr   as_numpy_dtyper   castr   where_v2	not_equal	gather_ndr/   int64)r}  r  r  s      r4   '_to_sparse_input_and_drop_ignore_valuesr  A  s&   " #EE,/<<=
~~d-0  F 			v}}	,((
 $))88:==l((~?L  <6YHG))""<xHOO6<<mEF'F F Fs   C4E		Ec                    t        | t        j                        r| g} t        | t        j                        rt        |       } t        | t              rt        d      | D ]@  }t        |t        j                        rt        dj                  t        |      |             | st        d      i }| D ]G  }|j                  |v r(t        dj                  |||j                                 |||j                  <   I t        | 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                     | j                   S rR   r   r   s    r4   rS   z,_normalize_feature_columns.<locals>.<lambda>  s
    qvv r6   r   )rf   r   r   r$   Iteratorr   dictrb   r   r   r.   r   )r   r   name_to_columns      r4   rz   rz   p  s     !7!78&'O!9!9:?+O&
K
LL Lffh445 ..4fT&\6.JL LL 

9
::. )f{{n$ ( )/v/=fkk/J)L	M M #)N6;;) 
%5	66r6   c                   h   e Zd ZdZed        Zed        Zed        Ze ej                  e
e      d               Zd Z ej                  e
e      d        Zd Zed	        Ze ej                  e
e      d
               Zd Z ej                  e
e      dd       Zed        Zd Zedd       Zy)r   zsee `numeric_column`.c                      yNTrK   r<  s    r4   rF  zNumericColumn._is_v2_column      r6   c                     | j                   S See `FeatureColumn` base class.r   r<  s    r4   r.   zNumericColumn.name       88Or6   c                     | j                   t        j                  | j                  | j                  | j
                        iS r  )r   r   FixedLenFeaturer/   r0   r   r<  s    r4   r   z NumericColumn.parse_example_spec  s8     	''

DJJ(,(:(:< r6   c                     | j                   S rR   r   r<  s    r4   _parse_example_specz!NumericColumn._parse_example_spec       """r6   c                     t        |t        j                        r$t        dj	                  | j
                              | j                  | j                  |      }t        j                  |t        j                        S )NzeThe corresponding Tensor of numerical column must be a Tensor. SparseTensor is not supported. key: {})rf   rz  r{  rb   r   r   r   r   r  r
   float32r-   r}  s     r4   _transform_input_tensorz%NumericColumn._transform_input_tensor  sh    , 1 > >?3396$((3CE E %''5l==v~~66r6   c                 Z    |j                  | j                        }| j                  |      S rR   r~   r   r  r-   inputsr}  s      r4   _transform_featurez NumericColumn._transform_feature  s'     ::dhh'L''55r6   c                 \    |j                  | j                  |      }| j                  |      S )a  See `FeatureColumn` base class.

    In this case, we apply the `normalizer_fn` to the input tensor.

    Args:
      transformation_cache: A `FeatureTransformationCache` object to access
        features.
      state_manager: A `StateManager` to create / access resources such as
        lookup tables.

    Returns:
      Normalized input tensor.
    Raises:
      ValueError: If a SparseTensor is passed in.
    r  r-   r   r   r}  s       r4   ru  zNumericColumn.transform_feature  s+      (++DHHmDL''55r6   c                 @    t        j                  | j                        S See `DenseColumn` base class.)r   TensorShaper/   r<  s    r4   r=  zNumericColumn.variable_shape  s     ##DJJ//r6   c                     | j                   S rR   r=  r<  s    r4   _variable_shapezNumericColumn._variable_shape       r6   c                 &    |j                  | |      S )aK  Returns dense `Tensor` representing numeric feature.

    Args:
      transformation_cache: A `FeatureTransformationCache` object to access
        features.
      state_manager: A `StateManager` to create / access resources such as
        lookup tables.

    Returns:
      Dense `Tensor` created within `transform_feature`.
    r~   r@  s      r4   rA  zNumericColumn.get_dense_tensor  s      ##D-88r6   Nc                 (    ~~|j                  |       S rR   r  r-   r  weight_collectionsr1   s       r4   _get_dense_tensorzNumericColumn._get_dense_tensor  s     	::dr6   c                     | j                   gS See 'FeatureColumn` base class.r   r<  s    r4   parentszNumericColumn.parents	       HH:r6   c                     t        t        | j                  |             }t        j                  | j
                        |d<   | j                  j                  |d<   |S )r  r   r0   )r  zip_fieldsr   _serialize_keras_objectr   r0   r.   r-   r   s     r4   
get_configzNumericColumn.get_config	  sK    #dllD)*F+CCF?jjooF7OMr6   c                     t        || j                         t        |      }t        j                  |d   |      |d<   t        j                  |d         |d<    | di |S )r  r   )custom_objectsr0   rK   )_check_config_keysr  _standardize_and_copy_configr   _deserialize_keras_objectr
   r  clsr   r  columns_by_namekwargss        r4   from_configzNumericColumn.from_config	  s`     vs{{+)&1F+EE%'F? oofWo6F7O==r6   NN)rG   rH   rI   rJ   propertyrF  r.   r   r!   
deprecated _FEATURE_COLUMN_DEPRECATION_DATE_FEATURE_COLUMN_DEPRECATIONr  r  r  ru  r=  r  rA  r  r  r  classmethodr  rK   r6   r4   r   r     s=          ;:57#7 #7 ;:576766& 0 0 ;:577 9  ;:577
   	 	r6   r   r   c                      e Zd ZdZed        Zed        Zed        Ze ej                  e
e      d               Z ej                  e
e      d        Zd Zed        Ze ej                  e
e      d	               Zd
 Zd Z ej                  e
e      dd       Zed        Ze ej                  e
e      d               Zd Zd Z ej                  e
e      	 	 dd       Zed        Zd Zedd       Zy)r   zSee `bucketized_column`.c                 z    t        | j                  t        j                        xr | j                  j                  S rR   )rf   r   r   r   rF  r<  s    r4   rF  zBucketizedColumn._is_v2_column&	  s3     	4%%x'='=> 	-,,r6   c                 L    dj                  | j                  j                        S )r  z{}_bucketized)r   r   r.   r<  s    r4   r.   zBucketizedColumn.name-	  s!     !!$"4"4"9"9::r6   c                 .    | j                   j                  S r  )r   r   r<  s    r4   r   z#BucketizedColumn.parse_example_spec2	  s     000r6   c                 .    | j                   j                  S rR   )r   r  r<  s    r4   r  z$BucketizedColumn._parse_example_spec7	  s     111r6   c                 z    |j                  | j                        }t        j                  || j                        S z6Returns bucketized categorical `source_column` tensor.)r   r~   r   r   
_bucketizer   )r-   r  source_tensors      r4   r  z#BucketizedColumn._transform_feature=	  s5     JJt112M??$ $r6   c                 |    |j                  | j                  |      }t        j                  || j                        S r  r  )r-   r   r   r  s       r4   ru  z"BucketizedColumn.transform_featureF	  s7    (,,T-?-?OM??$ $r6   c                     t        j                  t        | j                  j                        t        | j                        dz   fz         S )r  r   )r   r  r   r   r/   r   r   r<  s    r4   r=  zBucketizedColumn.variable_shapeM	  sC     ##d  &&'3t+?!+C*EEG Gr6   c                     | j                   S rR   r  r<  s    r4   r  z BucketizedColumn._variable_shapeS	  r  r6   c                     t        j                  t        j                  |t        j
                        t        | j                        dz   dd      S )Nr   r   r   )r  depthon_value	off_value)r   one_hotr   r  r
   r  r   r   r  s     r4   "_get_dense_tensor_for_input_tensorz3BucketizedColumn._get_dense_tensor_for_input_tensorY	  s>    lFLL9$//"Q&	 r6   c                 H    |j                  | |      }| j                  |      S )z'Returns one hot encoded dense `Tensor`.r~   r  r  s       r4   rA  z!BucketizedColumn.get_dense_tensor`	  s%    '++D-@L22<@@r6   Nc                 J    ~~|j                  |       }| j                  |      S rR   r  r-   r  r  r1   r}  s        r4   r  z"BucketizedColumn._get_dense_tensore	  s)     	::d#L22<@@r6   c                 f    t        | j                        dz   | j                  j                  d   z  S )#See `CategoricalColumn` base class.r   r   )r   r   r   r/   r<  s    r4   r   zBucketizedColumn.num_bucketsm	  s.      1$(:(:(@(@(CCCr6   c                     | j                   S rR   r   r<  s    r4   r   zBucketizedColumn._num_bucketss	       r6   c           
      ,   t        j                  |      d   }| j                  j                  d   }t        j                  t        j                  t        j
                  t        j                  d|      d      d|g      d      }t        j                  t        j                  d|      |g      }t        j                  |d      t        | j                        dz   |z  z   }t        j                  t        j                  t        j                  ||f            t        j                        }t        j                  t        j                  ||g      t        j                        }t!        j"                  |||      }	t$        j'                  |	d       S )Nr   r   )r	  r  )r   r/   r   rR  tiler|  r   r   r   r   r  	transposer   stackr
   r  rz  r{  r   rV  )
r-   r}  rT  source_dimensioni1i2bucket_indicesr  r  r   s
             r4   $_get_sparse_tensors_for_input_tensorz5BucketizedColumn._get_sparse_tensors_for_input_tensory	  sM   .q1J))//2			!!(..J"?C !	#$)
+B 
q*:;j\	JB 	,	!$'$81$<#B	C  mmO112r(;<fllLG--z+;<=v||MK%22KIM))->>r6   c                 H    |j                  | |      }| j                  |      S zDConverts dense inputs to SparseTensor so downstream code can use it.r~   r  r  s       r4   r]  z#BucketizedColumn.get_sparse_tensors	  s%    '++D-@L44\BBr6   c                 J    ~~|j                  |       }| j                  |      S r  r  r  s        r4   _get_sparse_tensorsz$BucketizedColumn._get_sparse_tensors	  s)     	::d#L44\BBr6   c                     | j                   gS r  )r   r<  s    r4   r  zBucketizedColumn.parents	  s     r6   c                 z    ddl m} t        t        | j                  |             } || j
                        |d<   |S )r  r   serialize_feature_columnr   ).tensorflow.python.feature_column.serializationr  r  r  r  r   r-   r  r   s      r4   r  zBucketizedColumn.get_config	  s4    W#dllD)*F6t7I7IJF?Mr6   c                     ddl m} t        || j                         t	        |      } ||d   ||      |d<    | di |S )r  r   deserialize_feature_columnr   rK   r  r  r  r  r  r  r   r  r  r  r  s         r4   r  zBucketizedColumn.from_config	  sH     Zvs{{+)&1F8BF?==r6   r  )rG   rH   rI   rJ   r  rF  r.   r   r!   r  r  r  r  r  ru  r=  r  r  rA  r  r   r   r  r]  r	  r  r  r  r  rK   r6   r4   r   r   	  s    !  ; ; 1 1 ;:5727 2 ;:57$7$$ G G
 ;:577 A
 ;:57A7A D D
 ;:577 ?0C
 ;:57 .2$(C7C      r6   r   )r   r   c                       e Zd ZdZ	 d fd	Zed        Zed        Zed        Ze e	j                  ee      d               Zd Z e	j                  ee      d        Zed	        Ze e	j                  ee      d
               Zd Zd Zd Zd Zd Z e	j                  ee      dd       Zd Z e	j                  ee      	 	 dd       Zed        Zd Zedd       Z xZS )r   See `embedding_column`.c
                 >    t         t        |   | |||||||||	
      S )Nr   )superr   __new__)r  r   r   r   r3   r   r   r   r1   r   	__class__s             r4   r  zEmbeddingColumn.__new__	  s<     #.-+/"; / 
= 
=r6   c                 z    t        | j                  t        j                        xr | j                  j                  S rR   rf   r   r   r   rF  r<  s    r4   rF  zEmbeddingColumn._is_v2_column	  3     	4**H,B,BC 	2##11r6   c                 L    dj                  | j                  j                        S )r  z{}_embeddingr   r   r.   r<  s    r4   r.   zEmbeddingColumn.name	  !       !8!8!=!=>>r6   c                 .    | j                   j                  S r  r   r   r<  s    r4   r   z"EmbeddingColumn.parse_example_spec	       ""555r6   c                 .    | j                   j                  S rR   r   r  r<  s    r4   r  z#EmbeddingColumn._parse_example_spec	       ""666r6   c                 :    |j                  | j                  |      S )z+Transforms underlying `categorical_column`.r~   r   r@  s      r4   ru  z!EmbeddingColumn.transform_feature	      ##D$;$;]KKr6   c                 8    |j                  | j                        S rR   r(  r-   r  s     r4   r  z"EmbeddingColumn._transform_feature	  s     ::d--..r6   c                 B    t        j                  | j                  g      S r  )r   r  r   r<  s    r4   r=  zEmbeddingColumn.variable_shape	  s     ##T^^$455r6   c                     | j                   S rR   r  r<  s    r4   r  zEmbeddingColumn._variable_shape
  r  r6   c           	      2   | j                   r| j                  j                  n| j                  j                  }t	        | j                  d|      }|| j
                  f}|j                  | d|t        j                  | j                  d| j                         y)z&Creates the embedding lookup variable.r   embedding_weightsT)r.   r/   r0   r1   r2   r3   N)rF  r   r   r   getattrr   r5   r
   r  r1   r3   )r-   r   default_num_bucketsr   embedding_shapes        r4   create_statezEmbeddingColumn.create_state
  s      	++#'#:#:#G#G  $11=-/K"DNN3O!! nn..$$ " &r6   c                    |j                   }|j                  }| j                  X|}t        |t        j
                        r|j                         }t        j                  | j                  | j                  |i       t        j                  |j                  j                         d         }t        j                  }| j                   s||dk  rt        j"                  } ||||| j$                  d| j&                  z  | j(                        S )Nr   r1  
%s_weightsr   r.   r   )rW  rX  r   rf   r   rg   _get_variable_listr    init_from_checkpointr   r   dimension_valuer  r  r   rb  r   embedding_lookup_sparse_v2r   r.   r   )r-   rc  r/  
sparse_idsr`  
to_restoresparse_id_rankembedding_lookup_sparses           r4   !_get_dense_tensor_internal_helperz1EmbeddingColumn._get_dense_tensor_internal_helper
  s    ))J#11N)$j	J	 = =	>224
++

 
 4#;#;Z"HJ "11((*1-/N+HH**~/I! - H H"DII%   r6   c                 L    |j                  | d      }| j                  ||      S )z>Private method that follows the signature of get_dense_tensor.r/  r   )r=   r?  )r-   rc  r   r/  s       r4   _get_dense_tensor_internalz*EmbeddingColumn._get_dense_tensor_internal3
  s8    %22& 3 (11.2CE Er6   c                 z   | j                   j                  | j                  f}|rEt        j                  j
                  |vr)|j                  t        j                  j
                         t        j                  d|t        j                  | j                  | j                  xr ||      }| j                  ||      S )?Private method that follows the signature of _get_dense_tensor.r/  )r.   r/   r0   r3   r1   rY   )r   r   r   r   	GraphKeysGLOBAL_VARIABLESr   r   r=   r
   r  r3   r1   r?  )r-   rc  r  r1   r2  r/  s         r4   _old_get_dense_tensor_internalz.EmbeddingColumn._old_get_dense_tensor_internal:
  s     ..;;T^^LO&&.@@ > >?&33 nn$$...Y&( 11.2CE Er6   c                    t        | j                  t              rCt        dj	                  | j
                  t        | j                        | j                              | j                  j                  ||      }| j                  ||      S )a  Returns tensor after doing the embedding lookup.

    Args:
      transformation_cache: A `FeatureTransformationCache` object to access
        features.
      state_manager: A `StateManager` to create / access resources such as
        lookup tables.

    Returns:
      Embedding lookup tensor.

    Raises:
      ValueError: `categorical_column` is SequenceCategoricalColumn.
    5  In embedding_column: {}. categorical_column must not be of type SequenceCategoricalColumn. Suggested fix A: If you wish to use DenseFeatures, use a non-sequence categorical_column_with_*. Suggested fix B: If you wish to create sequence input, use SequenceFeatures instead of DenseFeatures. Given (type {}): {})	rf   r   r   rb   r   r.   r   r]  rA  r-   r   r   rc  s       r4   rA  z EmbeddingColumn.get_dense_tensorK
  s     $))+DE  !'tyy$t7N7N2O'+'>'>!@A A ,,??m-N**>=IIr6   c                 <   t        | j                  t        t        j                  f      rCt        dj                  | j                  t        | j                        | j                              | j                  j                  |||      }| j                  |||      S )Na6  In embedding_column: {}. categorical_column must not be of type _SequenceCategoricalColumn. Suggested fix A: If you wish to use DenseFeatures, use a non-sequence categorical_column_with_*. Suggested fix B: If you wish to create sequence input, use SequenceFeatures instead of DenseFeatures. Given (type {}): {})rf   r   r   r   r   rb   r   r.   r   r	  rF  r-   r  r  r1   rc  s        r4   r  z!EmbeddingColumn._get_dense_tensori
  s     	"F$E$EFH   !'tyy$t7N7N2O'+'>'>!@A A ,,@@"I/N..~/A9N Nr6   c                    t        | j                  t              sCt        dj	                  | j
                  t        | j                        | j                              | j                  j                  ||      }| j                  ||      }t        j                  |j                        }t        j                  ||      S %See `SequenceDenseColumn` base class.In embedding_column: {}. categorical_column must be of type SequenceCategoricalColumn to use SequenceFeatures. Suggested fix: Use one of sequence_categorical_column_with_*. Given (type {}): {}rg  )rf   r   r   rb   r   r.   r   r]  rA  r   "sequence_length_from_sparse_tensorrW  re  rf  )r-   r   r   rc  rh  ri  s         r4   rk  z)EmbeddingColumn.get_sequence_dense_tensor}
  s    d--/HI  !'tyy$t7N7N2O'+'>'>!@A A ,,??m-N22>3@BLAA  "O77!? 8 D Dr6   c                    t        | j                  t        t        j                  f      sCt        dj                  | j                  t        | j                        | j                              | j                  j                  |      }| j                  |||      }t        j                  |j                        }t        j                  ||      S )NrO  )r  r1   rg  )rf   r   r   r   r   rb   r   r.   r   r	  rF  r   rP  rW  re  rf  )r-   r  r  r1   rc  rh  ri  s          r4   _get_sequence_dense_tensorz*EmbeddingColumn._get_sequence_dense_tensor
  s     	"F$E$EFH   !'tyy$t7N7N2O'+'>'>!@A A ,,@@HN66- 7 L AA  "O77!? 8 D Dr6   c                     | j                   gS r  r*  r<  s    r4   r  zEmbeddingColumn.parents
       ##$$r6   c                     t        t        | j                  |             }t        j                  | j
                        |d<   t        j                  | j                        |d<   |S )r  r   r3   )r  r  r  r   r  r   r  r3   r  s     r4   r  zEmbeddingColumn.get_config
  sY    #dllD)*F#0#I#I$!F )AAF=Mr6   c                 >   d|vrd|d<   t        || j                         t        |      }t        j                  |d   ||      |d<   t        t        j                  t        t        j                              }t        j                  |d   ||      |d<    | di |S )r  r   Tr   r3   )module_objectsr  rK   )r  r  r  r   r  r  r#   
getmembersr   isclassr  )r  r   r  r  r  all_initializerss         r4   r  zEmbeddingColumn.from_config
  s     #&0,0f()vs{{+)&1F#0#K#K#$no$GF J11(J<N<NOP)CC}'%'F= ==r6   Tr  )rG   rH   rI   rJ   r  r  rF  r.   r   r!   r  r  r  r  ru  r  r=  r  r3  r?  rA  rF  rA  r  rk  rR  r  r  r  r  __classcell__r  s   @r4   r   r   	  s      )-=,   ? ? 6 6 ;:5777 7L ;:57/7/ 6 6 ;:577 &" 6EE"J< ;:57N7N$D& ;:57 59+/D7D0 % %  r6   r   r   c                      t        d      )NzSharedEmbeddingColumns are not supported in `linear_model` or `input_layer`. Please use `DenseFeatures` or `LinearModel` instead.)rb   rK   r6   r4   $_raise_shared_embedding_column_errorr_  
  s     ? 	@ @r6   c                   B    e Zd ZdZ	 	 ddZd Zed        Zed        Zy)r   z-Class that creates a `SharedEmbeddingColumn`.c	                     || _         || _        || _        || _        || _        || _        || _        || _        i | _        y rR   )	
_dimension_initializer_ckpt_to_load_from_tensor_name_in_ckptr   rU   _name_use_safe_embedding_lookup_embedding_weights)	r-   r   r3   r   r   r   r1   r.   r   s	            r4   r^   z%SharedEmbeddingColumnCreator.__init__
  sI      DO#D/D 3D#DDODJ&?D# Dr6   c                 4    t        || ||| j                        S rR   )SharedEmbeddingColumnrg  )r-   r   r   r   s       r4   __call__z%SharedEmbeddingColumnCreator.__call__
  s#     !3T8X!%!@!@B Br6   c                    t        j                         j                  }|| j                  vr| j                  | j
                  f}t        j                  | j                  |t        j                  | j                  | j                        }| j                  X|}t        |t        j                         r|j#                         }t%        j&                  | j                  | j(                  |i       || j                  |<   | j                  |   S )N)r.   r/   r0   r3   r1   )r   get_default_graph
_graph_keyrh  r   rb  r   r=   rf  r
   r  rc  rU   rd  rf   r   rg   r7  r    r8  re  )r-   r   r2  r8   r<  s        r4   r/  z.SharedEmbeddingColumnCreator.embedding_weights
  s    



!
,
,C
$)))**DOO<o''zz''OO%c 
	 	 	,
j)"?"?@!446*--##d&?&?%L	N%(dc"""3''r6   c                     | j                   S rR   )rb  r<  s    r4   r   z&SharedEmbeddingColumnCreator.dimension
  s    ??r6   N)shared_embedding_column_creatorT)	rG   rH   rI   rJ   r^   rk  r  r/  r   rK   r6   r4   r   r   
  s@    5 6)-!(B ( ((  r6   r   c                        e Zd ZdZ	 d fd	Zed        Zed        Zed        Zed        Z	d Z
d Zed	        Zed
        Zd Zd ZddZd Z	 	 ddZed        Z xZS )rj  r  c                 6    t         t        |   | |||||      S )Nr   rp  r   r   r   )r  rj  r  )r  r   rp  r   r   r   r  s         r4   r  zSharedEmbeddingColumn.__new__  s1     &4-(G"; 5 = =r6   c                      yr  rK   r<  s    r4   rF  z#SharedEmbeddingColumn._is_v2_column  r  r6   c                 L    dj                  | j                  j                        S )r  z{}_shared_embeddingr  r<  s    r4   r.   zSharedEmbeddingColumn.name"  s!     !''(?(?(D(DEEr6   c                 .    | j                   j                  S r  r"  r<  s    r4   r   z(SharedEmbeddingColumn.parse_example_spec'  r#  r6   c                     t               S rR   r_  r<  s    r4   r  z)SharedEmbeddingColumn._parse_example_spec,      /11r6   c                 :    |j                  | j                  |      S r  r(  r@  s      r4   ru  z'SharedEmbeddingColumn.transform_feature0  r)  r6   c                     t               S rR   rx  r+  s     r4   r  z(SharedEmbeddingColumn._transform_feature4      /11r6   c                 V    t        j                  | j                  j                  g      S r  )r   r  rp  r   r<  s    r4   r=  z$SharedEmbeddingColumn.variable_shape7  s)     ##		-	-	7	78: :r6   c                     t               S rR   rx  r<  s    r4   r  z%SharedEmbeddingColumn._variable_shape=  ry  r6   c           	      (   t        j                  d| j                        5  | j                  j	                  ||      }|j
                  }|j                  }| j                  j                  }t        j                  |j                  j                         d         }t        j                  }| j                  s||dk  rt        j                   } ||||| j"                  d| j                  z  | j$                        cddd       S # 1 sw Y   yxY w)rC  Nry   r   r1  r5  r6  )r   r{   r.   r   r]  rW  rX  rp  r/  r   r9  r  r  r   rb  r   r:  r   r   )	r-   r   r   rc  r;  r`  r/  r=  r>  s	            r4   rA  z0SharedEmbeddingColumn._get_dense_tensor_internalA  s    
 
499	5 "..AA
/n!++j%33n>>PP#33

 
 
*
*
,Q
/1n - J J,,1K
A
"/"J"J$


==dii'=="!" " "s   CDDc                     t        | j                  t              rCt        dj	                  | j
                  t        | j                        | j                              | j                  ||      S )z$Returns the embedding lookup result.rH  )rf   r   r   rb   r   r.   r   rA  r@  s      r4   rA  z&SharedEmbeddingColumn.get_dense_tensor^  sf    $))+DE  !'tyy$t7N7N2O'+'>'>!@A A **+?OOr6   c                     t               S rR   rx  r  s       r4   r  z'SharedEmbeddingColumn._get_dense_tensorl  r|  r6   c                    t        | j                  t              sCt        dj	                  | j
                  t        | j                        | j                              | j                  ||      }| j                  j                  ||      }t        j                  |j                        }t        j                  ||      S rM  )rf   r   r   rb   r   r.   r   rA  r]  r   rP  rW  re  rf  r-   r   r   rh  rc  ri  s         r4   rk  z/SharedEmbeddingColumn.get_sequence_dense_tensoro  s    d--/HI  !'tyy$t7N7N2O'+'>'>!@A A 223G3@BL,,??m-NAA  "O77!? 8 D Dr6   c                     t               S rR   rx  r  s       r4   rR  z0SharedEmbeddingColumn._get_sequence_dense_tensor  s     011r6   c                     | j                   gS r  r*  r<  s    r4   r  zSharedEmbeddingColumn.parents  rT  r6   r[  r  )rG   rH   rI   rJ   r  r  rF  r.   r   r  ru  r  r=  r  rA  rA  r  rk  rR  r  r\  r]  s   @r4   rj  rj    s       )-=   F F 6 6 2 2L2 : :
 2 2":P2D* 59+/2 % %r6   rj  rs  c                     | J t        j                  |       s| g} t        |       } | D ]M  }t        |t              st        dj                  | |            |dk  s4t        dj                  | |             | S )z4Returns shape if it's valid, raises error otherwise.z4shape dimensions must be integer. shape: {}, key: {}r   z;shape dimensions must be greater than 0. shape: {}, key: {})r"   	is_nestedr   rf   intr   r   rb   )r/   r   r   s      r4   r   r     s    					GE
,% @ii% ++16%+=? ?1} ,,2F5#,>@ @@ 
,r6   c                   l   e Zd ZdZed        Zed        Zed        Ze ej                  e
e      d               Zd Zd Z ej                  e
e      d        Zed	        Ze ej                  e
e      d
               Zd Z ej                  e
e      	 	 dd       Zed        Zd Zedd       Zy)r   z*see `categorical_column_with_hash_bucket`.c                      yr  rK   r<  s    r4   rF  z%HashedCategoricalColumn._is_v2_column  r  r6   c                     | j                   S r  r   r<  s    r4   r.   zHashedCategoricalColumn.name  r  r6   c                 X    | j                   t        j                  | j                        iS r  r   r   VarLenFeaturer0   r<  s    r4   r   z*HashedCategoricalColumn.parse_example_spec  "     HHk//

;<<r6   c                     | j                   S rR   r  r<  s    r4   r  z+HashedCategoricalColumn._parse_example_spec  r  r6   c                    t        |t        j                        st        d      t	        j
                  |j                  dj                  | j                               | j                  j                  |j                  j                  k7  r:t        dj                  | j                  | j                  |j                              | j                  t        j                  k(  r|j                  }nt        j                  |j                        }t        j                  || j                   d      }t        j                  |j"                  ||j$                        S )(Hashes the values in the feature_column.z*SparseColumn input must be a SparseTensor.column_name: {} input_tensorr   dColumn dtype and SparseTensors dtype must be compatible. key: {}, column dtype: {}, tensor dtype: {}lookupr   )rf   rz  r{  rb   r   r   r0   r   r   r   r
   r  rx   r   	as_stringstring_to_hash_bucket_fastr   r  r  )r-   r}  sparse_valuessparse_id_valuess       r4   r  z/HashedCategoricalColumn._transform_input_tensor  s   l$5$B$BCCDD!!-44TXX>@ zz 2 2 = ==88>hh

L$6$6989 9
 zzV]]""))m **<+>+>?m!<<t,,8=)),*>*>*:*6*B*BD Dr6   c                 n    t        |j                  | j                  |            }| j                  |      S )r  r  r~   r   r  r  s       r4   ru  z)HashedCategoricalColumn.transform_feature  1    :  =9;L''55r6   c                 l    t        |j                  | j                              }| j                  |      S rR   r  r  s      r4   r  z*HashedCategoricalColumn._transform_feature  ,     ;6::dhh;OPL''55r6   c                     | j                   S rZ  r   r<  s    r4   r   z#HashedCategoricalColumn.num_buckets          r6   c                     | j                   S rR   r  r<  s    r4   r   z$HashedCategoricalColumn._num_buckets  r  r6   c                 N    t         j                  |j                  | |      d      S r  Nr   rV  r~   r@  s      r4   r]  z*HashedCategoricalColumn.get_sparse_tensors  '    ))  }5t= =r6   Nc                 P    ~~t         j                  |j                  |       d       S rR   r  r  s       r4   r	  z+HashedCategoricalColumn._get_sparse_tensors  &     	))&**T*:DAAr6   c                     | j                   gS r  r   r<  s    r4   r  zHashedCategoricalColumn.parents  r  r6   c                 v    t        t        | j                  |             }| j                  j                  |d<   |S r  r0   r  r  r  r0   r.   r  s     r4   r  z"HashedCategoricalColumn.get_config  -    #dllD)*FjjooF7OMr6   c                     t        || j                         t        |      }t        j                  |d         |d<    | di |S r  r0   rK   r  r  r  r
   r  r  s        r4   r  z#HashedCategoricalColumn.from_config  >     vs{{+)&1FoofWo6F7O==r6   r  rG   rH   rI   rJ   r  rF  r.   r   r!   r  r  r  r  r  ru  r  r   r   r]  r	  r  r  r  r  rK   r6   r4   r   r     sH    3    = = ;:57#7 #D46 ;:57676 ! ! ;:577 =
 ;:57 .2$(B7B    r6   r   r   c                       e Zd ZdZ	 d fd	Zed        Zed        Zed        Ze e	j                  ee      d               Zd Zd Zdd	Zd
 Z e	j                  ee      d        Zed        Ze e	j                  ee      d               Zd Z e	j                  ee      	 	 dd       Zed        Zd Zedd       Z xZS )r  z.See `categorical_column_with_vocabulary_file`.c           
      :    t         t        |   | |||||||      S )Nr   r   r   r   r0   r   r
  )r  r  r  )	r  r   r   r   r   r0   r   r
  r  s	           r4   r  z'VocabularyFileCategoricalColumn.__new__  s7     0#>'''# ? ! !r6   c                      yr  rK   r<  s    r4   rF  z-VocabularyFileCategoricalColumn._is_v2_column*  r  r6   c                     | j                   S r  r   r<  s    r4   r.   z$VocabularyFileCategoricalColumn.name.  r  r6   c                 X    | j                   t        j                  | j                        iS r  r  r<  s    r4   r   z2VocabularyFileCategoricalColumn.parse_example_spec3  r  r6   c                     | j                   S rR   r  r<  s    r4   r  z3VocabularyFileCategoricalColumn._parse_example_spec8  r  r6   c                     t        j                  | j                  d      }fd}t        j                  |j                  |      | j                  | j                  | j                  |      S )Nr  )compression_typec                 Z    t         j                  u r| S t        j                  |       S )N)r  )r
   r  r   string_to_number)r   	key_dtypes    r4   key_dtype_fnzYVocabularyFileCategoricalColumn._make_table_from_tfrecord_gzip_file.<locals>.key_dtype_fnB  s-    .S #J4O4O
	5# #r6   )r   
vocab_sizer   r  r.   )	r   r  r   data_lookup_opsindex_table_from_datasetmapr   r   r   )r-   r  r.   datasetr  s    `   r4   #_make_table_from_tfrecord_gzip_filezCVocabularyFileCategoricalColumn._make_table_from_tfrecord_gzip_file>  se    %%v7G# 33L!,,''(( r6   c           	         dj                  | j                        }||j                  | |      st        j                         5  | j
                  dk(  r| j                  ||      }nCt        j                  | j                  | j                  | j                  | j                  ||      }d d d        ||j                  | |       S |j                  | |      }|S # 1 sw Y   4xY w)N	{}_lookupr   )r   r   r  r   r  r.   )r   r   rB   r   
init_scoper
  r  r   index_table_from_filer   r   r   r   r@   rE   )r-   r  r   r.   tables        r4   _make_tablez+VocabularyFileCategoricalColumn._make_tableN  s    dhh'DM$>$>tT$J>> 
.::9dK%22"22"22-- ..!%	
 
	"""4u5 L ((t4eL!
 
s   A&CC&c                 2   | j                   j                  |j                   j                  k7  r:t        dj                  | j                  | j                   |j                               t        j                  |j                   dj                  | j                               | j                   }|j                   j                  r4t        j                  }t        j                  |t        j                        }| j                  ||      j                  |      S )*Creates a lookup table for the vocabulary.r  r  r   )r0   r   rb   r   r   r   r   r
   r  r   r  r  r  )r-   r}  r   r  s       r4   r  z7VocabularyFileCategoricalColumn._transform_input_tensorc  s    zz 2 2 = ==88>hh

L$6$6989 9
 !!-44TXX>@ 

I$$,,i]]<>lI}5<<\JJr6   c                 p    t        |j                  | j                  |            }| j                  ||      S )r  r  r  s       r4   ru  z1VocabularyFileCategoricalColumn.transform_featurev  3    :  =9;L''mDDr6   c                 l    t        |j                  | j                              }| j                  |      S rR   r  r  s      r4   r  z2VocabularyFileCategoricalColumn._transform_feature|  r  r6   c                 4    | j                   | j                  z   S r  )r   r   r<  s    r4   r   z+VocabularyFileCategoricalColumn.num_buckets  s     $"6"666r6   c                     | j                   S rR   r  r<  s    r4   r   z,VocabularyFileCategoricalColumn._num_buckets  r  r6   c                 N    t         j                  |j                  | |      d      S r  r  r@  s      r4   r]  z2VocabularyFileCategoricalColumn.get_sparse_tensors  r  r6   c                 P    ~~t         j                  |j                  |       d       S rR   r  r  s       r4   r	  z3VocabularyFileCategoricalColumn._get_sparse_tensors  r  r6   c                     | j                   gS r  r   r<  s    r4   r  z'VocabularyFileCategoricalColumn.parents  r  r6   c                 v    t        t        | j                  |             }| j                  j                  |d<   |S r  r  r  s     r4   r  z*VocabularyFileCategoricalColumn.get_config  r  r6   c                     t        || j                         t        |      }t        j                  |d         |d<    | di |S r  r  r  s        r4   r  z+VocabularyFileCategoricalColumn.from_config  r  r6   rR   r  )rG   rH   rI   rJ   r  r  rF  r.   r   r!   r  r  r  r  r  r  r  ru  r  r   r   r]  r	  r  r  r  r  r\  r]  s   @r4   r  r    s`    7 !$     = = ;:57#7 # *K&E ;:57676 7 7 ;:577 =
 ;:57 .2$(B7B    r6   r  r  c                   n   e Zd ZdZed        Zed        Zed        Ze ej                  e
e      d               ZddZd Z ej                  e
e      d	        Zed
        Ze ej                  e
e      d               Zd Z ej                  e
e      	 	 dd       Zed        Zd Zedd       Zy)r   z.See `categorical_column_with_vocabulary_list`.c                      yr  rK   r<  s    r4   rF  z-VocabularyListCategoricalColumn._is_v2_column  r  r6   c                     | j                   S r  r   r<  s    r4   r.   z$VocabularyListCategoricalColumn.name  r  r6   c                 X    | j                   t        j                  | j                        iS r  r  r<  s    r4   r   z2VocabularyListCategoricalColumn.parse_example_spec  r  r6   c                     | j                   S rR   r  r<  s    r4   r  z3VocabularyListCategoricalColumn._parse_example_spec  r  r6   Nc                    | j                   j                  |j                   j                  k7  r:t        dj                  | j                  | j                   |j                               t        j                  |j                   dj                  | j                               | j                   }|j                   j                  r4t        j                  }t        j                  |t        j                        }dj                  | j                        }||j                  | |      stt        j                         5  t        j                  t!        | j"                        | j$                  | j&                  ||      }ddd       |&|j)                  | |       n|j+                  | |      }j-                  |      S # 1 sw Y   BxY w)/Creates a lookup table for the vocabulary list.r  r  r   r  N)r  r   r   r0   r.   )r0   r   rb   r   r   r   r   r
   r  r   r  rB   r   r  r   index_table_from_tensorr   r  r   r   r@   rE   r  )r-   r}  r   r  r.   r  s         r4   r  z7VocabularyListCategoricalColumn._transform_input_tensor  so   zz 2 2 = ==88>hh

L$6$6989 9
 !!-44TXX>@ 

I$$,,i]]<>ldhh'DM$>$>tT$J>> 22!$"6"67,, 00 
	"""4u5 ((t4e<<%% s   ;AF>>Gc                 p    t        |j                  | j                  |            }| j                  ||      S )r  r  r  s       r4   ru  z1VocabularyListCategoricalColumn.transform_feature  r  r6   c                 l    t        |j                  | j                              }| j                  |      S rR   r  r  s      r4   r  z2VocabularyListCategoricalColumn._transform_feature  r  r6   c                 F    t        | j                        | j                  z   S r  )r   r  r   r<  s    r4   r   z+VocabularyListCategoricalColumn.num_buckets  s      t##$t';';;;r6   c                     | j                   S rR   r  r<  s    r4   r   z,VocabularyListCategoricalColumn._num_buckets  r  r6   c                 N    t         j                  |j                  | |      d      S r  r  r@  s      r4   r]  z2VocabularyListCategoricalColumn.get_sparse_tensors  r  r6   c                 P    ~~t         j                  |j                  |       d       S rR   r  r  s       r4   r	  z3VocabularyListCategoricalColumn._get_sparse_tensors  r  r6   c                     | j                   gS r  r   r<  s    r4   r  z'VocabularyListCategoricalColumn.parents  r  r6   c                 v    t        t        | j                  |             }| j                  j                  |d<   |S r  r  r  s     r4   r  z*VocabularyListCategoricalColumn.get_config  r  r6   c                     t        || j                         t        |      }t        j                  |d         |d<    | di |S r  r  r  s        r4   r  z+VocabularyListCategoricalColumn.from_config!  r  r6   rR   r  r  rK   r6   r4   r   r     sI    7    = = ;:57#7 # &DE ;:57676 < < ;:577 =
 ;:57 .2$(B7B    r6   r   r  c                   l   e Zd ZdZed        Zed        Zed        Ze ej                  e
e      d               Zd Zd Z ej                  e
e      d        Zed	        Ze ej                  e
e      d
               Zd Z ej                  e
e      	 	 dd       Zed        Zd Zedd       Zy)r&  z'See `categorical_column_with_identity`.c                      yr  rK   r<  s    r4   rF  z'IdentityCategoricalColumn._is_v2_column2  r  r6   c                     | j                   S r  r   r<  s    r4   r.   zIdentityCategoricalColumn.name6  r  r6   c                 `    | j                   t        j                  t        j                        iS r  )r   r   r  r
   r  r<  s    r4   r   z,IdentityCategoricalColumn.parse_example_spec;  s"     HHk//=>>r6   c                     | j                   S rR   r  r<  s    r4   r  z-IdentityCategoricalColumn._parse_example_spec@  r  r6   c           
         |j                   j                  s/t        dj                  | j                  |j                               |j
                  }|j
                  j                   t        j                  k7  r&t        j                  |t        j                  d      }| j                  t        j                  |j
                  t        j                  d      }t        j                  | j                  t        j                  d      }t        j                  dt        j                  d      }t        j                  t        j                  ||k  ||k\  d      t        j                  t        j                   |      t        j                  | j                  t        j                        d	      |      }t#        j$                  |j&                  ||j(                  
      S ),Returns a SparseTensor with identity values.z-Invalid input, not integer. key: {} dtype: {}rx   r   r   r   zeroout_of_rangedefault_values)dimsr   r.   r  )r0   r   rb   r   r   rx   r
   r  r   r  r   r   r   r  
logical_orfillr/   rz  r{  r  r  )r-   r}  rx   r   r  s        r4   r  z1IdentityCategoricalColumn._transform_input_tensorF  sb   ((FMM
((L&&( ) )  F  FLL0}}VV\\Af%}}\00&,,XNfMM


FLL}>k]]1fll8d!!


tmV{2I
..??6*MM$"4"4fllC#% '-.f ))$$ ,,. .r6   c                 n    t        |j                  | j                  |            }| j                  |      S )r  r  r  s       r4   ru  z+IdentityCategoricalColumn.transform_featurea  r  r6   c                 l    t        |j                  | j                              }| j                  |      S rR   r  r  s      r4   r  z,IdentityCategoricalColumn._transform_featureg  r  r6   c                     | j                   S r  )r%  r<  s    r4   r   z%IdentityCategoricalColumn.num_bucketsm  s     r6   c                     | j                   S rR   r  r<  s    r4   r   z&IdentityCategoricalColumn._num_bucketsr  r  r6   c                 N    t         j                  |j                  | |      d      S r  r  r@  s      r4   r]  z,IdentityCategoricalColumn.get_sparse_tensorsx  r  r6   Nc                 P    ~~t         j                  |j                  |       d       S rR   r  r  s       r4   r	  z-IdentityCategoricalColumn._get_sparse_tensors}  r  r6   c                     | j                   gS r  r   r<  s    r4   r  z!IdentityCategoricalColumn.parents  r  r6   c                 @    t        t        | j                  |             S r  )r  r  r  r<  s    r4   r  z$IdentityCategoricalColumn.get_config  s    DLL$'((r6   c                 T    t        || j                         t        |      } | di |S )r  rK   )r  r  r  r  s        r4   r  z%IdentityCategoricalColumn.from_config  s(     vs{{+)&1F==r6   r  r  rK   r6   r4   r&  r&  *  sG    0    ? ? ;:57#7 #.66 ;:57676   ;:577 =
 ;:57 .2$(B7B  )  r6   r&  r$  c                   l   e Zd ZdZed        Zed        Zed        Ze ej                  e
e      d               Zed        Ze ej                  e
e      d               Zd Zd	 Z ej                  e
e      d
        Zd Z ej                  e
e      	 	 dd       Zed        Zd Zedd       Zy)r   z"See `weighted_categorical_column`.c                 z    t        | j                  t        j                        xr | j                  j                  S rR   r  r<  s    r4   rF  z'WeightedCategoricalColumn._is_v2_column  r  r6   c                 b    dj                  | j                  j                  | j                        S )r  z{}_weighted_by_{})r   r   r.   r.  r<  s    r4   r.   zWeightedCategoricalColumn.name  s.     %%d&=&=&B&B&*&=&=? ?r6   c                 
   | j                   j                  }| j                  |v r2t        dj	                  || j                     | j                              t        j                  | j                        || j                  <   |S )r  &Parse config {} already exists for {}.)r   r   r.  rb   r   r   r  r0   r  s     r4   r   z,WeightedCategoricalColumn.parse_example_spec  s{     $$77F&(?FF
((
)4+B+BD E E&1&?&?

&KF4""#Mr6   c                 
   | j                   j                  }| j                  |v r2t        dj	                  || j                     | j                              t        j                  | j                        || j                  <   |S )Nr  )r   r  r.  rb   r   r   r  r0   r  s     r4   r  z-WeightedCategoricalColumn._parse_example_spec  s{     $$88F&(?FF
((
)4+B+BD E E&1&?&?

&KF4""#Mr6   c                 .    | j                   j                  S r  r   r   r<  s    r4   r   z%WeightedCategoricalColumn.num_buckets       ""...r6   c                 .    | j                   j                  S rR   r   r   r<  s    r4   r   z&WeightedCategoricalColumn._num_buckets       ""///r6   c                    |$t        dj                  | j                              t        j                  |      }| j
                  |j
                  j                  k7  r/t        dj                  | j
                  |j
                              t        |t        j                        st        |d      }|j
                  j                  s$t        j                  |t        j                        }|S )NzMissing weights {}.z#Bad dtype, expected {}, but got {}.r   )r  )rb   r   r.  rz  r  r0   
base_dtyperf   r{  r  r   r   r  r
   r  )r-   rX  s     r4   _transform_weight_tensorz2WeightedCategoricalColumn._transform_weight_tensor  s    ,33D4K4KLMM%HHMzz]((333<CC
**m))+ , ,m%6%C%CD=
c+m**mmM6>>Bmr6   c                     |j                  | j                  |      }| j                  |      }t        |j                  | j                  |            }||fS z?Applies weights to tensor generated from `categorical_column`'.)r~   r.  r  r  r   )r-   r   r   rX  sparse_weight_tensorsparse_categorical_tensors         r4   ru  z+WeightedCategoricalColumn.transform_feature  s\    (,,T-D-D-:<M88G G  !8!8-H!J%';<<r6   c                     |j                  | j                        }| j                  |      }|j                  | j                        |fS r  )r~   r.  r  r   )r-   r  rX  s      r4   r  z,WeightedCategoricalColumn._transform_feature  sB     JJt667M11-@MJJt../??r6   c                 ^    |j                  | |      }t        j                  |d   |d         S )r  r   r   r~   r   rV  )r-   r   r   tensorss       r4   r]  z,WeightedCategoricalColumn.get_sparse_tensors  s/    "&&t];G))'!*gajAAr6   Nc                 `    ~~|j                  |       }t        j                  |d   |d         S )Nr   r   r  )r-   r  r  r1   r  s        r4   r	  z-WeightedCategoricalColumn._get_sparse_tensors  s3     	jjG))'!*gajAAr6   c                 2    | j                   | j                  gS r  )r   r.  r<  s    r4   r  z!WeightedCategoricalColumn.parents  s     ##T%<%<==r6   c                     ddl m} t        t        | j                  |             } || j
                        |d<   | j                  j                  |d<   |S )r  r   r  r   r0   )r  r  r  r  r  r   r0   r.   r  s      r4   r  z$WeightedCategoricalColumn.get_config  sI    W#dllD)*F#;$!F jjooF7OMr6   c                     ddl m} t        || j                         t	        |      } ||d   ||      |d<   t        j                  |d         |d<    | di |S )r  r   r  r   r0   rK   )r  r  r  r  r  r
   r  r  s         r4   r  z%WeightedCategoricalColumn.from_config  s`     Zvs{{+)&1F#=#$no$GF oofWo6F7O==r6   r  )rG   rH   rI   rJ   r  rF  r.   r   r!   r  r  r  r  r   r   r  ru  r  r]  r	  r  r  r  r  rK   r6   r4   r   r     sJ    +  ? ?
   ;:577  / / ;:5707 0 = ;:57@7@B
 ;:57 .2$(B7B > >  r6   r   r-  c                   f   e Zd ZdZed        Zed        Zed        Ze ej                  e
e      d               Zd Z ej                  e
e      d        Zed        Ze ej                  e
e      d	               Zd
 Z ej                  e
e      	 	 dd       Zed        Zd Zedd       Zy)r7  zSee `crossed_column`.c                     t        |       D ]G  }t        |t        j                        rt        |t        j
                        s y|j                  rG y y)NFT)_collect_leaf_level_keysrf   r   r5  r   r   rF  )r-   r   s     r4   rF  zCrossedColumn._is_v2_column!  sM    '- 	C))	*X334 r6   c                    g }t        |       D ]Y  }t        |t        j                  t        j
                  f      r|j                  |j                         I|j                  |       [ dj                  t        |            S )r  _X_)
r  rf   r   r   r   _FeatureColumnr   r.   r   r   )r-   feature_namesr   s      r4   r.   zCrossedColumn.name,  sn     M'- "	C(00&2G2GH	ISXX&S!	"
 ::f]+,,r6   c                 l   i }| j                   D ]  }t        |t        j                        r|j	                  |j
                         9t        |t        j                        r|j	                  |j                         o|j	                  |t        j                  t        j                        i        |S r  )r3  rf   r   r   r   r   r   r   r  r   r  r
   r  )r-   r   r   s      r4   r   z CrossedColumn.parse_example_spec7  s     Fyy G	C//	0c,,-c6001c--.sK55fmmDEFG Mr6   c                     | j                   S rR   r  r<  s    r4   r  z!CrossedColumn._parse_example_specD  r  r6   c                 $   g }t        |       D ]  }t        |t        j                        r"|j	                  |j                  ||             ?t        |t        j                  t        f      r^|j                  ||      }|j                  $t        dj                  |j                              |j	                  |j                         t        dj                  |             t        j                   || j"                  | j$                        S z7Generates a hashed sparse cross from the input tensors.zmcrossed_column does not support weight_tensor, but the given column populates weight_tensor. Given column: {}z"Unsupported column type. Given: {})r  r   r4  )r  rf   r   r5  r   r~   r   r   r   r]  rX  rb   r   r.   rW  r   sparse_cross_hashedr   r4  )r-   r   r   feature_tensorsr   ids_and_weightss         r4   ru  zCrossedColumn.transform_featureJ  s    O'- K	C))	*377]KLcF557HIJ001E1>@((4!!'!13 3 	889=DDSIJJK ))))   r6   c                     g }t        |       D ]  }t        |t        j                        r!|j	                  |j                  |             >t        |t        t        j                  f      r]|j                  |      }|j                  $t        dj                  |j                              |j	                  |j                         t        dj                  |             t        j                   || j"                  | j$                        S r%  )r  rf   r   r5  r   r~   r   r   r   r	  rX  rb   r   r.   rW  r   r&  r   r4  )r-   r  r'  r   r(  s        r4   r  z CrossedColumn._transform_feature`  s     O'- K	C))	*vzz#/c-v/H/HIJ11&9((4!!'!13 3 	889=DDSIJJK ))))   r6   c                     | j                   S r  r  r<  s    r4   r   zCrossedColumn.num_bucketsw  r  r6   c                     | j                   S rR   r  r<  s    r4   r   zCrossedColumn._num_buckets|  r  r6   c                 N    t         j                  |j                  | |      d      S r  r  r@  s      r4   r]  z CrossedColumn.get_sparse_tensors  r  r6   Nc                 P    ~~t         j                  |j                  |       d      S r  r  r  s       r4   r	  z!CrossedColumn._get_sparse_tensors  s&     	))&**T*:DAAr6   c                 ,    t        | j                        S r  )r   r3  r<  s    r4   r  zCrossedColumn.parents  s     		?r6   c                     ddl m} t        t        | j                  |             }t        | j                  D cg c]
  } ||       c}      |d<   |S c c}w )r  r   r  r3  )r  r  r  r  r  r   r3  )r-   r  r   fcs       r4   r  zCrossedColumn.get_config  sH    W#dllD)*F499MR4R8MNF6NM Ns   Ac           
          ddl m} t        || j                         t	        |      }t        |d   D cg c]  } ||||       c}      |d<    | di |S c c}w )r  r   r  r3  rK   )r  r  r  r  r  r   )r  r   r  r  r  r  r   s          r4   r  zCrossedColumn.from_config  sd     Zvs{{+)&1F 	#1noF F6N ==	s   Ar  )rG   rH   rI   rJ   r  rF  r.   r   r!   r  r  r  r  ru  r  r   r   r]  r	  r  r  r  r  rK   r6   r4   r7  r7    sB      - - 
 
 ;:57#7 # , ;:57 7 * ! ! ;:577 =
 ;:57 .2$(B7B   	 	r6   r7  r2  c                     g }| j                   D ]>  }t        |t              r|j                  t	        |             .|j                  |       @ |S )zCollects base keys by expanding all nested crosses.

  Args:
    cross: A `CrossedColumn`.

  Returns:
    A list of strings or `CategoricalColumn` instances.
  )r3  rf   r7  extendr  r   )crossleaf_level_keysks      r4   r  r    sP     /::  a!]#5a89Q	 
 
r6   c                 0   t        j                  | j                  d      }|Ct        j                  |t	        j
                  |j                  t        j                              }t        j                  | |      } |t        j                  ||      }| |fS )z7Prune invalid IDs (< 0) from the input ids and weights.r   )r0   )
r   greater_equalrx   logical_andr   	ones_liker
   boolr   sparse_retain)r;  r`  is_id_valids      r4   _prune_invalid_idsr>    s    &&z'8'8!<+&&N11EGK ''
K@*--nkJN	^	##r6   c                     |Lt        j                  |j                  d      }t        j                  | |      } t        j                  ||      }| |fS )z;Prune invalid weights (< 0) from the input ids and weights.r   )r   greaterrx   r   r<  )r;  r`  is_weights_valids      r4   _prune_invalid_weightsrB    sR    ''(=(=qA))*6FGJ--n>NON	^	##r6   c                      e Zd ZdZed        Zed        Zd Zd Z e	j                  ee      d        Zed        Ze e	j                  ee      d               Zed	        Ze e	j                  ee      d
               Zd Z e	j                  ee      dd       Zd Z e	j                  ee      	 	 dd       Zed        Zd Zedd       Zy)r)  zRepresents a one-hot column for use in deep networks.

  Args:
    categorical_column: A `CategoricalColumn` which is created by
      `categorical_column_with_*` function.
  c                 z    t        | j                  t        j                        xr | j                  j                  S rR   r  r<  s    r4   rF  zIndicatorColumn._is_v2_column  r  r6   c                 L    dj                  | j                  j                        S )r  z{}_indicatorr  r<  s    r4   r.   zIndicatorColumn.name  r   r6   c                    |j                   }|j                  }|yt        j                  ||t	        |            }t        j
                  |ddg|j                        }t        j                  |j                  |j                  |j                        S t        j                  |d      }t        j                  ||dd      }t        j                  |dg	      S )
N)sp_ids	sp_valuesr  r   r	  )r   r   r   )r  r  r  )axis)rW  rX  r   sparse_merger  sparse_slicer  r   
scatter_ndr  rx   sparse_tensor_to_denser  r   
reduce_sum)r-   id_weight_pairsizerW  rX  weighted_columndense_id_tensorone_hot_id_tensors           r4   _transform_id_weight_pairz)IndicatorColumn._transform_id_weight_pair  s    ((I"00M  "//mD	Ko #//!Q0?0K0KMo !!/"9"9"1"8"8"1"="=? ? !77%O
 "))tcSB 0t<<r6   c                 x    | j                   j                  ||      }| j                  || j                  d         S )a  Returns dense `Tensor` representing feature.

    Args:
      transformation_cache: A `FeatureTransformationCache` object to access
        features.
      state_manager: A `StateManager` to create / access resources such as
        lookup tables.

    Returns:
      Transformed feature `Tensor`.

    Raises:
      ValueError: if input rank is not known at graph building time.
    r	  )r   r]  rU  r=  )r-   r   r   rP  s       r4   ru  z!IndicatorColumn.transform_feature	  sD     ,,??m-N)).*.*=*=b*AC Cr6   c                 v    | j                   j                  |      }| j                  || j                  d         S )Nr	  )r   r	  rU  r  )r-   r  rP  s      r4   r  z"IndicatorColumn._transform_feature  s?     ,,@@HN)).*.*>*>r*BD Dr6   c                 .    | j                   j                  S r  r"  r<  s    r4   r   z"IndicatorColumn.parse_example_spec$  r#  r6   c                 .    | j                   j                  S rR   r%  r<  s    r4   r  z#IndicatorColumn._parse_example_spec)  r&  r6   c                     t        | j                  t        j                        r+t	        j
                  d| j                  j                  g      S t	        j
                  d| j                  j                  g      S )zEReturns a `TensorShape` representing the shape of the dense `Tensor`.r   )rf   r   r   r   r   r  r   r   r<  s    r4   r=  zIndicatorColumn.variable_shape/  s^     $))8+A+AB%%q$*A*A*M*M&NOO%%q$*A*A*N*N&OPPr6   c                 X    t        j                  d| j                  j                  g      S r  )r   r  r   r   r<  s    r4   r  zIndicatorColumn._variable_shape7  s&     ##Q(?(?(L(L$MNNr6   c                     t        | j                  t              rCt        dj	                  | j
                  t        | j                        | j                              |j                  | |      S )a  Returns dense `Tensor` representing feature.

    Args:
      transformation_cache: A `FeatureTransformationCache` object to access
        features.
      state_manager: A `StateManager` to create / access resources such as
        lookup tables.

    Returns:
      Dense `Tensor` created within `transform_feature`.

    Raises:
      ValueError: If `categorical_column` is a `SequenceCategoricalColumn`.
    a5  In indicator_column: {}. categorical_column must not be of type SequenceCategoricalColumn. Suggested fix A: If you wish to use DenseFeatures, use a non-sequence categorical_column_with_*. Suggested fix B: If you wish to create sequence input, use SequenceFeatures instead of DenseFeatures. Given (type {}): {})rf   r   r   rb   r   r.   r   r~   r@  s      r4   rA  z IndicatorColumn.get_dense_tensor=  sg     $))+DE  !'tyy$t7N7N2O'+'>'>!@A A  ##D-88r6   Nc                    ~~t        | j                  t        t        j                  f      rCt        dj                  | j                  t        | j                        | j                              |j                  |       S )Na6  In indicator_column: {}. categorical_column must not be of type _SequenceCategoricalColumn. Suggested fix A: If you wish to use DenseFeatures, use a non-sequence categorical_column_with_*. Suggested fix B: If you wish to create sequence input, use SequenceFeatures instead of DenseFeatures. Given (type {}): {})
rf   r   r   r   r   rb   r   r.   r   r~   r  s       r4   r  z!IndicatorColumn._get_dense_tensorZ  sz     		"F$E$EFH   !'tyy$t7N7N2O'+'>'>!@A A ::dr6   c                    t        | j                  t              sCt        dj	                  | j
                  t        | j                        | j                              |j                  | |      }| j                  j                  ||      }t        j                  |j                        }t        j                  ||      S )rN  zIn indicator_column: {}. categorical_column must be of type SequenceCategoricalColumn to use SequenceFeatures. Suggested fix: Use one of sequence_categorical_column_with_*. Given (type {}): {}rg  )rf   r   r   rb   r   r.   r   r~   r]  r   rP  rW  re  rf  r  s         r4   rk  z)IndicatorColumn.get_sequence_dense_tensoro  s    d--/HI  !'tyy$t7N7N2O'+'>'>!@A A (++D-@L,,??m-NAA  "O77!? 8 D Dr6   c                    ~~t        | j                  t        t        j                  f      sCt        dj                  | j                  t        | j                        | j                              |j                  |       }| j                  j                  |      }t        j                  |j                        }t        j                  ||      S )NzIn indicator_column: {}. categorical_column must be of type _SequenceCategoricalColumn to use SequenceFeatures. Suggested fix: Use one of sequence_categorical_column_with_*. Given (type {}): {}rg  )rf   r   r   r   r   rb   r   r.   r   r~   r	  r   rP  rW  re  rf  )r-   r  r  r1   rh  rc  ri  s          r4   rR  z*IndicatorColumn._get_sequence_dense_tensor  s     		"F$E$EFH   !'tyy$t7N7N2O'+'>'>!@A A ::d#L,,@@HNAA  "O77!? 8 D Dr6   c                     | j                   gS r  r*  r<  s    r4   r  zIndicatorColumn.parents  rT  r6   c                 z    ddl m} t        t        | j                  |             } || j
                        |d<   |S r  r   r  r   r  r  r  r  r  r   r  s      r4   r  zIndicatorColumn.get_config  8    W#dllD)*F#;$!F Mr6   c                     ddl m} t        || j                         t	        |      } ||d   ||      |d<    | di |S r  r   r  r   rK   r  r  s         r4   r  zIndicatorColumn.from_config  J     Zvs{{+)&1F#=#$no$GF ==r6   r  )rG   rH   rI   rJ   r  rF  r.   rU  ru  r!   r  r  r  r  r   r  r=  r  rA  r  rk  rR  r  r  r  r  rK   r6   r4   r)  r)    s}      ? ?=8C( ;:57D7D
 6 6 ;:5777 7 Q Q ;:57O7 O9: ;:577&D( ;:57 59+/D7D6 % %  r6   r)  r   c           	      d   d}t        dt        |             D ]  }t        j                  t        j                  | |   j
                  d               }|j                  H||}|}O|j                  |      rat        dj                  |   j                  ||   j                  ||             y)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 ({}, {}): ({}, {}))r   r   r   	Dimensionr9  r/   r   is_compatible_withrb   r   r.   )r  columnsexpected_batch_sizer   rT  bath_size_column_indexs         r4   "_verify_static_batch_size_equalityrn    s     CL! 2a''$$WQZ%5%5a%89;J#		$!"("55jA77=v./44gajoo#Z812 	22r6   c                   l   e Zd ZdZed        Zed        Zed        Ze ej                  e
e      d               Zd Z ej                  e
e      d        Zed        Ze ej                  e
e      d	               Zd
 Zd Z ej                  e
e      	 	 dd       Zed        Zd Zedd       Zy)r   z)Represents sequences of categorical data.c                 z    t        | j                  t        j                        xr | j                  j                  S rR   r  r<  s    r4   rF  z'SequenceCategoricalColumn._is_v2_column  r  r6   c                 .    | j                   j                  S r  )r   r.   r<  s    r4   r.   zSequenceCategoricalColumn.name  s     ""'''r6   c                 .    | j                   j                  S r  r"  r<  s    r4   r   z,SequenceCategoricalColumn.parse_example_spec  r#  r6   c                 .    | j                   j                  S rR   r%  r<  s    r4   r  z-SequenceCategoricalColumn._parse_example_spec  r&  r6   c                 :    | j                   j                  ||      S r  )r   ru  r@  s      r4   ru  z+SequenceCategoricalColumn.transform_feature  s#    ""445I5BD Dr6   c                 8    | j                   j                  |      S rR   )r   r  r+  s     r4   r  z,SequenceCategoricalColumn._transform_feature  s     ""55f==r6   c                 .    | j                   j                  S r  r  r<  s    r4   r   z%SequenceCategoricalColumn.num_buckets  r  r6   c                 .    | j                   j                  S rR   r
  r<  s    r4   r   z&SequenceCategoricalColumn._num_buckets  r  r6   c                 &   |j                   }|j                  }t        j                  |      }|d   |d   t	        j
                  |dd        g}t        j                  ||      }|t        j                  ||      }t        j                  ||      S )Nr   r   r1  )
rW  rX  r   r/   r   reduce_prodr   ra  r   rV  )r-   rc  rW  rX  r/   target_shapes         r4   _get_sparse_tensors_helperz4SequenceCategoricalColumn._get_sparse_tensors_helper  s    ((I"00M OOI&E !HeAh(<(<U12Y(GHL)))\BI  //|Lm)))]CCr6   c                 \    | j                   j                  ||      }| j                  |      S )r\  )r   r]  r{  rI  s       r4   r]  z,SequenceCategoricalColumn.get_sparse_tensors  s0    & ,,??m-N**>::r6   Nc                 Z    | j                   j                  |      }| j                  |      S rR   )r   r	  r{  rK  s        r4   r	  z-SequenceCategoricalColumn._get_sparse_tensors.  s+     ,,@@HN**>::r6   c                     | j                   gS r  r*  r<  s    r4   r  z!SequenceCategoricalColumn.parents7  rT  r6   c                 z    ddl m} t        t        | j                  |             } || j
                        |d<   |S rb  rc  r  s      r4   r  z$SequenceCategoricalColumn.get_config<  rd  r6   c                     ddl m} t        || j                         t	        |      } ||d   ||      |d<    | di |S rf  r  r  s         r4   r  z%SequenceCategoricalColumn.from_configD  rg  r6   r  )rG   rH   rI   rJ   r  rF  r.   r   r!   r  r  r  r  ru  r  r   r   r{  r]  r	  r  r  r  r  rK   r6   r4   r   r     sG    2  ( ( 6 6 ;:5777 7D
 ;:57>7> / / ;:5707 0D ;. ;:57 .2$(;7; % %  r6   r   c                     t        | j                               t        |      k7  rt        dj                  | |            y)z+Checks that a config has all expected_keys.z%Invalid config: {}, expected keys: {}N)r  r3  rb   r   )r   expected_keyss     r4   r  r  O  s?    3}--
<CC     .r6   c                     | j                         }|j                         D ]$  \  }}t        |t              st	        |      ||<   & |S )a  Returns a shallow copy of config with lists turned to tuples.

  Keras serialization uses nest to listify everything.
  This causes problems with the NumericColumn shape, which becomes
  unhashable. We could try to solve this on the Keras side, but that
  would require lots of tracking to avoid changing existing behavior.
  Instead, we ensure here that we revive correctly.

  Args:
    config: dict that will be used to revive a Feature Column

  Returns:
    Shallow copy of config with lists turned to tuples.
  )rn  itemsrf   r   r   )r   r  r6  rm   s       r4   r  r  V  sF     ;;=&lln da!T(fQi 
-r6   c                 P    t        j                  d      }|j                  d|       S )zASanitizes user-provided feature names for use as variable scopes.z[^A-Za-z0-9_.\-]r   )recompilesub)r.   invalid_chars     r4   r}   r}   m  s$    /0,			#t	$$r6   )r   NNNNTT)r   NNNNNTT)Nr	  r   rR   )rJ   rB  rY   r   r  r  r  r   'tensorflow.python.data.experimental.opsr   r  tensorflow.python.data.opsr   tensorflow.python.eagerr    tensorflow.python.feature_columnr   r   r   r   r   r	   r   tensorflow.python.frameworkr
   r   r   rz  r   r  r   tensorflow.python.opsr   r   r   r   r   r   r   r   r   r   r   r   tensorflow.python.platformr   r   r  tensorflow.python.trackabler   r   rc   r   tensorflow.python.trainingr    tensorflow.python.utilr!   r"   r#   tensorflow.python.util.compatr$    tensorflow.python.util.tf_exportr%   tensorflow.tools.docsr&   r  r  #_FEATURE_COLUMN_DEPRECATION_WARNING+_FEATURE_COLUMN_DEPRECATION_RUNTIME_WARNINGobjectr(   rN   r   headerr  r   r   r   r   r  r   r   r  r   r   r   r"  r'  r+  r/  r8  r   r:  rG  rN  rM  r   rL  register_feature_columnre  r|   r  rz   _DenseColumnr^  r   r   r   _SequenceDenseColumnr   r_  AutoTrackabler   rj  r   r   r  r   r&  r   r7  r  r>  rB  r)  rn  r   r   r  r  r}   rK   r6   r4   <module>r     sR
  
    	  
 Q . + E P : > . + J < 4 + 1 + & / * , * - , , 0 + , < 5 9 7 7 . ' - 9 6 .#'   / ' ## ,];6 ];@ 5"=CF CF >CFL,^ 89
,	 IJ9 K :
9x 89
,-IJ %!%'+)-"#/3M; K . :M;` 89
89:IJ '-)->B/315&*'+7;W K ; :Wt 89
&	 IJ *0,0AE2648)-*.:>F K :
FR 89
*+IJ!%!%	^# K , :^#B 89
-.IJQ< K / :Q<h 89
?@IJ /5mmB? K A :B?J 89
GHIIJ =A<=:>28--fE K J :fER 89
<	 IJ @D5;]]=A?@;?B K :
BJ 89
CDIJ 37:<<=	q' K E :q'h 89
<=IJHH K > :HHV 89
,-IJ'- K . :'-T 89
78IJ '-nnH K 9 :HV 89
*+
|N , :|N@ 4<"	((( "	 ="	J$B#	.. #	L.d <D&&	(00 	 ' E	& CKRG RG LRGl,F^*7Z &&{
KCE{ '{| &&Y

K-:<Y 'Yx &&L

K	&'L 'L^@2=#>#> 2j &&F%

K	23F% 'F%R  &&l
K4?Al 'l^ &&^
K)	23^ '^B &&v
K)OQv 'vr &&j
K6EGj 'jZ &&}
K#=?} '}@ &&N
K?CEN 'Nb$
$$ &&a

K,/CEa 'aH26 &&x
%%K603x 'xv .%r6   