§
    l¬¸jö)  ã                  ó¢   — d dl mZ d dlmZ d dlmZ d dlZd dlmZ	 d dl
mZmZ d dlmZ d dlmZmZ d dlmZmZ d d	lmZ  G d
„ de¦  «        ZdS )é    )Úannotations)ÚPath)ÚAnyN)ÚClassificationDatasetÚbuild_dataloader)ÚBaseValidator)ÚLOGGERÚRANK)ÚClassifyMetricsÚConfusionMatrix)Úplot_imagesc                  óŽ   ‡ — e Zd ZdZd&d'ˆ fd„Zd(d	„Zd)d„Zd*d„Zd+d„Zd,d„Z	d-d„Z
d.d„Zd,d„Zd/d„Zd0d!„Zd,d"„Zd1d$„Zd2d%„Zˆ xZS )3ÚClassificationValidatoraì  A class extending the BaseValidator class for validation based on a classification model.

    This validator handles the validation process for classification models, including metrics calculation, confusion
    matrix generation, and visualization of results.

    Attributes:
        targets (list[torch.Tensor]): Ground truth class labels.
        pred (list[torch.Tensor]): Model predictions.
        metrics (ClassifyMetrics): Object to calculate and store classification metrics.
        names (dict): Mapping of class indices to class names.
        nc (int): Number of classes.
        confusion_matrix (ConfusionMatrix): Matrix to evaluate model performance across classes.

    Methods:
        get_desc: Return a formatted string summarizing classification metrics.
        init_metrics: Initialize confusion matrix, class names, and tracking containers.
        preprocess: Preprocess input batch by moving data to device.
        update_metrics: Update running metrics with model predictions and batch targets.
        finalize_metrics: Finalize metrics including confusion matrix and processing speed.
        postprocess: Extract the primary prediction from model output.
        get_stats: Calculate and return a dictionary of metrics.
        build_dataset: Create a ClassificationDataset instance for validation.
        get_dataloader: Build and return a data loader for classification validation.
        print_results: Print evaluation metrics for the classification model.
        plot_val_samples: Plot validation image samples with their ground truth labels.
        plot_predictions: Plot images with their predicted class labels.

    Examples:
        >>> from ultralytics.models.yolo.classify import ClassificationValidator
        >>> args = dict(model="yolo26n-cls.pt", data="imagenet10")
        >>> validator = ClassificationValidator(args=args)
        >>> validator()

    Notes:
        Torchvision classification models can also be passed to the 'model' argument, i.e. model='resnet18'.
    NÚ
_callbacksúdict | NoneÚreturnÚNonec                óª   •— t          ¦   «                              ||||¦  «         d| _        d| _        d| j        _        t          ¦   «         | _        dS )aá  Initialize ClassificationValidator with dataloader, save directory, and other parameters.

        Args:
            dataloader (torch.utils.data.DataLoader, optional): DataLoader to use for validation.
            save_dir (str | Path, optional): Directory to save results.
            args (dict, optional): Arguments containing model and validation configuration.
            _callbacks (dict, optional): Dictionary of callback functions to be called during validation.
        NÚclassify)ÚsuperÚ__init__ÚtargetsÚpredÚargsÚtaskr   Úmetrics)ÚselfÚ
