o
    -wi_                     @   s   d Z ddlZddlZddlmZ ddlmZmZ ddlZ	ddlm
Z
 ddlZddlmZ g dZg dZerHdd	lmZmZmZ G d
d deZdddZG dd de	jjZdS )zxgboost init!    N)Path)TYPE_CHECKINGcast)Booster)	telemetry)	rmsermslemaemapempheloglosserrorzerror@tmerror)aucaucprndcgmapzndcg@nzmap@n)CallableList
NamedTuplec                   @   s   e Zd ZU eed< dS )CallbackEnvevaluation_result_listN)__name__
__module____qualname__r   __annotations__ r   r   ^/home/ubuntu/sommelier/.venv/lib/python3.10/site-packages/wandb/integration/xgboost/xgboost.pyr       s   
 r   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   c                 S   s0   | j D ]\}}tj||idd qti  d S )NFcommit)r   wandblog)r!   kvr   r   r   callback/   s   z wandb_callback.<locals>.callback)r!   r   r   N)warningswarnUserWarningwb_telemetrycontextfeaturexgboost_old_wandb_callback)telr(   r   r   r   wandb_callback$   s   


r1   c                	   @   s   e Zd ZdZ				ddedededefd	d
ZdedefddZdedefddZ	dede
dedefddZdeddfddZdeddfddZdededdfddZd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log_feature_importanceimportance_typedefine_metricc                 C   sb   || _ || _|| _|| _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)r4   r5   r6   r7   r$   runErrorr,   r-   r.   xgboost_wandb_callback)selfr4   r5   r6   r7   r0   r   r   r   __init__`   s   



"zWandbCallback.__init__modelr   c                 C   s   |  }tjt| |S )z Run before training is finished.)save_configr$   configupdatejsonloads)r;   r=   r?   r   r   r   before_trainingr   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)rD   rE   )r4   _log_model_as_artifactr5   _log_feature_importanceattrr$   r%   floatr   strint)r;   r=   r   r   r   after_trainingz   s   

zWandbCallback.after_trainingepoch	evals_logc                 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"   rM   )itemsr7   _define_metricr$   r%   )r;   r=   rM   rN   datametricmetric_namer%   r   r   r   after_iteration   s   ""zWandbCallback.after_iterationNc                 C   sV   t jj d}tt jj| }|t| t j|dd}|t| t 	| d S )Nz_model.jsonr=   )nametype)
r$   r8   idr   dir
save_modelrJ   Artifactadd_filelog_artifact)r;   r=   
model_name
model_pathmodel_artifactr   r   r   rF      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)r6   c                    s   g | ]}| | gqS r   r   ).0r&   fir   r   
<listcomp>   s    z9WandbCallback._log_feature_importance.<locals>.<listcomp>Feature
Importance)rS   columnszFeature Importance)title)	get_scorer6   r$   Tabler%   plotbar)r;   r=   fi_datatabler   rc   r   rG      s   z%WandbCallback._log_feature_importancerS   rU   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lossrO   min)summarymax)rJ   lowerr$   r7   MINIMIZE_METRICSMAXIMIZE_METRICS)r;   rS   rU   r   r   r   rR      s   zWandbCallback._define_metric)FTr3   T)r   r   r   __doc__boolrJ   r<   r   rC   rL   rK   dictrV   rF   rG   rR   r   r   r   r   r2   7   s*    *
	r2   )r   r   )rw   rA   r)   pathlibr   typingr   r   xgboostxgbr   r$   wandb.sdk.libr   r,   ru   rv   r   r   r   r   r1   r(   TrainingCallbackr2   r   r   r   r   <module>   s     
