
    4ri              %          d Z ddlZddlZddlmZmZ ddlmZ ddlm	Z	 ddl
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 dd	lmZmZmZmZmZmZmZmZm Z m!Z!m"Z" dd
l#m$Z$m%Z%m&Z&m'Z' g dZ(eeej)        ege!f         eej)        egee!         f         f         Z*eeeee+ef         geeeee+ef         f         f         Z,de-dee+ef         dee+ef         fdZ.	 	 	 	 	 	 	 d-dee+ef         dede-deee                  deee+                  deee*ee*         f                  deee+e	ef                  de/deee                  defdZ0 G d d          Z1dedeeeeej)        ej)        f                  e%f                  de-dee+ef         d e-d!ee,         d"e/d#e/d$e/de1fd%Z2d&eee                  dee         fd'Z3	 	 	 	 	 	 	 	 	 	 	 	 	 d.dee+ef         dede-deeeeej)        ej)        f                  e%f                  de-d"e/d#e/d*eee+ee+         f                  deee*ee*         f                  deee+e	ef                  d!ee,         d e-deee                  d$e/d+e/dee+eee4         e1f         f         f d,Z5dS )/z+Library with training routines of LightGBM.    N)OrderedDictdefaultdict)
attrgetter)Path)AnyCallableDictIterableListOptionalTupleUnion   )callback)BoosterDatasetLightGBMError_choose_param_value_ConfigAliases_InnerPredictor!_LGBM_BoosterEvalMethodResultType6_LGBM_BoosterEvalMethodResultWithStandardDeviationType_LGBM_CustomObjectiveFunction_LGBM_EvalFunctionResultType_log_warning)SKLEARN_INSTALLED_LGBMBaseCrossValidator_LGBMGroupKFold_LGBMStratifiedKFold)cv	CVBoostertrainnum_boost_round_kwargparamsreturnc                    fdt          j        d          D             }t          d|           t          |          dk    rS t          t	          |                                                    dk    rS d                    d |                                D                       }t          d| dd          d	           S )
a  Choose number of boosting rounds.

    In ``train()`` and ``cv()``, there are multiple ways to provide configuration for
    the number of boosting rounds to perform:

      * the ``num_boost_round`` keyword argument
      * any of the ``num_iterations`` or its aliases via the ``params`` dictionary

    These should be preferred in the following order (first one found wins):

      1. ``num_iterations`` provided via ``params`` (because it's the main parameter name)
      2. any other aliases of ``num_iterations`` provided via ``params``
      3. the ``num_boost_round`` keyword argument

    This function handles that choice, and issuing helpful warnings in the cases where the
    result might be surprising.

    Returns
    -------
    params : dict
        Parameters, with ``"num_iterations"`` set to the preferred value and all other
        aliases of ``num_iterations`` removed.
    c                 *    i | ]}|v ||         S  r(   ).0aliasr$   s     o/var/www/html/bestrading.cuttalo.com/services/ml-inference/venv/lib/python3.11/site-packages/lightgbm/engine.py
<dictcomp>z*_choose_num_iterations.<locals>.<dictcomp>M   s2     & & &!&RW[aRaRave}RaRaRa    num_iterationsmain_param_namer$   default_valuer   z, c              3   *   K   | ]\  }}| d | V  dS )=Nr(   )r)   r*   vals      r+   	<genexpr>z)_choose_num_iterations.<locals>.<genexpr>c   s4      gg*%----ggggggr-   zCFound conflicting values for num_iterations provided via 'params': z. LightGBM will perform up to z boosting rounds. To be confident in the maximum number of boosting rounds LightGBM will perform and to suppress this warning, modify 'params' so that only one of those is present.)	r   getr   lensetvaluesjoinitemsr   )r#   r$   num_iteration_configs_providedvalue_strings    `  r+   _choose_num_iterationsr>   5   s   0& & & &*8*<=M*N*N& & &" !(+  F )**a// 3-44667788A== 99gg@^@d@d@f@fgggggL	Wl 	W 	W'-.>'?	W 	W 	W   Mr-   d   F	train_setnum_boost_round
valid_setsvalid_namesfeval
init_modelkeep_training_booster	callbacksc	                    t          |t                    s%t          dt          |          j         d          t          |t
                    rRt          |          D ]B\  }	}
