o
    ?ei7                     @   s   d 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gZedgdG dd dejZG dd deZdS )zStudent's t distribution class.    N)constant_op)dtypes)ops)tensor_shape)	array_ops)	check_ops)control_flow_ops)math_ops)nn)
random_ops)special_math_ops)distribution)util)deprecation)	tf_exportStudentTStudentTWithAbsDfSoftplusScalezdistributions.StudentT)v1c                       s   e Zd ZdZejdddd			 d. fdd	Ze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d$d% Zed&d'd( Zed)d*d+ Zd,d- Z  ZS )0r   a  Student's t-distribution.

  This distribution has parameters: degree of freedom `df`, location `loc`,
  and `scale`.

  #### Mathematical details

  The probability density function (pdf) is,

  ```none
  pdf(x; df, mu, sigma) = (1 + y**2 / df)**(-0.5 (df + 1)) / Z
  where,
  y = (x - mu) / sigma
  Z = abs(sigma) sqrt(df pi) Gamma(0.5 df) / Gamma(0.5 (df + 1))
  ```

  where:
  * `loc = mu`,
  * `scale = sigma`, and,
  * `Z` is the normalization constant, and,
  * `Gamma` is the [gamma function](
    https://en.wikipedia.org/wiki/Gamma_function).

  The StudentT distribution is a member of the [location-scale family](
  https://en.wikipedia.org/wiki/Location-scale_family), i.e., it can be
  constructed as,

  ```none
  X ~ StudentT(df, loc=0, scale=1)
  Y = loc + scale * X
  ```

  Notice that `scale` has semantics more similar to standard deviation than
  variance. However it is not actually the std. deviation; the Student's
  t-distribution std. dev. is `scale sqrt(df / (df - 2))` when `df > 2`.

  Samples of this distribution are reparameterized (pathwise differentiable).
  The derivatives are computed using the approach described in
  (Figurnov et al., 2018).

  #### Examples

  Examples of initialization of one or a batch of distributions.

  ```python
  import tensorflow_probability as tfp
  tfd = tfp.distributions

  # Define a single scalar Student t distribution.
  single_dist = tfd.StudentT(df=3)

  # Evaluate the pdf at 1, returning a scalar Tensor.
  single_dist.prob(1.)

  # Define a batch of two scalar valued Student t's.
  # The first has degrees of freedom 2, mean 1, and scale 11.
  # The second 3, 2 and 22.
  multi_dist = tfd.StudentT(df=[2, 3], loc=[1, 2.], scale=[11, 22.])

  # Evaluate the pdf of the first distribution on 0, and the second on 1.5,
  # returning a length two tensor.
  multi_dist.prob([0, 1.5])

  # Get 3 samples, returning a 3 x 2 tensor.
  multi_dist.sample(3)
  ```

  Arguments are broadcast when possible.

  ```python
  # Define a batch of two Student's t distributions.
  # Both have df 2 and mean 1, but different scales.
  dist = tfd.StudentT(df=2, loc=1, scale=[11, 22.])

  # Evaluate the pdf of both distributions on the same point, 3.0,
  # returning a length 2 tensor.
  dist.prob(3.0)
  ```

  Compute the gradients of samples w.r.t. the parameters:

  ```python
  df = tf.constant(2.0)
  loc = tf.constant(2.0)
  scale = tf.constant(11.0)
  dist = tfd.StudentT(df=df, loc=loc, scale=scale)
  samples = dist.sample(5)  # Shape [5]
  loss = tf.reduce_mean(tf.square(samples))  # Arbitrary loss function
  # Unbiased stochastic gradients of the loss function
  grads = tf.gradients(loss, [df, loc, scale])
  ```

  References:
    Implicit Reparameterization Gradients:
      [Figurnov et al., 2018]
      (http://papers.nips.cc/paper/7326-implicit-reparameterization-gradients)
      ([pdf](http://papers.nips.cc/paper/7326-implicit-reparameterization-gradients.pdf))
  
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_onceFc              	      s   t t }tj||||gdH}t|rt|gng + tj|dd| _	tj|dd| _
tj|dd| _t| j	| j
| jf W d   n1 sKw   Y  W d   n1 sZw   Y  tt| j| jjtj|||| j	| j
| jg|d dS )a  Construct Student's t distributions.

    The distributions have degree of freedom `df`, mean `loc`, and scale
    `scale`.

    The parameters `df`, `loc`, and `scale` must be shaped in a way that
    supports broadcasting (e.g. `df + loc + scale` is a valid operation).

    Args:
      df: Floating-point `Tensor`. The degrees of freedom of the
        distribution(s). `df` must contain only positive values.
      loc: Floating-point `Tensor`. The mean(s) of the distribution(s).
      scale: Floating-point `Tensor`. The scaling factor(s) for the
        distribution(s). Note that `scale` is not technically the standard
        deviation of this distribution but has semantics more similar to
        standard deviation than variance.
      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.

    Raises:
      TypeError: if loc and scale are different dtypes.
    valuesdfnamelocscaleN)dtypeZreparameterization_typevalidate_argsallow_nan_stats
parametersZgraph_parentsr   )dictlocalsr   
name_scopeZcontrol_dependenciesr   Zassert_positiver   identity_df_loc_scaleZassert_same_float_dtypesuperr   __init__r   r   ZFULLY_REPARAMETERIZEDselfr   r   r   r   r   r   r    	__class__ n/home/www/facesmatcher.com/pyenv/lib/python3.10/site-packages/tensorflow/python/ops/distributions/student_t.pyr)      s2   
,

