o
    xi                     @  s   U d Z ddlmZ ddlZddlZddlmZ ddlmZm	Z	m
Z
mZmZ ddlZddlZddlmZmZ ddlZddlmZ g dZg d	ZermG d
d de
Zeee eeeef  f Zeeeeef f Z de!d< dddZ"G dd dej#j$Z%dS )zxgboost init!    )annotationsN)Path)TYPE_CHECKINGCallable
NamedTupleUnioncast)	TypeAliasoverride)	telemetry)	rmsermslemaemapempheloglosserrorzerror@tmerror)aucaucprndcgmapzndcg@nzmap@nc                   @  s   e Zd ZU ded< dS )CallbackEnvlistevaluation_result_listN)__name__
__module____qualname____annotations__ r   r   U/home/ubuntu/.local/lib/python3.10/site-packages/wandb/integration/xgboost/xgboost.pyr   "   s   
 r   r	   	_EvalsLogreturnr   c                  C  sN   t jdtdd t } d| j_W d   n1 sw   Y  dd
d}|S )zrOld style callback that will be deprecated in favor of WandbCallback. Please try the new logger for more features.zhwandb_callback will be deprecated in favor of WandbCallback. Please use WandbCallback for more features.   )
stacklevelTNenvr   r"   Nonec                 S  s0   | j D ]\}}tj||idd qti  d S )NFcommit)r   wandblog)r%   kvr   r   r    callback5   s   z wandb_callback.<locals>.callback)r%   r   r"   r&   )warningswarnUserWarningwb_telemetrycontextfeaturexgboost_old_wandb_callback)telr-   r   r   r    wandb_callback*   s   


r6   c                      st   e Zd ZdZ				d#d$ fddZed%ddZed%ddZed&ddZd'ddZ	d'ddZ
d(d!d"Z  ZS ))WandbCallbackar  `WandbCallback` automatically integrates XGBoost with wandb.

    Args:
        log_model: (boolean) if True save and upload the model to Weights & Biases Artifacts
        log_feature_importance: (boolean) if True log a feature importance bar plot
        importance_type: (str) one of {weight, gain, cover, total_gain, total_cover} for tree model. weight for linear model.
        define_metric: (boolean) if True (default) capture model performance at the best step, instead of the last step, of training in your `wandb.summary`.

    Passing `WandbCallback` to XGBoost will:

    - log the booster model configuration to Weights & Biases
    - log evaluation metrics collected by XGBoost, such as rmse, accuracy etc. to Weights & Biases
    - log training metric collected by XGBoost (if you provide training data to eval_set)
    - log the best score and the best iteration
    - save and upload your trained model to Weights & Biases Artifacts (when `log_model = True`)
    - log feature importance plot when `log_feature_importance=True` (default).
    - Capture the best eval metric in `wandb.summary` when `define_metric=True` (default).

    Example:
        ```python
        bst_params = dict(
            objective="reg:squarederror",
            colsample_bytree=0.3,
            learning_rate=0.1,
            max_depth=5,
            alpha=10,
            n_estimators=10,
            tree_method="hist",
            callbacks=[WandbCallback()],
        )

        xg_reg = xgb.XGBRegressor(**bst_params)
        xg_reg.fit(
            X_train,
            y_train,
            eval_set=[(X_test, y_test)],
        )
        ```
    FTgain	log_modelboollog_feature_importanceimportance_typestrdefine_metricc                   sl   t    || _|| _|| _|| _tjd u rtdt	
 }d|j_W d    d S 1 s/w   Y  d S )Nz1You must call wandb.init() before WandbCallback()T)super__init__r9   r;   r<   r>   r)   runErrorr1   r2   r3   xgboost_wandb_callback)selfr9   r;   r<   r>   r5   	__class__r   r    r@   f   s   




"zWandbCallback.__init__modelxgb.Boosterr"   c                 C  s   |  }tjt| |S )z Run before training is finished.)save_configr)   configupdatejsonloads)rD   rG   rJ   r   r   r    before_trainingz   s   zWandbCallback.before_trainingc              	   C  sb   | j r| | | jr| | |ddur/tttt	|dt
tt	|dd |S )zRun after training is finished.
best_scoreNbest_iteration)rO   rP   )r9   _log_model_as_artifactr;   _log_feature_importanceattrr)   r*   floatr   r=   int)rD   rG   r   r   r    after_training   s   

zWandbCallback.after_trainingepochrU   	evals_logr!   c                 C  s   |  D ]7\}}|  D ].\}}| jr*| || tj| d| |d idd qtj| d| |d idd qqtd|i d| _dS )z@Run after each iteration. Return True when training should stop.-Fr'   rW   )itemsr>   _define_metricr)   r*   )rD   rG   rW   rX   datametricmetric_namer*   r   r   r    after_iteration   s   	""zWandbCallback.after_iterationr&   c                 C  sV   t jj d}tt jj| }|t| t j|dd}|t| t 	| d S )Nz_model.jsonrG   )nametype)
r)   rA   idr   dir
save_modelr=   Artifactadd_filelog_artifact)rD   rG   
model_name
model_pathmodel_artifactr   r   r    rQ      s   z$WandbCallback._log_model_as_artifactc              	     sT   |j | jd  fdd D }tj|ddgd}tdtjj|ddddi d S )	N)r<   c                   s   g | ]}| | gqS r   r   ).0r+   fir   r    
<listcomp>   s    z9WandbCallback._log_feature_importance.<locals>.<listcomp>Feature
Importance)r]   columnszFeature Importance)title)	get_scorer<   r)   Tabler*   plotbar)rD   rG   fi_datatabler   rm   r    rR      s   z%WandbCallback._log_feature_importancer]   r_   c                 C  s   dt |v rtj| d| dd d S t |tv r*tj| d| dd d S t |tv r?tj| d| dd d S 	 d S )NlossrY   min)summarymax)r=   lowerr)   r>   MINIMIZE_METRICSMAXIMIZE_METRICS)rD   r]   r_   r   r   r    r\      s   zWandbCallback._define_metric)FTr8   T)r9   r:   r;   r:   r<   r=   r>   r:   )rG   rH   r"   rH   )rG   rH   rW   rU   rX   r!   r"   r:   )rG   rH   r"   r&   )r]   r=   r_   r=   r"   r&   )r   r   r   __doc__r@   r
   rN   rV   r`   rQ   rR   r\   __classcell__r   r   rE   r    r7   =   s     *

	r7   )r"   r   )&r   
__future__r   rL   r.   pathlibr   typingr   r   r   r   r   xgboostxgbxgboost.callbacktyping_extensionsr	   r
   r)   wandb.sdk.libr   r1   r   r   r   r   rT   tuple
_ScoreListdictr=   r!   r   r6   r-   TrainingCallbackr7   r   r   r   r    <module>   s&    