t          |
t                    s(t          d|	 dt          |
          j         d          Ct          j        |           } t          d| d          } d}t          | d                   r| d         }d| d<   t          || 	          } | d
         }|dk    rt          d| d          t          d| d          } | d         |                     d           |                     dd          }d}t          |t          t           f          rt#          j        ||           }n;t          |t&                    r&t#          j        |t+          |j        fi |           }||                                }nd}|                    |                               |           d}d}g }g }|t          |t                    r|g}t          |t                    r|g}t          |          D ]\  }	}||u rd}|||	         }|                    |                    |                               |                     |/t9          |          |	k    r|                    ||	                    |                    d|	            |t;                      }nOt          |          D ]0\  }	}|j                            d|	t9          |          z
             1t;          |          }tA          j!        |                     dd                    rl|"                    tA          j#        | d         ||                     dd          t          d| d                              d          dk                         d |D             }||z
  }tI          |tK          d                    }tI          |tK          d                    }	 t'          | |          }|r|&                    |           tO          ||          D ]\  }}|(                    ||           	 |)                                 |D ]}|)                                 n2# |)                                 |D ]}|)                                 w xY wd|_*        tW          |||z             D ]}	|D ](} |tA          j,        || |	|||z   d                     )|-                    |            g }|R|r(|.                    |/                    |                     |.                    |0                    |                     	 |D ](} |tA          j,        || |	|||z   |                     )# t@          j1        $ r!}|j*        dz   |_*        |j2        }Y d}~ nd}~ww xY wtg          th                    |_2        |D ]\  }} }!}"|!|j2        |         | <   |s9|5                    |6                                          7                                 |S )!a  Perform the training with given parameters.

    Parameters
    ----------
    params : dict
        Parameters for training. Values passed through ``params`` take precedence over those
        supplied via arguments.
    train_set : Dataset
        Data to be trained on.
    num_boost_round : int, optional (default=100)
        Number of boosting iterations.
    valid_sets : list of Dataset, or None, optional (default=None)
        List of data to be evaluated on during training.
    valid_names : list of str, or None, optional (default=None)
        Names of ``valid_sets``.
    feval : callable, list of callable, or None, optional (default=None)
        Customized evaluation function.
        Each evaluation function should accept two parameters: preds, eval_data,
        and return (eval_name, eval_result, is_higher_better) or list of such tuples.

            preds : numpy 1-D array or numpy 2-D array (for multi-class task)
                The predicted values.
                For multi-class task, preds are numpy 2-D array of shape = [n_samples, n_classes].
                If custom objective function is used, predicted values are returned before any transformation,
                e.g. they are raw margin instead of probability of positive class for binary task in this case.
            eval_data : Dataset
                A ``Dataset`` to evaluate.
            eval_name : str
                The name of evaluation function (without whitespaces).
            eval_result : float
                The eval result.
            is_higher_better : bool
                Is eval result higher better, e.g. AUC is ``is_higher_better``.

        To ignore the default metric corresponding to the used objective,
        set the ``metric`` parameter to the string ``"None"`` in ``params``.
    init_model : str, pathlib.Path, Booster or None, optional (default=None)
        Filename of LightGBM model or Booster instance used for continue training.
    keep_training_booster : bool, optional (default=False)
        Whether the returned Booster will be used to keep training.
        If False, the returned value will be converted into _InnerPredictor before returning.
        This means you won't be able to use ``eval``, ``eval_train`` or ``eval_valid`` methods of the returned Booster.
        When your model is very large and cause the memory error,
        you can try to set this param to ``True`` to avoid the model conversion performed during the internal call of ``model_to_string``.
        You can still use _InnerPredictor as ``init_model`` for future continue training.
    callbacks : list of callable, or None, optional (default=None)
        List of callback functions that are applied at each iteration.
        See Callbacks in Python API for more information.

    Note
    ----
    A custom objective function can be provided for the ``objective`` parameter.
    It should accept two parameters: preds, train_data and return (grad, hess).

        preds : numpy 1-D array or numpy 2-D array (for multi-class task)
            The predicted values.
            Predicted values are returned before any transformation,
            e.g. they are raw margin instead of probability of positive class for binary task.
        train_data : Dataset
            The training dataset.
        grad : numpy 1-D array or numpy 2-D array (for multi-class task)
            The value of the first order derivative (gradient) of the loss
            with respect to the elements of preds for each sample point.
        hess : numpy 1-D array or numpy 2-D array (for multi-class task)
            The value of the second order derivative (Hessian) of the loss
            with respect to the elements of preds for each sample point.

    For multi-class task, preds are numpy 2-D array of shape = [n_samples, n_classes],
    and grad and hess should be returned in the same format.

    Returns
    -------
    booster : Booster
        The trained Booster model.
    z9train() only accepts Dataset object, train_set has type ''.z8Every item in valid_sets must be a Dataset object. Item z has type '	objectiveNr/   noner#   r$   r.   r   6Number of boosting rounds must be greater than 0. Got .early_stopping_roundfirst_metric_onlyF