zStudentT.__init__c                 C   s    t tdtj| tjdgd S )N)r   r   r   r      )r!   zipr   Zconvert_to_tensorr   int32)Zsample_shaper.   r.   r/   _param_shapes   s   zStudentT._param_shapesc                 C      | j S )z8Degrees of freedom in these Student's t distribution(s).)r%   r+   r.   r.   r/   r         zStudentT.dfc                 C   r5   )z/Locations of these Student's t distribution(s).)r&   r6   r.   r.   r/   r      r7   zStudentT.locc                 C   r5   )z5Scaling factors of these Student's t distribution(s).)r'   r6   r.   r.   r/   r      r7   zStudentT.scalec              	   C   s,   t t | jt t | jt | jS N)r   Zbroadcast_dynamic_shapeshaper   r   r   r6   r.   r.   r/   _batch_shape_tensor   s   
zStudentT._batch_shape_tensorc                 C   s&   t t | j | j | j S r8   )r   Zbroadcast_static_shaper   	get_shaper   r   r6   r.   r.   r/   _batch_shape   s   zStudentT._batch_shapec                 C   s   t jg tjdS )Nr0   )r   Zconstantr	   r3   r6   r.   r.   r/   _event_shape_tensor   s   zStudentT._event_shape_tensorc                 C   s
   t g S r8   )r   ZTensorShaper6   r.   r.   r/   _event_shape   s   
