a
    Sic9                     @   sd   d Z ddlZddlm  mZ ddlmZ ddl	m
Z
 ddlmZ edG dd de
jZeZdS )	z!RMSprop optimizer implementation.    N)backend_config)optimizer_v2)keras_exportzkeras.optimizers.RMSpropc                       sf   e Zd ZdZdZd fdd		Zd
d Z fddZdddZdddZ	 fddZ
 fddZ  ZS )RMSpropa  Optimizer that implements the RMSprop algorithm.

    The gist of RMSprop is to:

    - Maintain a moving (discounted) average of the square of gradients
    - Divide the gradient by the root of this average

    This implementation of RMSprop uses plain momentum, not Nesterov momentum.

    The centered version additionally maintains a moving average of the
    gradients, and uses that average to estimate the variance.

    Args:
      learning_rate: A `Tensor`, floating point value, or a schedule that is a
        `tf.keras.optimizers.schedules.LearningRateSchedule`, or a callable
        that takes no arguments and returns the actual value to use. The
        learning rate. Defaults to 0.001.
      rho: Discounting factor for the history/coming gradient. Defaults to 0.9.
      momentum: A scalar or a scalar `Tensor`. Defaults to 0.0.
      epsilon: A small constant for numerical stability. This epsilon is
        "epsilon hat" in the Kingma and Ba paper (in the formula just before
        Section 2.1), not the epsilon in Algorithm 1 of the paper. Defaults to
        1e-7.
      centered: Boolean. If `True`, gradients are normalized by the estimated
        variance of the gradient; if False, by the uncentered second moment.
        Setting this to `True` may help with training, but is slightly more
        expensive in terms of computation and memory. Defaults to `False`.
      name: Optional name prefix for the operations created when applying
        gradients. Defaults to `"RMSprop"`.
      **kwargs: keyword arguments. Allowed arguments are `clipvalue`,
        `clipnorm`, `global_clipnorm`.
        If `clipvalue` (float) is set, the gradient of each weight
        is clipped to be no higher than this value.
        If `clipnorm` (float) is set, the gradient of each weight
        is individually clipped so that its norm is no higher than this value.
        If `global_clipnorm` (float) is set the gradient of all weights is
        clipped so that their global norm is no higher than this value.

    Note that in the dense implementation of this algorithm, variables and their
    corresponding accumulators (momentum, gradient moving average, square
    gradient moving average) will be updated even if the gradient is zero
    (i.e. accumulators will decay, momentum will be applied). The sparse
    implementation (used when the gradient is an `IndexedSlices` object,
    typically because of `tf.gather` or an embedding lookup in the forward pass)
    will not update variable slices or their accumulators unless those slices
    were used in the forward pass (nor is there an "eventual" correction to
    account for these omitted updates). This leads to more efficient updates for
    large embedding lookup tables (where most of the slices are not accessed in
    a particular graph execution), but differs from the published algorithm.

    Usage:

    >>> opt = tf.keras.optimizers.RMSprop(learning_rate=0.1)
    >>> var1 = tf.Variable(10.0)
    >>> loss = lambda: (var1 ** 2) / 2.0    # d(loss) / d(var1) = var1
    >>> step_count = opt.minimize(loss, [var1]).numpy()
    >>> var1.numpy()
    9.683772

    Reference:
      - [Hinton, 2012](
        http://www.cs.toronto.edu/~tijmen/csc321/slides/lecture_slides_lec6.pdf)
    TMbP??        Hz>Fc                    s   t  j|fi | | d|d| | d| j | d| d| _t|tjsdt	|sd|dkrjd| _t|t
tfr|dk s|dkrtd	| d
t| d| d| |pt | _|| _dS )a  Construct a new RMSprop optimizer.

        Args:
          learning_rate: A `Tensor`, floating point value, or a schedule that is
            a `tf.keras.optimizers.schedules.LearningRateSchedule`, or a
            callable that takes no arguments and returns the actual value to
            use. The learning rate. Defaults to 0.001.
          rho: Discounting factor for the history/coming gradient. Defaults to
            0.9.
          momentum: A scalar or a scalar `Tensor`. Defaults to 0.0.
          epsilon: A small constant for numerical stability. This epsilon is
            "epsilon hat" in the Kingma and Ba paper (in the formula just before
            Section 2.1), not the epsilon in Algorithm 1 of the paper. Defaults
            to 1e-7.
          centered: Boolean. If `True`, gradients are normalized by the
            estimated variance of the gradient; if False, by the uncentered
            second moment.  Setting this to `True` may help with training, but
            is slightly more expensive in terms of computation and memory.
            Defaults to `False`.
          name: Optional name prefix for the operations created when applying
            gradients. Defaults to "RMSprop".
          **kwargs: keyword arguments. Allowed to be {`clipnorm`, `clipvalue`,
            `lr`, `decay`}. `clipnorm` is clip gradients by norm; `clipvalue` is
            clip gradients by value, `decay` is included for backward
            compatibility to allow time inverse decay of learning rate. `lr` is
            included for backward compatibility, recommended to use
            `learning_rate` instead.

        @compatibility(eager)
        When eager execution is enabled, `learning_rate`, `decay`, `momentum`,
        and `epsilon` can each be a callable that takes no arguments and returns
        the actual value to use. This can be useful for changing these values
        across different invocations of optimizer functions.
        @end_compatibility
        learning_ratelrdecayrhoFr   T   z6`momentum` must be between [0, 1]. Received: momentum=z
 (of type z).momentumN)super__init__