model_filepred_parameterboosterrS   trainingTvalid_orderearly_stopping_min_delta        	verbosityr   stopping_roundsrP   	min_deltaverbosec                 4    h | ]}t          |d d          |S before_iterationFgetattrr)   cbs     r+   	<setcomp>ztrain.<locals>.<setcomp>"  +     f f fwrK]_d?e?e f f f fr-   key)r$   r@   modelr$   	iterationbegin_iterationend_iterationevaluation_result_listfobj)8
isinstancer   	TypeErrortype__name__list	enumeratecopydeepcopyr   callabler>   
ValueErrorpopr6   strr   r   from_model_filer   from_boosterdictr$   current_iteration_update_params_set_predictorappendset_referencer7   r8   __dict__
setdefaultr   _should_enable_early_stoppingaddearly_stoppingsortedr   set_train_data_namezip	add_valid_reverse_update_paramsbest_iterationrangeCallbackEnvupdateextend
eval_train
eval_validEarlyStopException
best_scorer   r   model_from_stringmodel_to_stringfree_dataset)#r$   r@   rA   rB   rC   rD   rE   rF   rG   i
valid_itemrr   rP   	predictorinit_iterationis_valid_contain_traintrain_data_namereduced_valid_setsname_valid_sets
valid_datacallbacks_setrf   callbacks_before_iter_setcallbacks_after_iter_setcallbacks_before_itercallbacks_after_iterrU   	valid_setname_valid_setrp   earlyStopExceptiondataset_name	eval_namescore_s#                                      r+   r"   r"   m   s   l i)) rpTXYbTcTcTlpppqqq*d## &z22 	 	MAzj'22 HH H*.z*:*:*CH H H   ]6""F #  F
 59D{#$$ %k"${#/RXYYYF-.O!dRadddeee !.  F
 $%-

)***

#6>>+/I*sDk** w#3zZ`aaa			J	(	( w#0TXYcYjTuTuntTuTuvvv	"4466V$$33I>>>" OOj'** 	&$Jk3'' 	(&-K&z22 	5 	5MAzY&&)-&*&1!nO%%j&?&?&G&G&U&UV_&`&`aaa&3{+;+;a+?+?&&{1~6666&&|||4444y)) 	@ 	@EArK""7AI,>????I-fjj9OQR.S.STT 
# &'= >"3 **%?EE+$/!"#   #k""	
 
 
	
 	
 	
 !g fm f f f,/HH"#<*WBUBUVVV!":