dataloaderÚsave_dirr   r   Ú	__class__s        €út/root/private/project/pallet_detection_v2/.venv/lib/python3.11/site-packages/ultralytics/models/yolo/classify/val.pyr   z ClassificationValidator.__init__8   sK   ø€ õ 	‰Œ×Ò˜ X¨t°ZÑ@Ô@Ð@ØˆŒØˆŒ	Ø#ˆŒ	ŒÝ&Ñ(Ô(ˆŒˆˆó    Ústrc                ó   — ddz  S )z=Return a formatted string summarizing classification metrics.z%22s%11s%11s)ÚclassesÚtop1_accÚtop5_acc© ©r   s    r!   Úget_descz ClassificationValidator.get_descG   s   € à#Ð'JÑJÐJr"   Úmodelútorch.nn.Modulec                ó¢   — |j         | _         t          |j         ¦  «        | _        g | _        g | _        t          |j         d¬¦  «        | _        dS )z^Initialize confusion matrix, class names, and tracking containers for predictions and targets.r   )Únamesr   N)r.   ÚlenÚncr   r   r   Úconfusion_matrix)r   r+   s     r!   Úinit_metricsz$ClassificationValidator.init_metricsK   sG   € à”[ˆŒ
Ý�e”kÑ"Ô"ˆŒØˆŒ	ØˆŒÝ /°e´kÈ
Ð SÑ SÔ SˆÔÐÐr"   Úbatchúdict[str, Any]c                óX  — |d                               | j        | j        j        dv¬¦  «        |d<   | j        j        dk    r|d                              ¦   «         n|d                              ¦   «         |d<   |d                               | j        | j        j        dv¬¦  «        |d<   |S )zTPreprocess input batch by moving data to device and converting to appropriate dtype.Úimg>   ÚcpuÚmps)Únon_blockingé   Úcls)ÚtoÚdeviceÚtyper   ÚquantizeÚhalfÚfloat)r   r3   s     r!   Ú
preprocessz"ClassificationValidator.preprocessS   s™   € à˜U”|—’ t¤{ÀÄÔAQÐYgÐAg�ÑhÔhˆˆe‰Ø.2¬iÔ.@ÀBÒ.FÐ.F�u˜U”|×(Ò(Ñ*Ô*Ð*ÈEÐRWÌL×L^ÒL^ÑL`ÔL`ˆˆe‰Ø˜U”|—’ t¤{ÀÄÔAQÐYgÐAg�ÑhÔhˆˆe‰Øˆr"   Úpredsútorch.Tensorc                ó¼  — t          t          | j        ¦  «        d¦  «        }| j                             |                     dd¬¦  «        dd…d|…f                              t          j        ¦  «         	                    ¦   «         ¦  «         | j
                             |d                              t          j        ¦  «         	                    ¦   «         ¦  «         dS )aî  Update running metrics with model predictions and batch targets.

        Args:
            preds (torch.Tensor): Model predictions, typically logits or probabilities for each class.
            batch (dict): Batch data containing images and class labels.

        Notes:
            This method appends the top-N predictions (sorted by confidence in descending order) to the
            prediction list for later evaluation. N is limited to the minimum of 5 and the number of classes.
        é   é   T)Ú
