o
    xiU                     @  s   d Z ddlmZ ddlmZ ddlmZ ddlmZm	Z	 ddl
Z
ddlmZ G dd	 d	ZdddZdddZ			ddddZdS ) zcatboost init.    )annotations)Path)SimpleNamespace)CatBoostClassifierCatBoostRegressorN)	telemetryc                   @  s&   e Zd ZdZddddZdddZdS )WandbCallbackal  `WandbCallback` automatically integrates CatBoost with wandb.

    Args:
        - metric_period: (int) if you are passing `metric_period` to your CatBoost model please pass the same value here (default=1).

    Passing `WandbCallback` to CatBoost will:
    - log training and validation metrics at every `metric_period`
    - log iteration at every `metric_period`

    Example:
        ```
        train_pool = Pool(
            train[features], label=train["label"], cat_features=cat_features
        )
        test_pool = Pool(test[features], label=test["label"], cat_features=cat_features)

        model = CatBoostRegressor(
            iterations=100,
            loss_function="Cox",
            eval_metric="Cox",
        )

        model.fit(
            train_pool,
            eval_set=test_pool,
            callbacks=[WandbCallback()],
        )
        ```
       metric_periodintc                 C  sN   t jd u r
t dt }d|j_W d    n1 sw   Y  || _d S )Nz5You must call `wandb.init()` before `WandbCallback()`T)wandbrunErrorwb_telemetrycontextfeaturecatboost_wandb_callbackr
   )selfr
   tel r   W/home/ubuntu/.local/lib/python3.10/site-packages/wandb/integration/catboost/catboost.py__init__-   s   




zWandbCallback.__init__infor   returnboolc                 C  sr   |j | j dkr7|j D ]\}}| D ]\}}tj| d| |d idd qqtd| j |j i dS )Nr   -Fcommitziteration@metric-period-T)	iterationr
   metricsitemsr   log)r   r   datametricmetric_namer"   r   r   r   after_iteration6   s   "zWandbCallback.after_iterationN)r	   )r
   r   )r   r   r   r   )__name__
__module____qualname____doc__r   r&   r   r   r   r   r      s    	r   model&CatBoostClassifier | CatBoostRegressoraliases	list[str]r   Nonec                 C  sj   t jdu r
t ddt jj }tt jjd }| | t j|dd}|t	| t j
||d dS )z(Upload model checkpoint as W&B artifact.N<You must call `wandb.init()` before `_checkpoint_artifact()`model_r+   )nametyper-   )r   r   r   idr   dir
save_modelArtifactadd_filestrlog_artifact)r+   r-   
model_name
model_pathmodel_artifactr   r   r   _checkpoint_artifactB   s   

r?   c                 C  st   t jdu r
t d| jdd}dd t|d |d D }t j|d	d
gd}t jdt jj|d	d
ddidd dS )z-Log feature importance with default settings.Nr0   T)
prettifiedc                 S  s   g | ]\}}||gqS r   r   ).0featfeat_impr   r   r   
<listcomp>a   s    z+_log_feature_importance.<locals>.<listcomp>z
Feature IdImportancesFeature
Importance)r#   columnszFeature Importance)titleFr   )	r   r   r   get_feature_importancezipTabler"   plotbar)r+   feat_dffi_datatabler   r   r   _log_feature_importanceV   s    

rR   TFlog_all_paramsr   save_model_checkpointlog_feature_importancec                 C  s   t jdu r
t dt| ttfst dt }d|j_	W d   n1 s)w   Y  | 
 }|r:t j| |  t jjd< |  t jjd< |r\|d rSdgnd	g}t| |d
 |rdt|  dS dS )aD  `log_summary` logs useful metrics about catboost model after training is done.

    Args:
        model: it can be CatBoostClassifier or CatBoostRegressor.
        log_all_params: (boolean) if True (default) log the model hyperparameters as W&B config.
        save_model_checkpoint: (boolean) if True saves the model upload as W&B artifacts.
        log_feature_importance: (boolean) if True (default) logs feature importance as W&B bar chart using the default setting of `get_feature_importance`.

    Using this along with `wandb_callback` will:

    - save the hyperparameters as W&B config,
    - log `best_iteration` and `best_score` as `wandb.summary`,
    - save and upload your trained model to Weights & Biases Artifacts (when `save_model_checkpoint = True`)
    - log feature importance plot.

    Example:
        ```python
        train_pool = Pool(
            train[features], label=train["label"], cat_features=cat_features
        )
        test_pool = Pool(test[features], label=test["label"], cat_features=cat_features)

        model = CatBoostRegressor(
            iterations=100,
            loss_function="Cox",
            eval_metric="Cox",
        )

        model.fit(
            train_pool,
            eval_set=test_pool,
            callbacks=[WandbCallback()],
        )

        log_summary(model)
        ```
    Nz3You must call `wandb.init()` before `log_summary()`zFModel should be an instance of CatBoostClassifier or CatBoostRegressorTbest_iteration
best_scoreuse_best_modelbestlastr4   )r   r   r   
isinstancer   r   r   r   r   catboost_log_summaryget_all_paramsconfigupdateget_best_iterationsummaryget_best_scorer?   rR   )r+   rS   rT   rU   r   paramsr-   r   r   r   log_summaryq   s(   
+


rd   )r+   r,   r-   r.   r   r/   )r+   r,   r   r/   )TFT)
r+   r,   rS   r   rT   r   rU   r   r   r/   )r*   
__future__r   pathlibr   typesr   catboostr   r   r   wandb.sdk.libr   r   r   r?   rR   rd   r   r   r   r   <module>   s    
4