7@S@STTT	/9===! 	9''888),-?)Q)Q 	9 	9%I~i8888	9 	((***+ 	/ 	/I,,....	/ 	((***+ 	/ 	/I,,....	/G >>O#CDD $ $' 
	 
	BB$!!$2"0?"B+/  	 	 	 	 	D!!!JL!% I&--g.@.@.G.GHHH"))'*<*<U*C*CDDD	* 
 
(%%"#(6&4&F/E  	 	 	 	
 * 	 	 	%7%F%JG"%7%B"EEEEE	 %[11G-C < <)i6;<(33  L!!'"9"9";";<<IIKKKNs%   :AR= =/S,#+WW?W::W?c                   z   e Zd ZdZ	 ddeeeef                  fdZde	ee
f         ddfdZdee         d	ed
ede	ee
f         fdZdedee
e
gee
         f         fdZde	ee
f         fdZde	ee
f         ddfdZdedd fdZ	 	 	 ddee         d	ed
edefdZ	 	 	 ddeeef         dee         d	ed
edd f
dZdS )r!   aK  CVBooster in LightGBM.

    Auxiliary data structure to hold and redirect all boosters of ``cv()`` function.
    This class has the same methods as Booster class.
    All method calls, except for the following methods, are actually performed for underlying Boosters and
    then all returned results are returned in a list.

    - ``model_from_string()``
    - ``model_to_string()``
    - ``save_model()``

    Attributes
    ----------
    boosters : list of Booster
        The list of underlying fitted models.
    best_iteration : int
        The best iteration of fitted model.
    NrR   c                     g | _         d| _        |Rt          |d          5 }|                     t	          j        |                     ddd           dS # 1 swxY w Y   dS dS )zInitialize the CVBooster.

        Parameters
        ----------
        model_file : str, pathlib.Path or None, optional (default=None)
            Path to the CVBooster model file.
        Nr)boostersr   open
_from_dictjsonload)selfrR   files      r+   __init__zCVBooster.__init__v  s     (* !j#&& 1$	$0001 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 "!s   (AAAmodelsr%   c                     |d         | _         g | _        |d         D ]*}| j                            t          |                     +dS )zLoad CVBooster from dict.r   r   )	model_strN)r   r   r   r   )r   r   r   s      r+   r   zCVBooster._from_dict  sY    $%56
+ 	? 	?IM  9!=!=!=>>>>	? 	?r-   num_iterationstart_iterationimportance_typec                     g }| j         D ]-}|                    |                    |||                     .|| j        dS )zSerialize CVBooster to dict.)r   r   r   )r   r   )r   r   r   r   )r   r   r   r   
models_strrU   s         r+   _to_dictzCVBooster._to_dict  sh    
} 	 	G''"/bq (     
 '$:MNNNr-   namec                 X     dt           dt           dt          t                    f fd}|S )z#Redirect methods call of CVBooster.argskwargsr%   c                  r    g }j         D ]+}|                     t          |          | i |           ,|S )z>Call methods with each booster, and concatenate their results.)r   r   rd   )r   r   retrU   r   r   s       r+   handler_functionz/CVBooster.__getattr__.<locals>.handler_function  sO    C= D D

177D114B6BBCCCCJr-   )r   r   )r   r   r   s   `` r+   __getattr__zCVBooster.__getattr__  sH    	C 	3 	49 	 	 	 	 	 	 	  r-   c                      t          |           S N)vars)r   s    r+   __getstate__zCVBooster.__getstate__  s    Dzzr-   statec                 J    t          |                               |           d S r   )r   r   )r   r   s     r+   __setstate__zCVBooster.__setstate__  s"    T

%     r-   r   c                 T    |                      t          j        |                     | S )zLoad CVBooster from a string.

        Parameters
        ----------
        model_str : str
            Model will be loaded from this string.

        Returns
        -------
        self : CVBooster
            Loaded CVBooster object.
        )r   r   loads)r   r   s     r+   r   zCVBooster.model_from_string  s%     	