descendingNr;   )Úminr/   r.   r   ÚappendÚargsortr>   ÚtorchÚint32r7   r   )r   rC   r3   Ún5s       r!   Úupdate_metricsz&ClassificationValidator.update_metricsZ   sª   € õ •�T”Z‘” !Ñ$Ô$ˆØŒ	×Ò˜Ÿš q°T˜Ñ:Ô:¸1¸1¸1¸c¸r¸c¸6ÔB×GÒGÍÌÑTÔT×XÒXÑZÔZÑ[Ô[Ð[ØŒ×Ò˜E %œL×-Ò-­e¬kÑ:Ô:×>Ò>Ñ@Ô@ÑAÔAÐAÐAÐAr"   c                ó&  — | j                              | j        | j        ¦  «         | j        j        r,dD ])}| j                              | j        || j        ¬¦  «         Œ*| j	        | j
        _	        | j        | j
        _        | j         | j
        _         dS )aœ  Finalize metrics including confusion matrix and processing speed.

        Examples:
            >>> validator = ClassificationValidator()
            >>> validator.pred = [torch.tensor([[0, 1, 2]])]  # Top-3 predictions for one sample
            >>> validator.targets = [torch.tensor([0])]  # Ground truth class
            >>> validator.finalize_metrics()
            >>> print(validator.metrics.confusion_matrix)  # Access the confusion matrix

        Notes:
            This method processes the accumulated predictions and targets to generate the confusion matrix,
            optionally plots it, and updates the metrics object with speed information.
        )TF)r   Ú	normalizeÚon_plotN)r1   Úprocess_cls_predsr   r   r   ÚplotsÚplotr   rR   Úspeedr   )r   rQ   s     r!   Úfinalize_metricsz(ClassificationValidator.finalize_metricsi   s‘   € ð 	Ô×/Ò/°´	¸4¼<ÑHÔHÐHØŒ9Œ?ð 	nØ(ð nð n�	ØÔ%×*Ò*°D´MÈYÐ`dÔ`lÐ*ÑmÔmÐmÐmØ!œZˆŒÔØ $¤ˆŒÔØ(,Ô(=ˆŒÔ%Ð%Ð%r"   ú7torch.Tensor | list[torch.Tensor] | tuple[torch.Tensor]c                óN   — t          |t          t          f¦  «        r|d         n|S )zSExtract the primary prediction from model output if it's in a list or tuple format.r   )Ú
isinstanceÚlistÚtuple)r   rC   s     r!   Úpostprocessz#ClassificationValidator.postprocess   s#   € å% e­dµE¨]Ñ;Ô;ÐFˆu�QŒxˆxÀÐFr"   údict[str, float]c                ód   — | j                              | j        | j        ¦  «         | j         j        S )zSCalculate and return a dictionary of metrics by processing targets and predictions.)r   Úprocessr   r   Úresults_dictr)   s    r!   Ú	get_statsz!ClassificationValidator.get_statsƒ   s)   € àŒ×Ò˜Tœ\¨4¬9Ñ5Ô5Ð5ØŒ|Ô(Ð(r"   c                óº  — t           dk    rŠdgt          j        ¦   «         z  }dgt          j        ¦   «         z  }t          j        | j        |d¬¦  «         t          j        | j        |d¬¦  «         d„ |D ¦   «         | _        d„ |D ¦   «         | _        dS t           dk    r:t          j        | j        dd¬¦  «         t          j        | j        dd¬¦  «         dS dS )zGather stats from all GPUs.r   N)Údstc                ó   — g | ]	}|D ]}|‘ŒŒ
S r(   r(   )Ú.0Úrankr   s      r!   ú
<listcomp>z8ClassificationValidator.gather_stats.<locals>.<listcomp>�   s%   € ÐJÐJÐJ $ÀTÐJÐJ¸T˜ÐJÐJÐJÐJr"   c                ó   — g | ]	}|D ]}|‘ŒŒ
S r(   r(   )rf   rg   r   s      r!   rh   z8ClassificationValidator.gather_stats.<locals>.<listcomp>�   s&   € ÐUÐUÐU¨ÐPTÐUÐUÀW˜GÐUÐUÐUÐUr"   )r
   ÚdistÚget_world_sizeÚgather_objectr   r   )r   Úgathered_predsÚgathered_targetss      r!   Úgather_statsz$ClassificationValidator.gather_statsˆ   sä   € å�1Š9ˆ9Ø"˜V¥dÔ&9Ñ&;Ô&;Ñ;ˆNØ $˜v­Ô(;Ñ(=Ô(=Ñ=ÐÝÔ˜tœy¨.¸aÐ@Ñ@Ô@Ð@ÝÔ˜tœ|Ð-=À1ÐEÑEÔEÐEØJÐJ¨.ÐJÑJÔJˆDŒIØUÐUÐ0@ÐUÑUÔUˆDŒLˆLˆLÝ�AŠXˆXÝÔ˜tœy¨$°AÐ6Ñ6Ô6Ð6ÝÔ˜tœ|¨T°qÐ9Ñ9Ô9Ð9Ð9Ð9ð ˆXr"   Úimg_pathr   c                óR   — t          || j        d| j        j        | j        ¬¦  «        S )z7Create a ClassificationDataset instance for validation.F)ÚaugmentÚprefixr.   )r   r   Úsplitr.   )r   rp   s     r!   Úbuild_datasetz%ClassificationValidator.build_dataset•   s(   € å$ X¨t¬yÀ%ÐPTÔPYÔP_ÐgkÔgqÐrÑrÔrÐrr"   Údataset_pathú
Path | strÚ
batch_sizeÚintútorch.utils.data.DataLoaderc                ó¤   — |                       |¦  «        }|j        st          d|› �¦  «        ‚t          ||| j        j        d| j        ¬¦  «        S )aP  Build and return a data loader for classification validation.

        Args:
            dataset_path (str | Path): Path to the dataset directory.
            batch_size (int): Number of samples per batch.

        Returns:
            (torch.utils.data.DataLoader): DataLoader object for the classification validation dataset.
        z,No images from the model's classes found in éÿÿÿÿ)rg   r=   )ru   ÚsamplesÚFileNotFoundErrorr   r   Úworkersr=   )r   rv   rx   Údatasets       r!   Úget_dataloaderz&ClassificationValidator.get_dataloader™   s\   € ð ×$Ò$ \Ñ2Ô2ˆØŒð 	cÝ#Ð$aÐS_Ð$aÐ$aÑbÔbÐbÝ ¨°T´YÔ5FÈRÐX\ÔXcÐdÑdÔdÐdr"   c                ó    — ddt          | j        j        ¦  «        z  z   }t          j        |d| j        j        | j        j        fz  ¦  «         dS )z6Print evaluation metrics for the classification model.z%22sz%11.3gÚallN)r/   r   Úkeysr	   ÚinfoÚtop1Útop5)r   Úpfs     r!   Úprint_resultsz%ClassificationValidator.print_results¨   sJ   € à�h¥ T¤\Ô%6Ñ!7Ô!7Ñ7Ñ7ˆÝŒ�B˜% ¤Ô!2°D´LÔ4EÐFÑFÑGÔGÐGÐGÐGr"   Únic                ó¨   — t          j        |d         j        d         ¦  «        |d<   t          || j        d|› d�z  | j        | j        ¬¦  «         dS )aê  Plot validation image samples with their ground truth labels.

        Args:
            batch (dict[str, Any]): Dictionary containing batch data with 'img' (images) and 'cls' (class labels).
            ni (int): Batch index used for naming the output file.

        Examples:
            >>> validator = ClassificationValidator()
            >>> batch = {"img": torch.rand(16, 3, 224, 224), "cls": torch.randint(0, 10, (16,))}
            >>> validator.plot_val_samples(batch, 0)
        r6   r   Ú	batch_idxÚ	val_batchz_labels.jpg)ÚlabelsÚfnamer.   rR   N)rL   ÚarangeÚshaper   r   r.   rR   )r   r3   rŠ   s      r!   Úplot_val_samplesz(ClassificationValidator.plot_val_samples­   sh   € õ #œ\¨%°¬,Ô*<¸QÔ*?Ñ@Ô@ˆˆkÑÝØØ”-Ð"=¨bÐ"=Ð"=Ð"=Ñ=Ø”*Ø”Lð		
ñ 	
ô 	
ð 	
ð 	
ð 	
r"   c                ó  — |d         t          j        |d         j        d         ¦  «        t          j        |d¬¦  «        t          j        |d¬¦  «        dœ}t          || j        d|› d�z  | j        | j        ¬¦  «         d	S )
a\  Plot images with their predicted class labels and save the visualization.

        Args:
            batch (dict[str, Any]): Batch data containing images and other information.
            preds (torch.Tensor): Model predictions with shape (batch_size, num_classes).
            ni (int): Batch index used for naming the output file.

        Examples:
            >>> validator = ClassificationValidator()
            >>> batch = {"img": torch.rand(16, 3, 224, 224)}
            >>> preds = torch.rand(16, 10)  # 16 images, 10 classes
            >>> validator.plot_predictions(batch, preds, 0)
        r6   r   rG   )Údim)r6   rŒ   r;   Úconfr�   z	_pred.jpg)r�   r.   rR   N)	rL   r�   r‘   ÚargmaxÚamaxr   r   r.   rR   )r   r3   rC   rŠ   Úbatched_predss        r!   Úplot_predictionsz(ClassificationValidator.plot_predictionsÁ   sš   € ð ˜”<Ýœ e¨E¤lÔ&8¸Ô&;Ñ<Ô<Ý”< ¨1Ð-Ñ-Ô-Ý”J˜u¨!Ð,Ñ,Ô,ð	
ð 
ˆõ 	ØØ”-Ð";¨bÐ";Ð";Ð";Ñ;Ø”*Ø”Lð		
ñ 	
ô 	
ð 	
ð 	
ð 	
r"   )NNNN)r   r   r   r   )r   r#   )r+   r,   r   r   )r3   r4   r   r4   )rC   rD   r3   r4   r   r   )r   r   )rC   rX   r   rD   )r   r^   )rp   r#   r   r   )rv   rw   rx   ry   r   rz   )r3   r4   rŠ   ry   r   r   )r3   r4   rC   rD   rŠ   ry   r   r   )Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   r*   r2   rB   rO   rW   r]   rb   ro   ru   r�   r‰   r’   r™   Ú__classcell__)r    s   @r!   r   r      sm  ø€ € € € € ð#ð #ðJ)ð )ð )ð )ð )ð )ð )ðKð Kð Kð KðTð Tð Tð Tðð ð ð ðBð Bð Bð Bð>ð >ð >ð >ð,Gð Gð Gð Gð)ð )ð )ð )ð
:ð :ð :ð :ðsð sð sð sðeð eð eð eðHð Hð Hð Hð

ð 
ð 
ð 
ð(
ð 
ð 
ð 
ð 
ð 
ð 
ð 
r"   r   )Ú
__future__r   Úpathlibr   Útypingr   rL   Útorch.distributedÚdistributedrj   Úultralytics.datar   r   Úultralytics.engine.validatorr   Úultralytics.utilsr	   r
   Úultralytics.utils.metricsr   r   Úultralytics.utils.plottingr   r   r(   r"   r!   ú<module>r©      s  ðð #Ð "Ð "Ð "Ð "Ð "à Ð Ð Ð Ð Ð Ø Ð Ð Ð Ð Ð à €€€Ø  Ð  Ð  Ð  Ð  Ð  à DÐ DÐ DÐ DÐ DÐ DÐ DÐ DØ 6Ð 6Ð 6Ð 6Ð 6Ð 6Ø *Ð *Ð *Ð *Ð *Ð *Ð *Ð *Ø FÐ FÐ FÐ FÐ FÐ FÐ FÐ FØ 2Ð 2Ð 2Ð 2Ð 2Ð 2ðH
ð H
ð H
ð H
ð H
˜mñ H
ô H
ð H
ð H
ð H
r"   