
    :[gT              ,          d Z ddlZddlZddlZddlmZmZmZmZm	Z	m
Z
mZmZmZ ddlZddlmZmZmZ ddlmZmZmZmZ ddlmZmZmZ ddlmZmZm Z m!Z!m"Z"m#Z# e
d	   Z$d
e	e    de	e    de	e    fdZ%e#	 d0ddddddddddd
dee&ef   dede'de	e
eee&f         de	e!   d
e	e    de	e(   de	e'   de	ejR                     de	ee(e'f      de	ee&ejT                  ee+f      de	e
e      de	e    defd       Z, G d d	      Z- G d d      Z.deej^                     d ej^                  dej^                  fd!Z0	 	 	 d1d"ed#e'd$ede
e&   d%e	e   d&e(dee-   fd'Z1	 	 	 	 	 d2d"ed#e'd$ed(e'de
e&   d%e	e   d)e	e(   d*e	e   d&e(dee-   fd+Z2	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d3dedede'd#e'd)e(d*ed,e
e&   de	e!   d
e	e    de	e(   de	e'   d%e	e   d-e(de	ee'e(f      d.e(d(e'de	e
e      d&e(de	e    deee&e3f   ef   f(d/Z4y)4z.Training Library containing training routines.    N)	AnyDictIterableListOptionalSequenceTupleUnioncast   )BoosterParamCallableFPreProcCallable)CallbackContainerEarlyStoppingEvaluationMonitorTrainingCallback)SKLEARN_INSTALLED	DataFrameXGBStratifiedKFold)BoosterDMatrixMetric	ObjectiveXGBoostError_deprecate_positional_argsCVPackfevalcustom_metricreturnc                 n    | d}t        j                  d| d       | |t        d      ||}|S | }|S )NzIhttps://xgboost.readthedocs.io/en/latest/tutorials/custom_metric_obj.htmlzy`feval` is deprecated, use `custom_metric` instead.  They have different behavior when custom objective is also used.See z$ for details on the `custom_metric`.zLBoth `feval` and `custom_metric` are supplied.  Use `custom_metric` instead.)warningswarn
ValueError)r   r   linkeval_metrics       K/var/www/html/bid-api/venv/lib/python3.12/site-packages/xgboost/training.py_configure_custom_metricr(      sp     W 	 	&<>	

 ]6Z
 	
 $1#<-K CHK    T)
evalsobjr   maximizeearly_stopping_roundsevals_resultverbose_eval	xgb_model	callbacksr   paramsdtrainnum_boost_roundr*   r+   r,   r-   r.   r/   r0   r1   c       
   	         |g nt        j                   t        |            }t        ||      }|rt        |      ng }t        | |g|D cg c]  }|d   	 c}z   |
      }d}|	r#|	du rdn|	}	|j	                  t        |	             |r|j	                  t        ||             t        ||t        |      xs ||u       }|j                  |      }t        ||      D ]B  }|j                  ||||      r n,|j                  |||       |j                  ||||      sB n |j                  |      }||j                  |j                         |j                         S c c}w )	a  Train a booster with given parameters.

    Parameters
    ----------
    params :
        Booster params.
    dtrain :
        Data to be trained.
    num_boost_round :
        Number of boosting iterations.
    evals :
        List of validation sets for which metrics will evaluated during training.
        Validation metrics will help us track the performance of the model.
    obj
        Custom objective function.  See :doc:`Custom Objective
        </tutorials/custom_metric_obj>` for details.
    feval :
        .. deprecated:: 1.6.0
            Use `custom_metric` instead.
    maximize :
        Whether to maximize feval.
    early_stopping_rounds :
        Activates early stopping. Validation metric needs to improve at least once in
        every **early_stopping_rounds** round(s) to continue training.
        Requires at least one item in **evals**.
        The method returns the model from the last iteration (not the best one).  Use
        custom callback or model slicing if the best model is desired.
        If there's more than one item in **evals**, the last entry will be used for early
        stopping.
        If there's more than one metric in the **eval_metric** parameter given in
        **params**, the last metric will be used for early stopping.
        If early stopping occurs, the model will have two additional fields:
        ``bst.best_score``, ``bst.best_iteration``.
    evals_result :
        This dictionary stores the evaluation results of all the items in watchlist.

        Example: with a watchlist containing
        ``[(dtest,'eval'), (dtrain,'train')]`` and
        a parameter containing ``('eval_metric': 'logloss')``,
        the **evals_result** returns

        .. code-block:: python

            {'train': {'logloss': ['0.48253', '0.35953']},
             'eval': {'logloss': ['0.480385', '0.357756']}}

    verbose_eval :
        Requires at least one item in **evals**.
        If **verbose_eval** is True then the evaluation metric on the validation set is
        printed at each boosting stage.
        If **verbose_eval** is an integer then the evaluation metric on the validation set
        is printed at every given **verbose_eval** boosting stage. The last boosting stage
        / the boosting stage found by using **early_stopping_rounds** is also printed.
        Example: with ``verbose_eval=4`` and at least one item in **evals**, an evaluation metric
        is printed every 4 boosting stages, instead of every boosting stage.
    xgb_model :
        Xgb model to be loaded before training (allows training continuation).
    callbacks :
        List of callback functions that are applied at end of each iteration.
        It is possible to use predefined callbacks by using
        :ref:`Callback API <callback_api>`.

        .. note::

           States in callback are not preserved during training, which means callback
           objects can not be reused for multiple training sessions without
           reinitialization or deepcopy.

        .. code-block:: python

            for params in parameters_grid:
                # be sure to (re)initialize the callbacks before each run
                callbacks = [xgb.callback.LearningRateScheduler(custom_rates)]
                xgboost.train(params, Xy, callbacks=callbacks)

    custom_metric:

        .. versionadded 1.6.0

        Custom metric function.  See :doc:`Custom Metric </tutorials/custom_metric_obj>`
        for details.

    Returns
    -------
    Booster : a trained booster model
    r   )
