U
    d                     @   sB   d dl m  m  mZ d dlmZ d dlZG dd dejZ	dS )    N)	workspacec                   @   s.   e Zd ZdddZdd Zdd Zd	d
 ZdS )ComputeTopKAccuracyN   c                 C   s2   |d krddg}|| _ || _|| _d| _d| _d S )Nsoftmaxlabelr   )	blob_nameoptstopkitervalue)selfr   r   r	    r   S/tmp/pip-unpacked-wheel-ua33x9lu/caffe2/contrib/playground/compute_topk_accuracy.py__init__   s    zComputeTopKAccuracy.__init__c                 C   s   d| _ d| _d S )Nr   )r
   r   )r   r   r   r   Reset   s    zComputeTopKAccuracy.Resetc           
   	   C   s  t | jd d | jd d | jd d  D ]L}d| jd d |}t|| jd  }t|| jd  }t|}t|}t|j	dkr|
d|j	d f}nt|j	dkstd	t|j	dkstd
|j	d |j	d kstd|j	d }tj| ddd d d | jf }||jtj|
|df| jgddk}	|  jt|	d d d | jf 7  _|  j|7  _q,d S )NZdistributedZfirst_xpu_idZnum_xpusz{}_{}/Zdevicer   r      z%wrong output size (1D or 2D expected)zwrong target size (1D expected)ztarget and output do not match)Zaxis)ranger   formatr   Z	FetchBlobr   npZsqueezelenshapeZreshapeAssertionErrorZargsortr	   ZastypeZdtyperepeatr   sumr
   )
r   idxprefixr   labelsoutputtargetNpredcorrectr   r   r   Add   s8    



"  &zComputeTopKAccuracy.Addc                 C   s   | j | j }|   |S )N)r   r
   r   )r   resultr   r   r   Compute8   s    zComputeTopKAccuracy.Compute)NNr   )__name__
__module____qualname__r   r   r"   r$   r   r   r   r   r      s   
	r   )
Zcaffe2.contrib.playground.metercontribZ
playgroundZmeterZMeterZcaffe2.pythonr   Znumpyr   r   r   r   r   r   <module>   s   