o
    ?e0                     @   s   d 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 ZedgdG dd dejZeeedddZdS )z#The Categorical distribution class.    )constant_op)dtypes)ops)tensor_shape)	array_ops)math_ops)nn_ops)
random_ops)distribution)kullback_leibler)util)deprecation)	tf_exportc                 C   s   | j jrn| j jrtj| tjd} ntd||j	j
duo,|j	dd  o,| j	 }|r9|j	dd | j	krn|tj| dtjf |j d9 }t	|dd }| tj|| j d9 } |j	j
durn| t|j	dd  | |fS )z0Broadcasts the event or distribution parameters.dtypez8`value` should have integer `dtype` or `self.dtype` ({})N.)r   
is_integerZis_floatingr   castr   int32	TypeErrorformatshapendimsis_fully_definedr   Z	ones_likeZnewaxisZones	set_shaper   TensorShape)eventparams
base_dtypeZshape_known_staticallyZparams_shape r   p/home/www/facesmatcher.com/pyenv/lib/python3.10/site-packages/tensorflow/python/ops/distributions/categorical.py_broadcast_cat_event_and_params    s*   r!   zdistributions.Categorical)v1c                       s   e Zd ZdZejddddddejddd f fdd		Ze	d
d Z
e	dd Ze	dd Zdd Zdd Zdd Zdd Zd"ddZdd Zdd Zdd Zd d! Z  ZS )#Categoricalas	  Categorical distribution.

  The Categorical distribution is parameterized by either probabilities or
  log-probabilities of a set of `K` classes. It is defined over the integers
  `{0, 1, ..., K}`.

  The Categorical distribution is closely related to the `OneHotCategorical` and
  `Multinomial` distributions.  The Categorical distribution can be intuited as
  generating samples according to `argmax{ OneHotCategorical(probs) }` itself
  being identical to `argmax{ Multinomial(probs, total_count=1) }`.

  #### Mathematical Details

  The probability mass function (pmf) is,

  ```none
  pmf(k; pi) = prod_j pi_j**[k == j]
  ```

  #### Pitfalls

  The number of classes, `K`, must not exceed:
  - the largest integer representable by `self.dtype`, i.e.,
    `2**(mantissa_bits+1)` (IEEE 754),
  - the maximum `Tensor` index, i.e., `2**31-1`.

  In other words,

  ```python
  K <= min(2**31-1, {
    tf.float16: 2**11,
    tf.float32: 2**24,
    tf.float64: 2**53 }[param.dtype])
  ```

  Note: This condition is validated only when `self.validate_args = True`.

  #### Examples

  Creates a 3-class distribution with the 2nd class being most likely.

  ```python
  dist = Categorical(probs=[0.1, 0.5, 0.4])
  n = 1e4
  empirical_prob = tf.cast(
      tf.histogram_fixed_width(
        dist.sample(int(n)),
        [0., 2],
        nbins=3),
      dtype=tf.float32) / n
  # ==> array([ 0.1005,  0.5037,  0.3958], dtype=float32)
  ```

  Creates a 3-class distribution with the 2nd class being most likely.
  Parameterized by [logits](https://en.wikipedia.org/wiki/Logit) rather than
  probabilities.

  ```python
  dist = Categorical(logits=np.log([0.1, 0.5, 0.4])
  n = 1e4
  empirical_prob = tf.cast(
      tf.histogram_fixed_width(
        dist.sample(int(n)),
        [0., 2],
        nbins=3),
      dtype=tf.float32) / n
  # ==> array([0.1045,  0.5047, 0.3908], dtype=float32)
  ```

  Creates a 3-class distribution with the 3rd class being most likely.
  The distribution functions can be evaluated on counts.

  ```python
  # counts is a scalar.
  p = [0.1, 0.4, 0.5]
  dist = Categorical(probs=p)
  dist.prob(0)  # Shape []

  # p will be broadcast to [[0.1, 0.4, 0.5], [0.1, 0.4, 0.5]] to match counts.
  counts = [1, 0]
  dist.prob(counts)  # Shape [2]

  # p will be broadcast to shape [3, 5, 7, 3] to match counts.
  counts = [[...]] # Shape [5, 7, 3]
  dist.prob(counts)  # Shape [5, 7, 3]
  ```

  z
2019-01-01zThe TensorFlow Distributions library has moved to TensorFlow Probability (https://github.com/tensorflow/probability). You should update all references to use `tfp.distributions` instead of `tf.distributions`.T)Z	warn_onceNFc           
   	      s  t t }tj|||gd}tj|||d|d\| _| _|r&t| j| _| j	 
d}|jdurAtj|jd tjdd| _ntjdd t| jd | _W d   n1 s[w   Y  tj| jd	d}	t|d
 durtj|jd
 jtjdd| _ntjdd |	| j | _W d   n1 sw   Y  |dd
  rtj|dd
  tjdd| _ntjdd |	dd
 | _W d   n1 sw   Y  W d   n1 sw   Y  tt| j|t j!|||| j| jg|d dS )a  Initialize Categorical distributions using class log-probabilities.

    Args:
      logits: An N-D `Tensor`, `N >= 1`, representing the log probabilities
        of a set of Categorical distributions. The first `N - 1` dimensions
        index into a batch of independent distributions and the last dimension
        represents a vector of logits for each class. Only one of `logits` or
        `probs` should be passed in.
      probs: An N-D `Tensor`, `N >= 1`, representing the probabilities
        of a set of Categorical distributions. The first `N - 1` dimensions
        index into a batch of independent distributions and the last dimension
        represents a vector of probabilities for each class. Only one of
        `logits` or `probs` should be passed in.
      dtype: The type of the event samples (default: int32).
      validate_args: Python `bool`, default `False`. When `True` distribution
        parameters are checked for validity despite possibly degrading runtime
        performance. When `False` invalid inputs may silently render incorrect
        outputs.
      allow_nan_stats: Python `bool`, default `True`. When `True`, statistics
        (e.g., mean, mode, variance) use the value "`NaN`" to indicate the
        result is undefined. When `False`, an exception is raised if one or
        more of the statistic's batch members are undefined.
      name: Python `str` name prefixed to Ops created by this class.
    valuesT)logitsprobsvalidate_argsZmultidimensionalname   NZ
