a
    yf                     @   s   d dl m Z  d dlZd dlmZmZ d dlmZ d dlmZ d dl	m
Z
 d dlmZmZmZmZ d dlmZmZ d d	lmZmZmZ G d
d deZdS )    )copyN)ClassificationDatasetbuild_dataloader)BaseTrainer)yolo)ClassificationModel)DEFAULT_CFGLOGGERRANKcolorstr)plot_imagesplot_results)is_parallelstrip_optimizertorch_distributed_zero_firstc                       s   e Zd ZdZeddf fdd	Zdd Zd!dd	Z fd
dZd"ddZ	d#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  ZS )%ClassificationTrainera  
    A class extending the BaseTrainer class for training based on a classification model.

    Notes:
        - Torchvision classification models can also be passed to the 'model' argument, i.e. model='resnet18'.

    Example:
        ```python
        from ultralytics.models.yolo.classify import ClassificationTrainer

        args = dict(model="yolov8n-cls.pt", data="imagenet10", epochs=3)
        trainer = ClassificationTrainer(overrides=args)
        trainer.train()
        ```
    Nc                    s>   |du ri }d|d< | ddu r*d|d< t ||| dS )z^Initialize a ClassificationTrainer object with optional configuration overrides and callbacks.NclassifytaskZimgsz   )getsuper__init__)selfcfgZ	overrides
_callbacks	__class__ b/var/www/html/django/DPS/env/lib/python3.9/site-packages/ultralytics/models/yolo/classify/train.pyr   !   s    zClassificationTrainer.__init__c                 C   s   | j d | j_dS )z9Set the YOLO model's class names from the loaded dataset.namesN)datamodelr   r   r   r   r   set_model_attributes*   s    z*ClassificationTrainer.set_model_attributesTc                 C   s   t || jd |otdkd}|r*|| | D ]>}| jjsPt|drP|  t	|t
jjr2| jjr2| jj|_q2| D ]
}d|_qz|S )z>Returns a modified PyTorch model configured for training YOLO.nc)r$   verbosereset_parametersT)r   r    r
   loadmodulesargs
pretrainedhasattrr'   
isinstancetorchnnZDropoutZdropoutp
parametersZrequires_grad)r   r   weightsr&   r!   mr0   r   r   r   	get_model.   s    
zClassificationTrainer.get_modelc                    sd   ddl }t| j|jjv rB|jj| j | jjr2dndd| _d}n
t  }t	
| j| jd  |S )z,Load, create or download model for any task.r   NZIMAGENET1K_V1)r2   r$   )torchvisionstrr!   models__dict__r*   r+   r   setup_modelr   Zreshape_outputsr    )r   r5   Zckptr   r   r   r9   =   s    
z!ClassificationTrainer.setup_modeltrainc                 C   s   t || j|dk|dS )zYCreates a ClassificationDataset instance given an image path, and mode (train/test etc.).r:   )rootr*   Zaugmentprefix)r   r*   )r   Zimg_pathmodebatchr   r   r   build_datasetK   s    z#ClassificationTrainer.build_dataset   r   c                 C   sz   t | | ||}W d   n1 s*0    Y  t||| jj|d}|dkrvt| jrj|jj| jj	_
n|jj| j_
|S )zNReturns PyTorch DataLoader with transforms to preprocess images for inference.N)rankr:   )r   r?   r   r*   workersr   r!   datasetZtorch_transformsmoduleZ
transforms)r   Zdataset_pathZ
batch_sizerA   r=   rC   loaderr   r   r   get_dataloaderO   s    
*
z$ClassificationTrainer.get_dataloaderc                 C   s,   |d  | j|d< |d  | j|d< |S )z+Preprocesses a batch of images and classes.imgcls)toZdevice)r   r>   r   r   r   preprocess_batch]   s    z&ClassificationTrainer.preprocess_batchc                 C   s.   dddt | j   ddg| jddR  S )z5Returns a formatted string showing training progress.
z%11s   ZEpochZGPU_memZ	InstancesSize)len
loss_namesr"   r   r   r   progress_stringc   s    z%ClassificationTrainer.progress_stringc                 C   s(   dg| _ tjj| j| jt| j| jdS )z>Returns an instance of ClassificationValidator for validation.Zloss)r*   r   )	rO   r   r   ZClassificationValidatorZtest_loadersave_dirr   r*   	callbacksr"   r   r   r   get_validatorm   s    z#ClassificationTrainer.get_validatorc                    s>    fdd| j D }|du r |S tt|dg}tt||S )z
        Returns a loss dict with labelled training loss items tensor.

        Not needed for classification but necessary for segmentation & detection
        c                    s   g | ]}  d | qS )/r   ).0xr<   r   r   
<listcomp>z       z:ClassificationTrainer.label_loss_items.<locals>.<listcomp>N   )rO   roundfloatdictzip)r   Z
loss_itemsr<   keysr   rW   r   label_loss_itemst   s
    z&ClassificationTrainer.label_loss_itemsc                 C   s   t | jd| jd dS )zPlots metrics from a CSV file.T)filer   on_plotN)r   csvrb   r"   r   r   r   plot_metrics   s    z"ClassificationTrainer.plot_metricsc                 C   s   | j | jfD ]r}| rt| || ju rtd| d | jj| jj_| jj	| jj_	| j|d| _
| j
dd | d qtdtd| j  dS )	z3Evaluate trained model and save validation results.z
Validating z...)r!   ZfitnessNZon_fit_epoch_endzResults saved to bold)lastbestexistsr   r	   infor*   r    	validatorZplotsZmetricspopZrun_callbacksr   rQ   )r   fr   r   r   
final_eval   s    
z ClassificationTrainer.final_evalc                 C   sB   t |d tt|d |d d| jd| d | jd dS )z.Plots training samples with their annotations.rG   rH   r%   Ztrain_batchz.jpg)ZimagesZ	batch_idxrH   fnamerb   N)r   r.   ZarangerN   viewrQ   rb   )r   r>   nir   r   r   plot_training_samples   s    z+ClassificationTrainer.plot_training_samples)NNT)r:   N)r@   r   r:   )Nr:   )__name__
__module____qualname____doc__r   r   r#   r4   r9   r?   rF   rJ   rP   rS   r`   rd   rm   rq   __classcell__r   r   r   r   r      s   	




r   )r   r.   Zultralytics.datar   r   Zultralytics.engine.trainerr   Zultralytics.modelsr   Zultralytics.nn.tasksr   Zultralytics.utilsr   r	   r
   r   Zultralytics.utils.plottingr   r   Zultralytics.utils.torch_utilsr   r   r   r   r   r   r   r   <module>   s   