o
    %ݫi
                     @   s4   d Z ddlZddlmZ dddZG dd dZdS )	z3Calculate accuracy.

Authors
* Jianyuan Zhong 2020
    N)length_to_maskc                 C   s   |dur(t ||jd  |jd d }t|jdkr(|ddd|jd }| d}|durDt|	||	|k}t|}nt||k}|jd }t
|t
|fS )a  Calculates the accuracy for predicted log probabilities and targets in a batch.

    Arguments
    ---------
    log_probabilities : torch.Tensor
        Predicted log probabilities (batch_size, time, feature).
    targets : torch.Tensor
        Target (batch_size, time).
    length : torch.Tensor
        Length of target (batch_size,).

    Returns
    -------
    numerator : float
        The number of correct samples
    denominator : float
        The total number of samples

    Example
    -------
    >>> probs = torch.tensor([[0.9, 0.1], [0.1, 0.9], [0.8, 0.2]]).unsqueeze(0)
    >>> acc = Accuracy(torch.log(probs), torch.tensor([1, 1, 0]).unsqueeze(0), torch.tensor([2/3]))
    >>> print(acc)
    (1.0, 2.0)
    N   )max_len      )r   shapeboollen	unsqueezerepeatargmaxtorchsummasked_selectfloat)log_probabilitiestargetslengthmaskpadded_pred	numeratordenominator r   N/home/ubuntu/.local/lib/python3.10/site-packages/speechbrain/utils/Accuracy.pyAccuracy   s$   

r   c                   @   s*   e Zd ZdZdd Zd	ddZdd ZdS )
AccuracyStatsaq  Module for calculate the overall one-step-forward prediction accuracy.

    Example
    -------
    >>> probs = torch.tensor([[0.9, 0.1], [0.1, 0.9], [0.8, 0.2]]).unsqueeze(0)
    >>> stats = AccuracyStats()
    >>> stats.append(torch.log(probs), torch.tensor([1, 1, 0]).unsqueeze(0), torch.tensor([2/3]))
    >>> acc = stats.summarize()
    >>> print(acc)
    0.5
    c                 C   s   d| _ d| _d S )Nr   correcttotalselfr   r   r   __init__H   s   
zAccuracyStats.__init__Nc                 C   s0   t |||\}}|  j|7  _|  j|7  _dS )a  This function is for updating the stats according to the prediction
        and target in the current batch.

        Arguments
        ---------
        log_probabilities : torch.Tensor
            Predicted log probabilities (batch_size, time, feature).
        targets : torch.Tensor
            Target (batch_size, time).
        length : torch.Tensor
            Length of target (batch_size,).
        N)r   r   r   )r!   r   r   r   r   r   r   r   r   appendL   s   zAccuracyStats.appendc                 C   s   | j | j S )zComputes the accuracy metric.r   r    r   r   r   	summarize]   s   zAccuracyStats.summarizeN)__name__
__module____qualname____doc__r"   r#   r$   r   r   r   r   r   ;   s
    
r   r%   )r)   r   speechbrain.dataio.dataior   r   r   r   r   r   r   <module>   s
    
/