_set_hyperget_initial_decay	_momentum
isinstancetfTensorcallableintfloat
ValueErrortyper   epsiloncentered)selfr
   r   r   r   r   namekwargs	__class__ a/var/www/html/django/DPS/env/lib/python3.9/site-packages/keras/optimizers/optimizer_v2/rmsprop.pyr   _   s6    -
zRMSprop.__init__c                 C   sR   |D ]}|  |d q| jr2|D ]}|  |d q | jrN|D ]}|  |d q<d S )Nrmsr   mg)add_slotr   r   )r    var_listvarr%   r%   r&   _create_slots   s    zRMSprop._create_slotsc                    sp   t  ||| t| d|}|||f t|||f d  t| j||t| d|d| d d S )Nr   lr_tr   g      ?)neg_lr_tr   r   r   one_minus_rho)	r   _prepare_localr   identity
_get_hyperupdatedictconvert_to_tensorr   )r    
var_device	var_dtypeapply_stater   r#   r%   r&   r0      s    zRMSprop._prepare_localNc                 C   s  |j |jj }}|pi ||fp,| ||}| |d}| jr| |d}| jr| |d}	tj	j
|j|	j|j|j|d |d |d |d || jd
S tj	j|j|j|j|d |d |d |d || jd	S n|d | |d	 t|  }
tjjj||
| jd
}
|
}| jrX| |d}	|d |	 |d	 |  }tjjj|	|| jd
}|
t| }||d | t||d    }tjjj||| jd
jS d S )Nr'   r   r(   r-   r   r   )
r+   r(   msmomr   r   r   r   graduse_locking)	r+   r9   r:   r   r   r   r   r;   r<   r/   r<   )devicedtype
base_dtyper   _fallback_apply_stateget_slotr   r   r   raw_opsResourceApplyCenteredRMSProphandle_use_lockingResourceApplyRMSPropsquarecompatv1assignsqrtop)r    r;   r+   r8   r6   r7   coefficientsr'   r:   r(   rms_tdenom_tmg_tvar_tr%   r%   r&   _resource_apply_dense   sv    


zRMSprop._resource_apply_densec                 C   s6  |j |jj }}|pi ||fp,| ||}| |d}| jr| |d}	| jr| |d}
tj	j
|j|
j|j|	j|d |d |d |d ||| jdS tj	j|j|j|	j|d |d |d |d ||| jd
S n\|| |d	  }tjjj|||d  | jd
}t|g* | |||}t||}W d    n1 sB0    Y  |}| jr| |d}
||d	  }tjjj|
|
|d  | jd
}t|g8 | |
||}t||}|t| }W d    n1 s0    Y  | |||d | t||d   }| jr$tj|||g S tj||g S d S )Nr'   r   r(   r-   r   r   )r+   r(   r9   r:   r   r   r   r   r;   indicesr<   )
r+   r9   r:   r   r   r   r   r;   rT   r<   r/   r=   r.   )r>   r?   r@   r   rA   rB   r   r   r   rC   "ResourceSparseApplyCenteredRMSProprE   rF   ResourceSparseApplyRMSProprI   rJ   rK   control_dependencies_resource_scatter_addgatherrH   rL   group)r    r;   r+   rT   r8   r6   r7   rN   r'   r:   r(   rms_scaled_g_valuesrO   	rms_slicedenom_slicemg_scaled_g_valuesrQ   mg_slice
var_updater%   r%   r&   _resource_apply_sparse   s    

,.zRMSprop._resource_apply_sparsec                    s:   | j }t|t|d kr*tdg| }t | d S )Nr   r   )weightslennparrayr   set_weights)r    rb   paramsr#   r%   r&   rf   ?  s    zRMSprop.set_weightsc              	      s>   t   }|| d| j| d| d| j| jd |S )Nr
   r   r   )r
   r   r   r   r   r   )r   
get_configr3   _serialize_hyperparameterr   r   r   )r    configr#   r%   r&   rh   H  s    
zRMSprop.get_config)r   r   r   r	   Fr   )N)N)__name__
__module____qualname____doc___HAS_AGGREGATE_GRADr   r,   r0   rS   ra   rf   rh   __classcell__r%   r%   r#   r&   r      s   @      E

<
G	r   )rn   numpyrd   tensorflow.compat.v2rI   v2r   kerasr   keras.optimizers.optimizer_v2r    tensorflow.python.util.tf_exportr   OptimizerV2r   RMSPropr%   r%   r%   r&   <module>   s     ?