9--...r-   r   splitc                 T    t          j        |                     |||                    S )a\  Save CVBooster to JSON string.

        Parameters
        ----------
        num_iteration : int or None, optional (default=None)
            Index of the iteration that should be saved.
            If None, if the best iteration exists, it is saved; otherwise, all iterations are saved.
            If <= 0, all iterations are saved.
        start_iteration : int, optional (default=0)
            Start index of the iteration that should be saved.
        importance_type : str, optional (default="split")
            What type of feature importance should be saved.
            If "split", result contains numbers of times the feature is used in a model.
            If "gain", result contains total gains of splits which use the feature.

        Returns
        -------
        str_repr : str
            JSON string representation of CVBooster.
        )r   dumpsr   )r   r   r   r   s       r+   r   zCVBooster.model_to_string  s$    4 z$--XXYYYr-   filenamec                     t          |d          5 }t          j        |                     |||          |           ddd           n# 1 swxY w Y   | S )a  Save CVBooster to a file as JSON text.

        Parameters
        ----------
        filename : str or pathlib.Path
            Filename to save CVBooster.
        num_iteration : int or None, optional (default=None)
            Index of the iteration that should be saved.
            If None, if the best iteration exists, it is saved; otherwise, all iterations are saved.
            If <= 0, all iterations are saved.
        start_iteration : int, optional (default=0)
            Start index of the iteration that should be saved.
        importance_type : str, optional (default="split")
            What type of feature importance should be saved.
            If "split", result contains numbers of times the feature is used in a model.
            If "gain", result contains total gains of splits which use the feature.

        Returns
        -------
        self : CVBooster
            Returns self.
        wN)r   r   dumpr   )r   r   r   r   r   r   s         r+   
save_modelzCVBooster.save_model  s    : (C   	\DIdmmM?OTTVZ[[[	\ 	\ 	\ 	\ 	\ 	\ 	\ 	\ 	\ 	\ 	\ 	\ 	\ 	\ 	\ s   +AAAr   )Nr   r   )rv   
__module____qualname____doc__r   r   r~   r   r   r	   r   r   intr   r   r   r   r   r   r   r   r   r(   r-   r+   r!   r!   b  s!        * 261 1U39-.1 1 1 1$?c3h ?D ? ? ? ?	Ohsm 	Oc 	O\_ 	Odhilnqiqdr 	O 	O 	O 	O
  
 #sT#Y1F(G 
  
  
  
 d38n    !$sCx. !T ! ! ! !3 ;    $ (, &	Z Z}Z Z 	Z
 
Z Z Z Z> (, &   T	"   }  	 
   
           r-   r!   	full_datafoldsnfoldseedfpreproc
stratifiedshuffleeval_train_metricc	                    |                                  } |                                 }	|t          |d          st          |d          st          d          t          |d          r|                                 }
|
Qt          j        |
t
          j                  }
t          j        t          t          |
                    |
          }n t          j        |	t
          j                  }|                    t          j        |	          |                                 |          }nt          fdt!          j        d	          D                       rt$          st'          d
          t          j        |                                 t
          j                  }
t          j        t          t          |
                    |
          }t)                    }|                    t          j        |	          |          }n|rdt$          st'          d          t+          ||          }|                    t          j        |	          |                                           }n|r3t
          j                            |                              |	          nt          j        |	          t5          |	z            fdt          d|	          D             fdt                    D             }t7          |          }t9                      }|D ]\  }}|                     t=          |                    }|                     t=          |                    }|$ |||                                          \  }}}n}tA          ||          }|r|!                    |d           |!                    |d           |j"        #                    |           |S )z2Make a n-fold list of Booster from random indices.N__iter__r   zyfolds should be a generator or iterator of (train_idx, test_idx) tuples or scikit-learn splitter object with split method)dtype)repeats)Xygroupsc              3   H   K   | ]}                     |d           dv V  dS ) >   xendcgxe_ndcg
lambdarankrank_xendcgxendcg_martxe_ndcg_martN)r6   )r)   	obj_aliasr$   s     r+   r5   z _make_n_folds.<locals>.<genexpr>  sP       
 
  JJy"%%`a
 
 
 
 
 