model_fileTr   )periodroundsr,   )metricoutput_margin)	iterationfobj)copylistr(   r   appendr   r   r   callablebefore_trainingrangebefore_iterationupdateafter_iterationafter_traininghistory)r2   r3   r4   r*   r+   r   r,   r-   r.   r/   r0   r1   r   	metric_fndbststart_iterationcb_containeris                      r'   trainrO   3   sh   P  'TYYtI-GI(>I DKbE
&6(E%:EqadE%::y
QCO(D0ql*,?@.ChWX$ sm9yE'9L 
&
&s
+C?O4((a?

6QS
1''Q> 5 
%
%c
*CL001 88:C &;s   
E#c            	           e Zd ZdZdededeeeef      ddfdZ	de
defd	Zd
edee   ddfdZd
edee   dede
fdZy)r   z. "Auxiliary datastruct to hold one fold of CV.r3   dtestparamr    Nc                 `    || _         || _        |df|dfg| _        t        |||g      | _        y)z "Initialize the CVPackrO   testN)r3   rQ   	watchlistr   rK   )selfr3   rQ   rR   s       r'   __init__zCVPack.__init__   s9     
!7+eV_=565/2r)   namec                 <     dt         dt         dt         f fd}|S )Nargskwargsr    c                  <     t        j                        | i |S N)getattrrK   )rZ   r[   rX   rV   s     r'   _innerz"CVPack.__getattr__.<locals>._inner   s     *7488T*D;F;;r)   )r   )rV   rX   r_   s   `` r'   __getattr__zCVPack.__getattr__   s$    	<# 	< 	< 	< r)   r<   r=   c                 R    | j                   j                  | j                  ||       y)z' "Update the boosters for one iterationN)rK   rE   r3   )rV   r<   r=   s      r'   rE   zCVPack.update   s    Y5r)   r   r;   c                 R    | j                   j                  | j                  |||      S )z( "Evaluate the CVPack for one iteration.)rK   eval_setrU   )rV   r<   r   r;   s       r'   evalzCVPack.eval   s!    xx  E=QQr)   )__name__
__module____qualname____doc__r   r   r
   r   r   rW   strr   r`   intr   rE   r   boolrd    r)   r'   r   r      s    833&-36>uT4Z?P6Q3	3  6 68I+> 64 6Rc R(6*: R4 RTW Rr)   c            	       T   e Zd ZdeddfdZdedee   ddfdZdedee	   d	e
dee   fd
Zdee   defdZdedee   fdZ	 ddeeeeeef      ef   dee   ddfdZdefdZedefd       Zej2                  deddfd       Zedefd       Zej2                  deddfd       Zy)_PackedBoostercvfoldsr    Nc                     || _         y r]   )ro   )rV   ro   s     r'   rW   z_PackedBooster.__init__   s	    r)   r<   r+   c                 J    | j                   D ]  }|j                  ||        y)z Iterate through folds for updateN)ro   rE   )rV   r<   r+   folds       r'   rE   z_PackedBooster.update   s    LLDKK	3' !r)   r   r;   c                 d    | j                   D cg c]  }|j                  |||       }}|S c c}w )zIterate through folds for eval)ro   rd   )rV   r<   r   r;   fresults         r'   rd   z_PackedBooster.eval   s6     DH<<P<a!&&E=9<P Qs   -r[   c                 ^    | j                   D ]  } |j                  j                  di |   y)z,Iterate through folds for setting attributesNrl   )ro   rK   set_attr)rV   r[   rt   s      r'   rw   z_PackedBooster.set_attr   s%    AAEENN$V$ r)   keyc                 R    | j                   d   j                  j                  |      S )zRedirect to booster attr.r   )ro   rK   attr)rV   rx   s     r'   rz   z_PackedBooster.attr   s!    ||A""'',,r)   r2   valuec                 ^    | j                   D ]  }|j                  j                  ||         y)z#Iterate through folds for set_paramN)ro   rK   	set_param)rV   r2   r{   rt   s       r'   r}   z_PackedBooster.set_param   s$     AEEOOFE* r)   c                 <    | j                   d   j                         S )zNumber of boosted rounds.r   )ro   num_boosted_roundsrV   s    r'   r   z!_PackedBooster.num_boosted_rounds   s    ||A1133r)   c                     t        t        t         | j                  d   j                  j	                  d                  S )Get best_iterationr   best_iteration)rj   r   ro   rK   rz   r   s    r'   r   z_PackedBooster.best_iteration  s0     4T\\!_00556FGHIIr)   c                 (    | j                  |       y)r   )r   Nrw   )rV   r<   s     r'   r   z_PackedBooster.best_iteration	  s     	Y/r)   c                     t        t        t         | j                  d   j                  j	                  d                  S )zGet best_score.r   
best_score)floatr   ro   rK   rz   r   s    r'   r   z_PackedBooster.best_score  s/     T%a!4!4!9!9,!GHIIr)   scorec                 (    | j                  |       y )N)r   r   )rV   r   s     r'   r   z_PackedBooster.best_score  s    'r)   r]   )re   rf   rg   _CVFoldsrW   rj   r   r   rE   r   rk   r   ri   rd   r   rw   rz   r
   r   r   r	   r}   r   propertyr   setterr   r   rl   r)   r'   rn   rn      sk    T ( ((9*= ($ (
%-f%5FJ	c%# %3 %
- - -  $+dHU38_5s:;+ }+ 
	+4C 4 J J J 0 0 0 0 JE J J ( ($ ( (r)   rn   groups
boundariesc                     t        j                  | D cg c]!  }t        j                  ||   ||dz            # c}      S c c}w )z
    Given group row boundaries, convert ground indexes to row indexes
    :param groups: list of groups for testing
    :param boundaries: rows index limits of each group
    :return: row in group
    r   )npconcatenatearange)r   r   gs      r'   groups_to_rowsr     s@     >>PVWPV1299Z]Jq1u4EFPVWXXWs   &AdallnfoldrR   fpreprocshufflec                    | j                  d      }t        j                  |      }|du r)t        j                  j	                  t        |            }nt        j                  t        |            }t        j                  ||      }	t        |      D 
cg c]7  }
t        j                  t        |      D cg c]  }|
|k7  s	|	|    c}      9 }}
}|D cg c]  }t        ||       }}|	D cg c]  }t        ||       }}g }t        |      D ]  }
| j                  ||
   d      }|j                  |||
             | j                  ||
   d      }|j                  ||	|
             | ||||j                               \  }}}n|}t        |j                               |D cg c]  }d|f c}z   }|j!                  t#        |||              |S c c}w c c}}
w c c}w c c}w c c}w )zb
    Make n folds for cross-validation maintaining groups
    :return: cross-validation folds
    	group_ptrT)allow_groupsr&   )get_uint_infor   diffrandompermutationlenr   array_splitrC   r   r   slice	set_groupr>   r?   itemsr@   r   )r   r   rR   r*   r   r   group_boundariesgroup_sizesidxout_group_idsetkrN   in_group_idset	in_groupsin_idset
out_groups	out_idsetretr3   rQ   tparamitmplsts                          r'   mkgroupfoldr   "  s    ))+6''*+K$ii##C$45iiK()nnS%0O uA 	E%LKLqAF*LKL   FTES	y"23^   HWGVz#34  
 C5\HQKd;^A%678

9Q<d
;OA$678$,VUEJJL$I!FE6FFLLN#u&Mus';u&MM

6&%./  J5 L
" 'Ns0   !G#7
GG		G#G)2G..G3G#seed
stratifiedfoldsc	                    t        |      }t        j                  j                  |       |du r|t	        | j                  d            dkD  rt        | |||||      S |du r.t        j                  j                  | j                               }	n#t        j                  | j                               }	t        j                  |	|      }
t        |      D cg c]7  }t        j                  t        |      D cg c]  }||k7  s	|
|    c}      9 }}}n|1	 |D cg c]  }|d   	 }}|D cg c]  }|d   	 }
}t	        |
      }nut!        |d|      }t        |j                  | j                         | j                                     }|D cg c]  }|d   	 }}|D cg c]  }|d   	 }
}t	        |
      }g }t        |      D ]  }| j#                  ||         }| j#                  |
|         }| ||||j%                               \  }}}n|}t        |j'                               |D cg c]  }d	|f c}z   }|j)                  t+        |||              |S c c}w c c}}w c c}w c c}w # t        $ rl t        |j                  | j                         | j                                     }|D cg c]  }|d   	 nc c}w }}|D cg c]  }|d   	 nc c}w }
}Y w xY wc c}w c c}w c c}w )
z<
    Make an n-fold list of CVPack from random indices.
    Fr   r   )r*   r   r   Tr   )Xy)n_splitsr   random_stater&   )r?   r   r   r   r   r   r   r   num_rowr   r   rC   r   	TypeErrorsplit	get_labelr   r   r>   r   r@   r   )r   r   rR   r   r*   r   r   r   r   r   r   r   rN   r   xsplitssfkr   r3   rQ   r   r   r   s                          r'   mknfoldr   W  s    KEIINN4Uu}t!!+./!3eU%(G  d?))''7C))DLLN+CNN3.	 5\
! NN%,I,Q!q&IaL,IJ! 	 
 
		/&+,e!eH,',-u!1uI- I !%DQcii$.."2dnn6FiGH"()&QAaD&)#)*6aQqT6	*I
C5\HQK(

9Q<($,VUEJJL$I!FE6FFLLN#u&Mus';u&MM

6&%./  JE J
 -- 	/%++(8DNN<L+MNF&,-f!f-H-'-.v!1v.I.		/ ** 'Nsy   !I*9
I%I%	I*I: I0+I: 1I5=I: K2'K75K<%I*0
I: :AK/?KK/K$#K/.K/metrics	as_pandas	show_stdvc                    |du rt         st        d      t        |t              r|g}| j	                         } t        | t
              r/| D cg c]  }|d   dk(  s|d    }}t        |       } d| v r|| d<   |s#d| v rt        | d   t
              r| d   }n| d   g}| j                  dd       i }t        ||| ||||||	      }t        ||      }|g nt	        j                  t        |            }|r$|du rdn|}|j                  t        ||             |
r|j                  t        |
|	             t        ||dt        |      xs ||u 	      }t        |      }|j!                  |       t#        |      D ]  }|j%                  |||d      r n|j'                  ||       |j)                  |||d      }|j*                  }t-        t.        t0        t        t2        t2        f      |      D ]R  \  }}}|d
z   |vrg ||d
z   <   |dz   |vrg ||dz   <   ||d
z      j                  |       ||dz      j                  |       T |s|j5                         D ]  } ||    d|j6                  dz    || <     n |r 	 ddl}!|!j:                  j=                  |      }|jA                  |       |S c c}w # t>        $ r Y #w xY w)a  Cross-validation with given parameters.

    Parameters
    ----------
    params : dict
        Booster params.
    dtrain : DMatrix
        Data to be trained.
    num_boost_round : int
        Number of boosting iterations.
    nfold : int
        Number of folds in CV.
    stratified : bool
        Perform stratified sampling.
    folds : a KFold or StratifiedKFold instance or list of fold indices
        Sklearn KFolds or StratifiedKFolds object.
        Alternatively may explicitly pass sample indices for each fold.
        For ``n`` folds, **folds** should be a length ``n`` list of tuples.
        Each tuple is ``(in,out)`` where ``in`` is a list of indices to be used
        as the training samples for the ``n`` th fold and ``out`` is a list of
        indices to be used as the testing samples for the ``n`` th fold.
    metrics : string or list of strings
        Evaluation metrics to be watched in CV.
    obj :

        Custom objective function.  See :doc:`Custom Objective
        </tutorials/custom_metric_obj>` for details.

    feval : function
        .. deprecated:: 1.6.0
            Use `custom_metric` instead.
    maximize : bool
        Whether to maximize feval.
    early_stopping_rounds: int
        Activates early stopping. Cross-Validation metric (average of validation
        metric computed over CV folds) needs to improve at least once in
        every **early_stopping_rounds** round(s) to continue training.
        The last entry in the evaluation history will represent the best iteration.
        If there's more than one metric in the **eval_metric** parameter given in
        **params**, the last metric will be used for early stopping.
    fpreproc : function
        Preprocessing function that takes (dtrain, dtest, param) and returns
        transformed versions of those.
    as_pandas : bool, default True
        Return pd.DataFrame when pandas is installed.
        If False or pandas is not installed, return np.ndarray
    verbose_eval : bool, int, or None, default None
        Whether to display the progress. If None, progress will be displayed
        when np.ndarray is returned. If True, progress will be displayed at
        boosting stage. If an integer is given, progress will be displayed
        at every given `verbose_eval` boosting stage.
    show_stdv : bool, default True
        Whether to display the standard deviation in progress.
        Results are not affected, and always contains std.
    seed : int
        Seed used to generate the folds (passed to numpy.random.seed).
    callbacks :
        List of callback functions that are applied at end of each iteration.
        It is possible to use predefined callbacks by using
        :ref:`Callback API <callback_api>`.

        .. note::

           States in callback are not preserved during training, which means callback
           objects can not be reused for multiple training sessions without
           reinitialization or deepcopy.

        .. code-block:: python

            for params in parameters_grid:
                # be sure to (re)initialize the callbacks before each run
                callbacks = [xgb.callback.LearningRateScheduler(custom_rates)]
                xgboost.train(params, Xy, callbacks=callbacks)

    shuffle : bool
        Shuffle data before creating folds.
    custom_metric :

        .. versionadded 1.6.0

        Custom metric function.  See :doc:`Custom Metric </tutorials/custom_metric_obj>`
        for details.

    Returns
    -------
    evaluation history : list(string)
    Tz;sklearn needs to be installed in order to use stratified cvr   r&   r   N)r7   r   r8   )r:   is_cvr;   z-meanz-std)!r   r   
isinstanceri   r>   r?   dictpopr   r(   r@   r   r   r   rA   rn   rB   rC   rD   rE   rF   aggregated_cvr   r   r	   r   keysr   pandasr   	from_dictImportErrorrG   )"r2   r3   r4   r   r   r   r   r+   r   r,   r-   r   r   r/   r   r   r1   r   r   r   _metricsresultsro   rI   callbacks_containerboosterrN   should_breakresrx   meanstdr   pds"                                     r'   cvr     s   Z T"3I
 	
 '3)[[]F&$"(B&QAaDM,AAaD&BfF"$,F=!&0f]+T2]+Gm,-G
JJ}d#&(GvtWh
E7G )>I  'TYYtI-GI(D0ql*,)TU.ChWX+sm9yE'9	 W%G''0?#//FDIq#*::7AvtT!//"4c5%.?(@#A3GNCsW}G+)+g&V|7*(*f%C'M"))$/C&L!((- H \\^$QZ(F7+A+AA+EG
 $% $& 	ll,,W5G &&w/NG C|  		s   J,J,:J1 1	J=<J=)
   )rl   NT)rl   NFNT)r      FNrl   NNNNNTNTr   NTN)5rh   r>   osr"   typingr   r   r   r   r   r   r	   r
   r   numpyr   _typingr   r   r   callbackr   r   r   r   compatr   r   r   corer   r   r   r   r   r   r   r(   ri   rj   rk   EvalsLogPathLike	bytearrayrO   r   rn   ndarrayr   r   r   r   r   rl   r)   r'   <module>r      sa   5  	  T T T  = =  E D  HF,4V,<f(  L
 6:#"#+/8</3GK6:&*LcNLL L
 HU7C<012L 
)	L FL tnL $C=L +445L 5s+,L c2;;BCDL !123L F#L L L^R R67( 7(tY4

+ Y Y

 Y +/2
22 2 C=	2
 '(2 2 
&\2t +/!&*.@
@@ @ 	@
 C=@ '(@ @ &'@ @ 
&\@L  $#"#+/+//36:&*'zzz z 	z
 z z c]z 
)	z Fz tnz $C=z '(z z 5d+,z z  !z" !123#z$ %z& F#'z( 4U
Y&')zr)   