zStudentT._event_shapeNc              	   C   s   t |g|  gd}tj|| j|d}| jt j|  | jd }tj|gd| d| jt	j
|ddd}|t||  }|| j | j S )Nr   )r   seedr0         ?Z	student_t)salt)betar   r?   )r   concatbatch_shape_tensorr   Zrandom_normalr   r   onesZrandom_gammadistribution_utilZgen_new_seedr	   Zrsqrtr   r   )r+   nr?   r9   Znormal_sampler   Zgamma_sampleZsamplesr.   r.   r/   	_sample_n   s   zStudentT._sample_nc                 C   s   |  ||   S r8   )_log_unnormalized_prob_log_normalization)r+   xr.   r.   r/   	_log_prob  s   zStudentT._log_probc                 C   s2   || j  | j }d| jd  t|d | j  S )Ng            ?       @)r   r   r   r	   log1p)r+   rK   yr.   r.   r/   rI     s   "zStudentT._log_unnormalized_probc                 C   sV   t t | jdt | j  dttj  t d| j  t d| jd   S )Nr@   rM   )r	   logabsr   r   nppilgammar6   r.   r.   r/   rJ     s   zStudentT._log_normalizationc                 C   s\   || j  t| j }| j|d | j  }dtd| j d| }tt|d|d| S )NrN   r@   g        rM   )	r   r	   rR   r   r   Zbetaincr   where_v2less)r+   rK   rP   Zx_tZneg_cdfr.   r.   r/   _cdf  s   zStudentT._cdfc                 C   s   t j|  | jddt jf }|| jdt jf  }t ||gdd }tt	| j
dt| j  t| d| jd  td| jd  td| j    S )Nr0   .rN   r@   rM   )r   rE   rD   r   Znewaxisr   rC   r	   rQ   rR   r   r   ZlbetaZdigamma)r+   vuZbeta_argr.   r.   r/   _entropy  s$   
zStudentT._entropyzThe mean of Student's T equals `loc` if `df > 1`, otherwise it is
      `NaN`. If `self.allow_nan_stats=True`, then an exception will be raised
      rather than returning `NaN`.c              	   C   s   | j tj|  | jd }| jr7tjtj| j	 d}t
t| jtj|  | jd|tj|  |ddS ttjtjg | jd| jddg|S )Nr0   nanr   z*mean not defined for components of df <= 1message)r   r   rE   rD   r   r   rS   arrayr]   as_numpy_dtyperV   r	   greaterr   fillr   with_dependenciesr   assert_less)r+   meanr]   r.   r.   r/   _mean)  s*   zStudentT._meanz
      The variance for Student's T equals

      ```
      df / (df - 2), when df > 2
      infinity, when 1 < df <= 2
      NaN, when df <= 1
      ```
      c              	   C   s  t t| jd| jd t | j}t j|  | jdt	| j
 | j | }tjtj| j d}t | jt |  dk|t j|  |dd}| jrutjtj| j d}t t| jt j|  | jd|t j|  |ddS ttjt jg | jd| jddg|S )NrN   r0   infr   r]   z.variance not defined for components of df <= 1r^   )r   rV   r	   rb   r   Z	ones_likerE   rD   r   Zsquarer   rS   r`   rh   ra   rc   r   r]   r   rd   r   re   )r+   denomvarrh   Zresult_where_definedr]   r.   r.   r/   	_varianceA  sF   

zStudentT._variancec                 C   s   t | jS r8   )r   r$   r   r6   r.   r.   r/   _modek  s   zStudentT._mode)FTr   r8   )__name__
__module____qualname____doc__r   
deprecatedr)   staticmethodr4   propertyr   r   r   r:   r<   r=   r>   rH   rL   rI   rJ   rX   r\   rF   ZAppendDocstringrg   rk   rl   __classcell__r.   r.   r,   r/   r   *   sH    c6






	!c                       s8   e Zd ZdZejdddd			 d	 fdd	Z  ZS )
r   zBStudentT with `df = floor(abs(df))` and `scale = softplus(scale)`.r   zLUse `tfd.StudentT(tf.floor(tf.abs(df)), loc, tf.nn.softplus(scale)) instead.Tr   Fc              	      sx   t t }tj|||gd!}tt| jtt	||t
j|dd|||d W d    n1 s2w   Y  || _d S )Nr   Zsoftplus_scaler   )r   r   r   r   r   r   )r!   r"   r   r#   r(   r   r)   r	   floorrR   r
   Zsoftplus_parametersr*   r,   r.   r/   r)   r  s   


z'StudentTWithAbsDfSoftplusScale.__init__)FTr   )rm   rn   ro   rp   r   rq   r)   rt   r.   r.   r,   r/   r   o  s    	)rp   numpyrS   Ztensorflow.python.frameworkr   r   r   r   Ztensorflow.python.opsr   r   r   r	   r
   r   r   Z#tensorflow.python.ops.distributionsr   r   rF   Ztensorflow.python.utilr   Z tensorflow.python.util.tf_exportr   __all__Distributionr   r   r.   r.   r.   r/   <module>   s2   
  F