r-   rJ   z'scikit-learn is required for ranking cv)n_splits)r   r   z*scikit-learn is required for stratified cv)r   r   random_state)r   r   c                 *    g | ]}||z            S r(   r(   )r)   r   ksteprandidxs     r+   
<listcomp>z!_make_n_folds.<locals>.<listcomp>/  s&    QQQ!wq1u9}-QQQr-   r   c                 n    g | ]0t          j        fd t                    D                       1S )c                 ,    g | ]}|k    |         S r(   r(   )r)   r   ktest_ids     r+   r  z,_make_n_folds.<locals>.<listcomp>.<listcomp>0  s#    'S'S'SqAQRFF
FFFr-   )npconcatenater   )r)   r  r   r  s    @r+   r  z!_make_n_folds.<locals>.<listcomp>0  sC    kkkYZ'S'S'S'S'SE%LL'S'S'STTkkkr-   r"   valid)$	constructnum_datahasattrAttributeError	get_groupr  asarrayint32repeatr   r7   zerosr   empty	get_labelanyr   r6   r   r   r   r   randomRandomStatepermutationaranger   r   r!   subsetr   ry   r   r   r   r   )r   r   r   r$   r   r   r   r   r   r
  
group_infoflatted_groupgroup_kfoldskftrain_idr   	train_idxtest_idxr@   r   tparambooster_for_foldr   r   r  s     ``                  @@@r+   _make_n_foldsr#    s    ##%%I!!##Huj)) 	'%2I2I 	 D   5'"" 	e",,..J%Z
"(CCC
 "	%J*@*@* U U U " B B BKK"(8"4"4	8K8K8M8MVcKddE 
 
 
 
 ,/<<
 
 
 
 
 	+
 % O#$MNNNI$7$7$9$9JJJJIeC