batch_rank)r   r)   r)   logits_shaper   
event_sizebatch_shape)r   Zreparameterization_typer(   allow_nan_stats
parametersZgraph_parentsr)   )"dictlocalsr   
name_scopedistribution_utilZget_logits_and_probs_logits_probsZ#embed_check_categorical_event_shape	get_shapeZwith_rank_at_leastr   convert_to_tensorr   r   _batch_rankr   Zrankr   r   Zdimension_valuedimsvalue_event_sizer   r   constantas_list_batch_shape_valsuperr#   __init__r
   ZNOT_REPARAMETERIZED)
selfr&   r'   r   r(   r/   r)   r0   Zlogits_shape_staticr,   	__class__r   r    rA      sn   
(





(
zCategorical.__init__c                 C      | j S )z-Scalar `int32` tensor: the number of classes.)r<   rB   r   r   r    r-         zCategorical.event_sizec                 C   rE   )z Vector of coordinatewise logits.)r5   rF   r   r   r    r&      rG   zCategorical.logitsc                 C   rE   )z'Vector of coordinatewise probabilities.)r6   rF   r   r   r    r'      rG   zCategorical.probsc                 C   s   t | jS N)r   identityr?   rF   r   r   r    _batch_shape_tensor   s   zCategorical._batch_shape_tensorc                 C   s   | j  d d S )Nr   )r&   r7   rF   r   r   r    _batch_shape  s   zCategorical._batch_shapec                 C   s   t jg tjdS )Nr   )r   r=   r   r   rF   r   r   r    _event_shape_tensor  s   zCategorical._event_shape_tensorc                 C   s
   t g S rH   )r   r   rF   r   r   r    _event_shape  s   
zCategorical._event_shapec                 C   s   | j  jdkr| j }n
t| j d| jg}| jjdkrtj	ntj
}tj||||d}tt|t|g|  gd}t|| jS )N   r      )seedZoutput_dtyper   )r&   r7   r   r   reshaper-   r   sizer   Zint64r   r	   ZmultinomialZ	transposeconcatZbatch_shape_tensorr   r   )rB   nrP   Z	logits_2dZsample_dtypeZdrawsr   r   r    	_sample_n  s   zCategorical._sample_nc                 C   s   t j|dd}| jrtj|tjd}t|| j| j	j
d\}}t|d| jf}t|dg}tt|| j|t|}tj|dd}t|t|S )Nkr+   Ztarget_dtyper   r   Zaxis)r   r8   r(   r4   "embed_check_integer_casting_closedr   r   r!   r'   r   r   r   rQ   r<   whereZsequence_maskZ
zeros_liker   
reduce_sumr   )rB   rV   r'   Zbatch_flattened_probsZbatch_flattened_kZto_sum_overZbatch_flattened_cdfr   r   r    _cdf  s&   
zCategorical._cdfc                 C   sL   t j|dd}| jrtj|tjd}t|| j| j	j
d\}}tj||d S )NrV   r+   rW   rX   )labelsr&   )r   r8   r(   r4   rZ   r   r   r!   r&   r   r   r   Z(sparse_softmax_cross_entropy_with_logits)rB   rV   r&   r   r   r    	_log_prob.  s   
zCategorical._log_probc                 C   s   t jt| j| j dd S )Nr   rY   )r   r\   r   log_softmaxr&   r'   rF   r   r   r    _entropy;  s   zCategorical._entropyc                 C   s0   t j| j| jd}t || j}|| j |S )NrY   )r   Zargmaxr&   r9   r   r   r   r.   )rB   retr   r   r    _mode?  s   zCategorical._moderH   )__name__
__module____qualname____doc__r   
deprecatedr   r   rA   propertyr-   r&   r'   rJ   rK   rL   rM   rU   r]   r_   ra   rc   __classcell__r   r   rC   r    r#   :   s:    Y
S



r#   Nc                 C   sn   t j|d| j|jgd! t| jt|j }tjt| j| ddW  d   S 1 s0w   Y  dS )aM  Calculate the batched KL divergence KL(a || b) with a and b Categorical.

  Args:
    a: instance of a Categorical distribution object.
    b: instance of a Categorical distribution object.
    name: (optional) Name to use for created operations.
      default is "kl_categorical_categorical".

  Returns:
    Batchwise KL(a || b)
  Zkl_categorical_categoricalr$   r   rY   N)r   r3   r&   r   r`   r   r\   Zsoftmax)abr)   Zdelta_log_probs1r   r   r    _kl_categorical_categoricalF  s   


$rm   rH   )rg   Ztensorflow.python.frameworkr   r   r   r   Ztensorflow.python.opsr   r   r   r	   Z#tensorflow.python.ops.distributionsr
   r   r   r4   Ztensorflow.python.utilr   Z tensorflow.python.util.tf_exportr   r!   Distributionr#   Z
RegisterKLrm   r   r   r   r    <module>   s*   
  
