
    ГhS              ,          S r SSKrSSKrSSKrSSKJrJrJrJrJ	r	J
r
JrJrJr  SSKrSSKJrJrJr  SSKJrJrJrJr  SSKJrJrJr  SSKJrJrJ r J!r!J"r"J#r#J$r$  \
S	   r%\# S4SSSSSS
SSSS.	S\\&\4   S\S\'S\	\
\\\&4         S\	\!   S\	\(   S\	\'   S\	\RR                     S\	\\(\'4      S\	\\&\RT                  \\+4      S\	\
\      S\	\    S\4S jjj5       r, " S S	5      r- " S S5      r.S\R^                  S\R^                  S\R^                  4S jr0S SS
S!.S"\S#\'S$\S\
\&   S%\	\   S&\(S\\-   4S' jjr1S SS(SS
S).S"\S#\'S$\S*\'S\
\&   S%\	\   S+\	\(   S,\	\   S&\(S\\-   4S- jjr2\# S4S.S(SS SSSSS
SS
SSS
SS/.S\S\S\'S#\'S+\(S,\S0\
\&   S\	\!   S\	\(   S\	\'   S%\	\   S1\(S\	\\'\(4      S2\(S*\'S\	\
\      S&\(S\	\    S\\\&\34   \4   4&S3 jjj5       r4g)5z.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	_RefMixInCVPackT)	evalsobjmaximizeearly_stopping_roundsevals_resultverbose_eval	xgb_model	callbackscustom_metricparamsdtrainnum_boost_roundr   r    r!   r"   r#   r$   r%   r&   r'   returnc       	   	         U
c  / O[         R                   " [        U
5      5      n
U(       a  [        U5      O/ nU Hp  u  p[        U[        5      (       d  [	        S5      e[        U[
        5      (       d  M<  UR                  [        R                  " U5      Ld  Ma  XLd  Mg  [        S5      e   [        X/U Vs/ s H  oS   PM	     sn-   U	S9nSnU(       a!  USL a  SOUnU
R                  [        US95        U(       a  U
R                  [        XeS95        [        X[        U5      S	9nUR                  U5      n[!        UU5       HH  nUR#                  UUX5      (       a    O/UR%                  UUUS
9  UR'                  UUX5      (       d  MH    O   UR)                  U5      nUb  UR%                  UR*                  5        UR-                  5       $ s  snf )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.
maximize :
    Whether to maximize custom_metric.

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 :py:class:`~xgboost.callback.EarlyStopping` or :py:meth:`model
    slicing <xgboost.Booster.__getitem__>` 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. The metric receives transformed prediction (after applying the
    reverse link function) when using a builtin objective, and raw output when using
    a custom objective.

Returns
-------
Booster : a trained booster model

zInvalid type for the `evals`.zfTraining dataset should be used as a reference when constructing the `QuantileDMatrix` for evaluation.r   )
model_fileTr   )periodroundsr!   )metricoutput_margin)	iterationfobj)copylist
isinstancer   	TypeErrorr   refweakref
ValueErrorr   appendr   r   r   callablebefore_trainingrangebefore_iterationupdateafter_iterationafter_traininghistoryreset)r(   r)   r*   r   r    r!   r"   r#   r$   r%   r&   r'   va_dbststart_iterationcb_containeris                      cC:\Users\julio\OneDrive\Documentos\Trabajo\Ideas Frescas\venv\Lib\site-packages\xgboost/training.pytrainrN       s   j  'TYYtI-GI DKbE"g&&;<< r9%%gkk&11 8   &(E%:EqdE%::y
QCO(D0ql*,?@.CWX$x}L 
&
&s
+C?O4((a??

6QS
1''Q>> 5 
%
%c
*CL00199;5 &;s   :Gc            	           \ rS rSrSrS\S\S\\\\	4      SS4S jr
S	\S\4S
 jrS\S\\   SS4S jrS\S\\   S\S\4S jrSrg)r      z-"Auxiliary datastruct to hold one fold of CV.r)   dtestparamr+   Nc                 Z    Xl         X l        US4US4/U l        [        X1U/5      U l        g)zInitialize the CVPack.rN   testN)r)   rQ   	watchlistr   rI   )selfr)   rQ   rR   s       rM   __init__CVPack.__init__   s3     
!7+eV_=55/2    namec                 @   ^ ^ S[         S[         S[         4UU 4S jjnU$ )Nargskwargsr+   c                  <   > [        TR                  T5      " U 0 UD6$ N)getattrrI   )r\   r]   rZ   rV   s     rM   _inner"CVPack.__getattr__.<locals>._inner   s    488T*D;F;;rY   )r   )rV   rZ   ra   s   `` rM   __getattr__CVPack.__getattr__   s)    	<# 	< 	< 	< 	< rY   r3   r4   c                 P    U R                   R                  U R                  X5        g)z&"Update the boosters for one iterationN)rI   rA   r)   )rV   r3   r4   s      rM   rA   CVPack.update   s    Y5rY   fevalr2   c                 P    U R                   R                  U R                  XU5      $ )z'"Evaluate the CVPack for one iteration.)rI   eval_setrU   )rV   r3   rg   r2   s       rM   evalCVPack.eval   s    xx  =QQrY   )rI   rQ   r)   rU   )__name__
__module____qualname____firstlineno____doc__r   r   r
   r   r   rW   strr   rc   intr   rA   r   boolrj   __static_attributes__ rY   rM   r   r      s    833&-36>uT4Z?P6Q3	3  6 68I+> 64 6Rc R(6*: R4 RTW RrY   c            	       t   \ rS rSrS\SS4S jrS\S\\   SS4S jr	S\S	\\
   S
\S\\   4S jrS\\   S\4S jrS\S\\   4S jr SS\\\\\\4      \4   S\\   SS4S jjrS\4S jr\S\4S j5       r\R4                  S\SS4S j5       r\S\4S j5       r\R4                  S\SS4S j5       rSrg)_PackedBooster   cvfoldsr+   Nc                     Xl         g r_   ry   )rV   ry   s     rM   rW   _PackedBooster.__init__   s    rY   r3   r    c                 L    U R                    H  nUR                  X5        M     g)z Iterate through folds for updateN)ry   rA   )rV   r3   r    folds       rM   rA   _PackedBooster.update   s    LLDKK	' !rY   rg   r2   c                 f    U R                    Vs/ s H  oDR                  XU5      PM     nnU$ s  snf )zIterate through folds for eval)ry   rj   )rV   r3   rg   r2   fresults         rM   rj   _PackedBooster.eval   s2     DH<<P<a&&=9<P Qs   .r]   c                 b    U R                    H  nUR                  R                  " S0 UD6  M!     g)z,Iterate through folds for setting attributesNru   )ry   rI   set_attr)rV   r]   r   s      rM   r   _PackedBooster.set_attr   s#    AEENN$V$ rY   keyc                 R    U R                   S   R                  R                  U5      $ )zRedirect to booster attr.r   )ry   rI   attr)rV   r   s     rM   r   _PackedBooster.attr   s!    ||A""'',,rY   r(   valuec                 `    U R                    H  nUR                  R                  X5        M      g)z#Iterate through folds for set_paramN)ry   rI   	set_param)rV   r(   r   r   s       rM   r   _PackedBooster.set_param   s"     AEEOOF* rY   c                 <    U R                   S   R                  5       $ )zNumber of boosted rounds.r   )ry   num_boosted_roundsrV   s    rM   r   !_PackedBooster.num_boosted_rounds   s    ||A1133rY   c                     [        [        [         U R                  S   R                  R	                  S5      5      5      $ )Get best_iterationr   best_iteration)rr   r   ry   rI   r   r   s    rM   r   _PackedBooster.best_iteration  s0     4T\\!_00556FGHIIrY   c                 "    U R                  US9  g)r   )r   Nr   )rV   r3   s     rM   r   r   	  s     	Y/rY   c                     [        [        [         U R                  S   R                  R	                  S5      5      5      $ )zGet best_score.r   
best_score)floatr   ry   rI   r   r   s    rM   r   _PackedBooster.best_score  s/     T%a!4!4!9!9,!GHIIrY   scorec                 "    U R                  US9  g )N)r   r   )rV   r   s     rM   r   r     s    'rY   r{   r_   )rl   rm   rn   ro   _CVFoldsrW   rr   r   r   rA   r   rs   r   rq   rj   r   r   r   r
   r   r   r	   r   r   propertyr   setterr   r   rt   ru   rY   rM   rw   rw      sk    T ( ((9*= ($ (
%-f%5FJ	c%# %3 %
- - -  $+dHU38_5s:;+ }+ 
	+4C 4 J J J 0 0 0 0 JE J J ( ($ ( (rY   rw   groups
boundariesc                     [         R                  " U  Vs/ s H!  n[         R                  " X   XS-      5      PM#     sn5      $ s  snf )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      rM   groups_to_rowsr     s<     >>PVWPV1299Z]J1u4EFPVWXXWs   (Aru   )r   fpreprocshuffledallnfoldrR   r   r   c                    U R                  S5      n[        R                  " U5      nUSL a)  [        R                  R	                  [        U5      5      nO[        R                  " [        U5      5      n[        R                  " X5      n	[        U5       V
Vs/ s H<  n
[        R                  " [        U5       Vs/ s H  oU:w  d  M
  X   PM     sn5      PM>     nn
nU Vs/ s H  n[        X5      PM     nnU	 Vs/ s H  n[        X5      PM     nn/ n[        U5       H  n
U R                  X   SS9nUR                  X|U
      5        U R                  UU
   SS9nUR                  XyU
      5        Ub  U" UUUR                  5       5      u  nnnOUn[        UR                  5       5      U Vs/ s H  nSU4PM	     sn-   nUR!                  [#        UUU5      5        M     U$ s  snf s  snn
f s  snf s  snf s  snf )zV
Make n folds for cross-validation maintaining groups
:return: cross-validation folds
	group_ptrT)allow_groupseval_metric)get_uint_infor   diffrandompermutationlenr   array_splitr?   r   r   slice	set_groupr5   r6   itemsr<   r   )r   r   rR   r   r   r   group_boundariesgroup_sizesidxout_group_idsetkrL   in_group_idset	in_groupsin_idset
out_groups	out_idsetretr)   rQ   tparamitmplsts                          rM   mkgroupfoldr   "  s    ))+6''*+K$ii##C$45iiK()nnS0O uA 	E%LKLqF**LKL   FTES	y3^   HWGVz4  
 C5\HKd;A%678

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

6&%./  J5 L
" 'Ns0   #G.<	G)	G)G.#G4>G94G>)G.F)r   r   
stratifiedfoldsr   seedr   r   c        	         &   [        U5      n[        R                  R                  U5        USL a  Uc  [	        U R                  S5      5      S:  a  [        U UUUUUS9$ USL a.  [        R                  R                  U R                  5       5      n	O$[        R                  " U R                  5       5      n	[        R                  " X5      n
[        U5       VVs/ s H<  n[        R                  " [        U5       Vs/ s H  oU:w  d  M
  X   PM     sn5      PM>     nnnOUb5   U Vs/ s H  oS   PM	     nnU Vs/ s H  oS   PM	     n
n[	        U
5      nOs[!        USUS9n[        UR                  U R                  5       U R                  5       S95      nU Vs/ s H  oS   PM	     nnU Vs/ s H  oS   PM	     n
n[	        U
5      n/ n[        U5       H  nU R#                  X   5      nU R#                  X   5      nUb  U" UUUR%                  5       5      u  nnnOUn[        UR'                  5       5      U Vs/ s H  nS	U4PM	     sn-   nUR)                  [+        UUU5      5        M     U$ s  snf s  snnf s  snf s  snf ! [         am    [        UR                  U R                  5       U R                  5       S95      nU Vs/ s H  oS   PM	     Os  snf nnU Vs/ s H  oS   PM	     Os  snf n
n GNf = fs  snf s  snf s  snf )
z4
Make an n-fold list of CVPack from random indices.
Fr   r   )r   r   rR   r   r   r   Tr   )Xy)n_splitsr   random_stater   )r6   r   r   r   r   r   r   r   num_rowr   r   r?   r   r8   split	get_labelr   r   r5   r   r<   r   )r   r   rR   r   r   r   r   r   r   r   r   r   rL   r   xsplitssfkr   r)   rQ   r   r   r   s                          rM   mknfoldr   X  s    KEIINN4Uu}t!!+./!3!  d?))''7C))DLLN+CNN3.	 5\
! NN%,I,Qq&LIL,IJ! 	 
 
		/&+,e!eH,',-u!1uI- I !%DQcii$.."2dnn6FiGH"()&QaD&)#)*6aqT6	*I
C5\HK(

9<($,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.I		/ ** 'Nsy   #I:=	I5
I5I:%J
 )J 7J
 =JJ
 L1L	 L5I: 
J
 
ALKL'K65L L   )r   r   r   metricsr    r!   r"   r   	as_pandasr$   	show_stdvr   r&   r   r'   r   r   r   c                   USL a  [         (       d  [        S5      e[        U[        5      (       a  U/n[        U[        5      (       a  [        S5      eU R                  5       n [        U [        5      (       a6  U  Vs/ s H  nUS   S:X  d  M  US   PM     nn[        U 5      n SU ;   a  UU S'   U(       d*  SU ;   a$  [        U S   [        5      (       a  U S   nOU S   /nU R                  SS5        0 n[        UUU UUU
UUUS9	nUc  / O[        R                  " [        U5      5      nU(       a!  USL a  SOUnUR                  [        XS	95        U	(       a  UR                  [        XS
95        [        UUS[        U5      S9n[!        U5      nUR#                  U5        [%        U5       GH  nUR'                  UUUS5      (       a    OUR)                  UU5        UR+                  UUUS5      nUR,                  n[/        [0        [2        [        [4        [4        4      U5       HW  u  nnnUS-   U;  a  / UUS-   '   US-   U;  a  / UUS-   '   UUS-      R                  U5        UUS-      R                  U5        MY     U(       d  M  UR7                  5        H  nUU   SUR8                  S-    UU'   M       O   U(       a    SSKnUR<                  R?                  U5      nURC                  U5        U$ s  snf ! [@         a     N$f = f)a  Cross-validation with given parameters.

Parameters
----------
params : dict
    Booster params.
dtrain :
    Data to be trained. Only the :py:class:`DMatrix` without external memory is
    supported.
num_boost_round :
    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.

maximize : bool
    Whether to maximize the evaluataion metric (score or error).

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 cvz'`QuantileDMatrix` is not yet supported.r   r   r   N)	r   r   rR   r   r   r   r   r   r   )r.   r   r/   )r1   is_cvr2   z-meanz-std)"r   r   r7   rq   r   r;   r5   r6   dictpopr   r<   r   r   r   r=   rw   r>   r?   r@   rA   rB   aggregated_cvr   r   r	   r   keysr   pandasr   	from_dictImportErrorrC   ) r(   r)   r*   r   r   r   r   r    r!   r"   r   r   r$   r   r   r&   r   r'   r   _metricsresultsry   callbacks_containerboosterrL   should_breakresr   meanstdr   pds                                    rM   cvr     s   Z T"3"3I
 	
 '3)&)$$BCC[[]F&$"(B&QAaDM,ADAaD&BfF"$,F=!&0f]+T22]+Gm,-G
JJ}d#&(G
G  'TYYtI-GI(D0ql*,TU.CWX+-t8C= W%G''0?#//FDI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/NM CB  		s   =K7	K7K< <
L	L	)
   )5rp   r5   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   rq   rr   rs   EvalsLogPathLike	bytearrayrN   r   rw   ndarrayr   r   r   r   r   ru   rY   rM   <module>r      s+   5  	  T T T  = =  E D   H  _
 6:##+/8</3GK6:&*_cN__ _
 HU7C<012_ 
)	_ tn_ $C=_ +445_ 5s+,_ c2;;BCD_ !123_ F#_ _ _DR R67( 7(tY2:: Y2:: Y"** Y +/3
3 3 	3
 C=3 '(3 3 
&\3x +/!&*.F
F F 	F
 F C=F '(F F &'F F 
&\FR  }
  $##+/+//36:&*'}}} }
 } } } c]} 
)	} tn} $C=} '(} } 5d+,} }  !}" !123#}$ %}& F#'}( 4U
Y&')} }rY   