OO&<&<jQQQM)5999K%%(:(:=%QQEE 	+$ R#$PQQQ&wUYZZZCII 2 2i6I6I6K6KILLEE .)//55AA(KK)H--5())EQQQQQuQ%7P7PQQQGkkkkk^cdi^j^jkkkH'**E
++C$ . .	8$$VI%6%677	$$VH%5%566	+38Iy&++--+X+X(Iy&&F"6955 	;&&y':::""9g666,----Jr-   raw_resultsc                    t                      t                      }| D ]F}|D ]A\  }}}}||f}||<   |                    |g            ||                             |           BGfd|                                D             S )z#Aggregate cross-validation results.c                     g | ]\\  }}|d          |d         t          t          j        |                    |         t          t          j        |                    f]S )r   r   )floatr  meanstd)r)   r  vmetric_typess      r+   r  z"_agg_cv_result.<locals>.<listcomp>`  sW    qqqSWSTVWQqT1Q4rwqzz**LOU26!99=M=MNqqqr-   )r   r   r   r;   )	r$  metric_values
one_resultr   metric_namemetric_valueis_higher_betterrj   r+  s	           @r+   _agg_cv_resultr1  D  s     1<L8CM! 4 4
IS 	4 	4EL+|5E-C 0L$$S"---#%%l3333		4 rqqq[h[n[n[p[pqqqqr-      Tmetricsreturn_cvboosterc                 (	   t          |t                    s%t          dt          |          j         d          t          j        |           } t          d| d          } d}t          | d                   r| d         }d| d<   t          ||           } | d         }|d	k    rt          d
| d          t          d| d          } | d         |                     d           |                     dd          }t          |	t          t          f          rt          j        |	|           }n>t          |	t"                    r't          j        |	t'          |	j        fi |           }nd}|2t+          j        d          D ]}|                     |d           || d<   |                    |                               |           t1          t2                    }t5          |||| ||
|||	  	        }|t7                      }nOt9          |          D ]0\  }}|j                            d|t?          |          z
             1t7          |          }tA          j!        |                     dd	                    rl|"                    tA          j#        | d         ||                     dd          t          d| d                              d          d	k                         d |D             }||z
  }tI          |tK          d                    }tI          |tK          d                    }tM          |          D ]7}|D ]%} |tA          j'        || |d	|d                     &|(                    |           tS          |*                    |                    }|D ]J\  }}}} }!|| d| d         +                    |           || d| d         +                    |!           K	 |D ]%} |tA          j'        || |d	||                     &# t@          j,        $ rM}"|"j-        dz   |_-        |j.        D ]}#|j-        |#_-        |D ]}$||$         d|j-                 ||$<   Y d}"~" nd}"~"ww xY w|r||d <   t'          |          S )!a  Perform the cross-validation with given parameters.

    Parameters
    ----------
    params : dict
        Parameters for training. Values passed through ``params`` take precedence over those
        supplied via arguments.
    train_set : Dataset
        Data to be trained on.
    num_boost_round : int, optional (default=100)
        Number of boosting iterations.
    folds : generator or iterator of (train_idx, test_idx) tuples, scikit-learn splitter object or None, optional (default=None)
        If generator or iterator, it should yield the train and test indices for each fold.
        If object, it should be one of the scikit-learn splitter classes
        (https://scikit-learn.org/stable/modules/classes.html#splitter-classes)
        and have ``split`` method.
        This argument has highest priority over other data split arguments.
    nfold : int, optional (default=5)
        Number of folds in CV.
    stratified : bool, optional (default=True)
        Whether to perform stratified sampling.
    shuffle : bool, optional (default=True)
        Whether to shuffle before splitting data.
    metrics : str, list of str, or None, optional (default=None)
        Evaluation metrics to be monitored while CV.
        If not None, the metric in ``params`` will be overridden.
    feval : callable, list of callable, or None, optional (default=None)
        Customized evaluation function.
        Each evaluation function should accept two parameters: preds, eval_data,
        and return (eval_name, eval_result, is_higher_better) or list of such tuples.

            preds : numpy 1-D array or numpy 2-D array (for multi-class task)
                The predicted values.
                For multi-class task, preds are numpy 2-D array of shape = [n_samples, n_classes].
                If custom objective function is used, predicted values are returned before any transformation,
                e.g. they are raw margin instead of probability of positive class for binary task in this case.
            eval_data : Dataset
                A ``Dataset`` to evaluate.
            eval_name : str
                The name of evaluation function (without whitespace).
            eval_result : float
                The eval result.
            is_higher_better : bool
                Is eval result higher better, e.g. AUC is ``is_higher_better``.

        To ignore the default metric corresponding to the used objective,
        set ``metrics`` to the string ``"None"``.
    init_model : str, pathlib.Path, Booster or None, optional (default=None)
        Filename of LightGBM model or Booster instance used for continue training.
    fpreproc : callable or None, optional (default=None)
        Preprocessing function that takes (dtrain, dtest, params)
        and returns transformed versions of those.
    seed : int, optional (default=0)
        Seed used to generate the folds (passed to numpy.random.seed).
    callbacks : list of callable, or None, optional (default=None)
        List of callback functions that are applied at each iteration.
        See Callbacks in Python API for more information.
    eval_train_metric : bool, optional (default=False)
        Whether to display the train metric in progress.
        The score of the metric is calculated again after each training step, so there is some impact on performance.
    return_cvbooster : bool, optional (default=False)
        Whether to return Booster models trained on each fold through ``CVBooster``.

    Note
    ----
    A custom objective function can be provided for the ``objective`` parameter.
    It should accept two parameters: preds, train_data and return (grad, hess).

        preds : numpy 1-D array or numpy 2-D array (for multi-class task)
            The predicted values.
            Predicted values are returned before any transformation,
            e.g. they are raw margin instead of probability of positive class for binary task.
        train_data : Dataset
            The training dataset.
        grad : numpy 1-D array or numpy 2-D array (for multi-class task)
            The value of the first order derivative (gradient) of the loss
            with respect to the elements of preds for each sample point.
        hess : numpy 1-D array or numpy 2-D array (for multi-class task)
            The value of the second order derivative (Hessian) of the loss
            with respect to the elements of preds for each sample point.

    For multi-class task, preds are numpy 2-D array of shape = [n_samples, n_classes],
    and grad and hess should be returned in the same format.

    Returns
    -------
    eval_results : dict
        History of evaluation results of each metric.
        The dictionary has the following format:
        {'valid metric1-mean': [values], 'valid metric1-stdv': [values],
        'valid metric2-mean': [values], 'valid metric2-stdv': [values],
        ...}.
        If ``return_cvbooster=True``, also returns trained boosters wrapped in a ``CVBooster`` object via ``cvbooster`` key.
        If ``eval_train_metric=True``, also returns the train metric history.
        In this case, the dictionary has the following format:
        {'train metric1-mean': [values], 'valid metric1-mean': [values],
        'train metric2-mean': [values], 'valid metric2-mean': [values],
        ...}.
    z6cv() only accepts Dataset object, train_set has type 'rI   rJ   Nr/   rK   rL   r.   r   rM   rN   rO   rP   FrQ   rT   metric)	r   r   r   r$   r   r   r   r   r   rX   rY   rZ   r[   r   r\   c                 4    h | ]}t          |d d          |S ra   rc   re   s     r+   rg   zcv.<locals>.<setcomp>,  rh   r-   ri   rk   rq    z-meanz-stdv	cvbooster)/rs   r   rt   ru   rv   ry   rz   r   r{   r>   r|   r}   r6   r~   r   r   r   r   r   r   r$   r   r   r   r   rw   r#  r8   rx   r   r   r7   r   r   r   r   r   r   r   r   r   r1  r   r   r   r   r   )%r$   r@   rA   r   r   r   r   r3  rD   rE   r   r   rG   r   r4  rr   rP   r   metric_aliasresultsr9  r   r   rf   r   r   r   r   resr   r.  metric_meanr   metric_std_devr   bstr  s%                                        r+   r    r    c  s   h i)) omQUV_Q`Q`Qimmmnnn]6""F #  F
 59D{#$$ %k"${#/RXYYYF-.O!dRadddeee !.  F
 $%-

)***

#6>>*sDk** #3!!
 
 
		 
J	(	( #0
 1<<V<<
 
 
		
 	*.x88 	+ 	+LJJ|T****"xV$$33I>>>$G+
 
 
I y)) 	@ 	@EArK""7AI,>????I-fjj9OQR.S.STT 
# &'= >"3 **%?EE+$/!"#   #k""	
 
 
	
 	
 	
 !g fm f f f,/HH"#<*WBUBUVVV!":
7@S@STTT?## # #' 
	 
	BB$#!$%"1+/  	 	 	 	 	d###Y11%8899IL 	Q 	QEL+{A~|88k8889@@MMM|88k8889@@PPPP	* 
 
('%"#()&5/2  	 	 	 	
 * 	 	 	'9'H1'LI$ ) > >%.%="" D D$QZ(B)*B(BC

EEEEE	  )(==s   6(PQ;.AQ66Q;)r?   NNNNFN)r?   Nr2  TTNNNNr   NFF)6r   ry   r   collectionsr   r   operatorr   pathlibr   typingr   r   r	   r
   r   r   r   r   numpyr  r   r   basicr   r   r   r   r   r   r   r   r   r   r   compatr   r   r   r   __all__ndarray_LGBM_CustomMetricFunctionr~   _LGBM_PreprocFunctionr   r>   boolr"   r!   r#  r1  r'  r    r(   r-   r+   <module>rL     s   1 1   0 0 0 0 0 0 0 0             N N N N N N N N N N N N N N N N N N N N                                    f e e e e e e e e e e e   #	W$	& 	W)*	,		  !gtCH~&	'7DcN
*+- 5# 5tCH~ 5RVWZ\_W_R` 5 5 5 5v *.'+[_6:"'*.r rcNrr r g'	r
 $s)$r E4d;U6VVWXr sD'123r  r X'r r r r rjV V V V V V V VrFFE(5RZ)?#@ACZZ[\F F cN	F
 F ,-F F F F F F F FRrd<=>r	
@Ar r r rD _c/3[_6:04*.#"v vcNvv v E(5RZ)?#@ACZZ[\	v
 v v v eCcN+,v E4d;U6VVWXv sD'123v ,-v v X'v v v  
#uT%[)+,
,-!v v v v v vr-   