a
    “ù»jÿ�  ã                   @   s¼  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,e-ee+ef ee+ef dœdd„Z.d!ee+ef ee-eee  eee+  eee*ee* f  eee+e	ef  e/eee  edœ
dd„Z0G dd„ dƒZ1eeeeeej)ej)f  e%f  e-ee+ef e-ee, e/e/e/e1dœ
dd„Z2eee  ee dœdd„Z3d"ee+ef ee-eeeeej)ej)f  e%f  e-e/e/eee+ee+ f  eee*ee* f  eee+e	ef  ee, e-eee  e/e/ee+eee4 e1f f dœd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_BoosterEvalMethodResultTypeÚ6_LGBM_BoosterEvalMethodResultWithStandardDeviationTypeÚ_LGBM_CustomObjectiveFunctionÚ_LGBM_EvalFunctionResultTypeÚ_log_warning)ÚSKLEARN_INSTALLEDÚ_LGBMBaseCrossValidatorÚ_LGBMGroupKFoldÚ_LGBMStratifiedKFold)ÚcvÚ	CVBoosterÚtrain)Únum_boost_round_kwargÚparamsÚreturnc                    s„   ‡ fdd„t  d¡D ƒ}tdˆ | d�‰ t|ƒdkr6ˆ S tt| ¡ ƒƒdkrNˆ S d 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                    s   i | ]}|ˆ v r|ˆ | “qS © r%   )Ú.0Úalias©r#   r%   ú5E:\soccer\ml_env\Lib\site-packages\lightgbm/engine.pyÚ
<dictcomp>M   s   z*_choose_num_iterations.<locals>.<dictcomp>Únum_iterations©Zmain_param_namer#   Údefault_valuer   z, c                 s   s    | ]\}}|› d |› �V  qdS )ú=Nr%   )r&   r'   Úvalr%   r%   r)   Ú	<genexpr>c   ó    z)_choose_num_iterations.<locals>.<genexpr>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#   Znum_iteration_configs_providedZvalue_stringr%   r(   r)   Ú_choose_num_iterations5   s&    
ÿýÿÿr8   éd   F)
r#   Ú	train_setÚnum_boost_roundÚ
valid_setsÚvalid_namesÚfevalÚ
init_modelÚkeep_training_boosterÚ	callbacksr$   c	           #      C   sº  t |tƒs tdt|ƒj› d�ƒ‚t |tƒrbt|ƒD ].\}	}
t |
tƒs2td|	› dt|
ƒj› d�ƒ‚q2t | ¡} t	d| dd�} d}t
| d ƒrš| d }d| d< t|| d	�} | d
 }|dkrÆtd|› d�ƒ‚t	d| dd�} | d du rê|  d¡ |  dd¡}d}t |ttfƒ�rtj|| d�}n(t |tƒ�rBtj|t|jfi | ¤Žd�}|du�rV| ¡ }nd}| | ¡ |¡ d}d}g }g }|du�r.t |tƒ�r–|g}t |tƒ�r¨|g}t|ƒD ]|\}	}||u �rÜd}|du�r°||	 }�q°| | | ¡ |¡¡ |du�rt|ƒ|	k�r| ||	 ¡ n| d|	› �¡ �q°|du �r@tƒ }n2t|ƒD ] \}	}|j d|	t|ƒ ¡ �qHt|ƒ}t  !|  dd¡¡�r¾| "t j#| d ||  dd¡t	d| dd� d¡dkd�¡ dd„ |D ƒ}|| }t$|t%dƒd�}t$|t%dƒd�}z^t| |d�}|�r| &|¡ t'||ƒD ]\}}| (||¡ �qW | )¡  |D ]}| )¡  �qBn| )¡  |D ]}| )¡  �q`0 d|_*t+||| ƒD ]ê}	|D ]$}|t j,|| |	||| dd �ƒ �qŽ|j-|d!� g }|du�rô|�rä| .| /|¡¡ | .| 0|¡¡ z.|D ]$}|t j,|| |	||| |d �ƒ �qúW nJ t j1�yl } z.|j*d |_*|j2}W Y d}~ �qrW Y d}~n
d}~0 0 �q†t3t4ƒ|_2|D ]\}} }!}"|!|j2| | < �q€|�s¶| 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©ÚboosterrL   ZtrainingTZvalid_ÚorderÚearly_stopping_min_deltaç        Ú	verbosityr   ©Zstopping_roundsrI   Z	min_deltaÚverbosec                 S   s   h | ]}t |d dƒr|’qS ©Zbefore_iterationF©Úgetattr©r&   Úcbr%   r%   r)   Ú	<setcomp>"  r1   ztrain.<locals>.<setcomp>©Úkey)r#   r:   ©Úmodelr#   Ú	iterationZbegin_iterationZend_iterationÚevaluation_result_list©Úfobj)8Ú
isinstancer   Ú	TypeErrorÚtypeÚ__name__ÚlistÚ	enumerateÚcopyÚdeepcopyr   Úcallabler8   Ú
ValueErrorÚpopr2   Ústrr   r   Úfrom_model_filer   Úfrom_boosterÚdictr#   Zcurrent_iterationÚ_update_paramsÚ_set_predictorÚappendZset_referencer3   r4   Ú__dict__Ú
setdefaultr   Ú_should_enable_early_stoppingÚaddÚearly_stoppingÚsortedr   Zset_train_data_nameÚzipÚ	add_validZ_reverse_update_paramsÚbest_iterationÚrangeÚCallbackEnvÚupdateÚextendZ
eval_trainÚ
eval_validÚEarlyStopExceptionZ
best_scorer   r   Úmodel_from_stringÚmodel_to_stringZfree_dataset)#r#   r:   r;   r<   r=   r>   r?   r@   rA   ÚiZ
valid_itemrb   rI   Ú	predictorZinit_iterationZis_valid_contain_trainZtrain_data_nameZreduced_valid_setsZname_valid_setsZ
valid_dataÚcallbacks_setrY   Úcallbacks_before_iter_setÚcallbacks_after_iter_setÚcallbacks_before_iterÚcallbacks_after_iterrN   Ú	valid_setZname_valid_setr`   ÚearlyStopExceptionÚdataset_nameZ	eval_nameZscoreÚ_r%   r%   r)   r!   m   s   V


ÿÿÿ
ýý







ýüûüÿ
þúÿ
úÿ
*
r!   c                   @   s   e Zd ZdZdeeeef  dœdd„Ze	ee
f ddœdd„Zee eee	ee
f d	œd
d„Zeee
e
gee
 f dœdd„Ze	ee
f dœdd„Ze	ee
f ddœdd„Zed dœdd„Zd ee eeed	œdd„Zd!eeef ee eed dœd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.
    N)rK   c                 C   sR   g | _ d| _|durNt|dƒ� }|  t |¡¡ W d  ƒ n1 sD0    Y  dS )z¿Initialize 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)ÚselfrK   Úfiler%   r%   r)   Ú__init__v  s
    zCVBooster.__init__)Úmodelsr$   c                 C   s4   |d | _ g | _|d D ]}| j t|d�¡ qdS )zLoad CVBooster from dict.r}   r“   )Ú	model_strN)r}   r“   rt   r   )r˜   r›   rœ   r%   r%   r)   r•   ˆ  s    
zCVBooster._from_dict)Únum_iterationÚstart_iterationÚimportance_typer$   c                 C   s2   g }| j D ]}| |j|||d�¡ q
|| jdœS )zSerialize CVBooster to dict.)r�   rž   rŸ   )r“   r}   )r“   rt   r…   r}   )r˜   r�   rž   rŸ   Z
models_strrN   r%   r%   r)   Ú_to_dict�  s    
ÿÿzCVBooster._to_dict)Únamer$   c                    s    t t tt  dœ‡ ‡fdd„}|S )z#Redirect methods call of CVBooster.)ÚargsÚkwargsr$   c                     s.   g }ˆj D ]}| t|ˆ ƒ| i |¤Ž¡ q
|S )z>Call methods with each booster, and concatenate their results.)r“   rt   rW   )r¢   r£   ÚretrN   ©r¡   r˜   r%   r)   Úhandler_function�  s    
z/CVBooster.__getattr__.<locals>.handler_function)r   r
   )r˜   r¡   r¦   r%   r¥   r)   Ú__getattr__š  s    zCVBooster.__getattr__)r$   c                 C   s   t | ƒS ©N)Úvars)r˜   r%   r%   r)   Ú__getstate__¦  s    zCVBooster.__getstate__)Ústater$   c                 C   s   t | ƒ |¡ d S r¨   )r©   r€   )r˜   r«   r%   r%   r)   Ú__setstate__©  s    zCVBooster.__setstate__)rœ   r$   c                 C   s   |   t |¡¡ | S )z÷Load 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œ   r%   r%   r)   r„   ¬  s    zCVBooster.model_from_stringr   Úsplitc                 C   s   t  |  |||¡¡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Ÿ   r%   r%   r)   r…   ¼  s    zCVBooster.model_to_string)Úfilenamer�   rž   rŸ   r$   c                 C   sD   t |dƒ�&}t |  |||¡|¡ W d  ƒ n1 s60    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™   r%   r%   r)   Ú
save_modelØ  s    4zCVBooster.save_model)N)Nr   r®   )Nr   r®   )rf   Ú
__module__Ú__qualname__Ú__doc__r   r   rn   r   rš   r   r   r•   Úintr    r   r
   r§   rª   r¬   r„   r…   r³   r%   r%   r%   r)   r    b  s<    þþ     üû   û
úr    )
Ú	full_dataÚfoldsÚnfoldr#   ÚseedÚfpreprocÚ
stratifiedÚshuffleÚeval_train_metricr$   c	                    sR  |   ¡ } |  ¡ }	|dur¤t|dƒs4t|dƒs4tdƒ‚t|dƒr |  ¡ }
|
durvtj|
tjd�}
tjt	t
|
ƒƒ|
d�}ntj|	tjd�}|jt |	¡|  ¡ |d�}�nt‡fdd	„t d
¡D ƒƒ�rtsÎtdƒ‚tj|  ¡ tjd�}
tjt	t
|
ƒƒ|
d�}tˆd�}|jt |	¡|d�}nª|�rTt�s,tdƒ‚tˆ||d�}|jt |	¡|  ¡ d�}nn|�rntj |¡ |	¡‰n
t |	¡‰t|	ˆ ƒ‰ ‡ ‡fdd„t	d|	ˆ ƒD ƒ‰‡‡fdd„t	ˆƒD ƒ}t|ˆƒ}tƒ }|D ]€\}}|  t|ƒ¡}|  t|ƒ¡}|du�r|||ˆ ¡ ƒ\}}}nˆ}t ||ƒ}|�r2| !|d¡ | !|d¡ |j" #|¡ �qÌ|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)Zdtype)Zrepeats)ÚXÚyÚgroupsc                 3   s   | ]}ˆ   |d ¡dv V  qdS )Ú >   Z
lambdarankZxendcg_martZxe_ndcgZxe_ndcg_martZrank_xendcgZxendcgN)r2   )r&   Z	obj_aliasr(   r%   r)   r0     s   þ
ÿz _make_n_folds.<locals>.<genexpr>rC   z'scikit-learn is required for ranking cv)Ún_splits)rÁ   rÃ   z*scikit-learn is required for stratified cv)rÅ   r¾   Zrandom_state)rÁ   rÂ   c                    s   g | ]}ˆ||ˆ  … ‘qS r%   r%   ©r&   r†   )ÚkstepÚrandidxr%   r)   Ú
<listcomp>/  r1   z!_make_n_folds.<locals>.<listcomp>r   c                    s*   g | ]"‰ t  ‡ ‡fd d„tˆƒD ƒ¡‘qS )c                    s   g | ]}ˆ |krˆ| ‘qS r%   r%   rÆ   )ÚkÚtest_idr%   r)   rÉ   0  r1   z,_make_n_folds.<locals>.<listcomp>.<listcomp>)ÚnpZconcatenater~   )r&   )rº   rË   )rÊ   r)   rÉ   0  r1   r!   Zvalid)$Z	constructÚnum_dataÚhasattrÚAttributeErrorZ	get_grouprÌ   ZasarrayZint32Úrepeatr~   r3   Zzerosr®   ÚemptyZ	get_labelÚanyr   r2   r   r   r   r   ÚrandomZRandomStateZpermutationZaranger·   r{   r    Zsubsetrz   ri   r   r|   r“   rt   )r¸   r¹   rº   r#   r»   r¼   r½   r¾   r¿   rÍ   Z
group_infoZflatted_groupZgroup_kfoldZskfZtrain_idr¤   Z	train_idxZtest_idxr:   r�   ZtparamZbooster_for_foldr%   )rÇ   rº   r#   rÈ   rË   r)   Ú_make_n_foldsû  s`    ÿ
ý





rÔ   )Úraw_resultsr$   c                    sh   t ƒ ‰ t ƒ }| D ]@}|D ]6\}}}}||f}|ˆ |< | |g ¡ ||  |¡ qq‡ fdd„| ¡ D ƒS )z#Aggregate cross-validation results.c              
      s>   g | ]6\}}|d  |d t t |¡ƒˆ | t t |¡ƒf‘qS )r   r   )ÚfloatrÌ   ÚmeanZstd)r&   rÊ   Úv©Zmetric_typesr%   r)   rÉ   `  r1   z"_agg_cv_result.<locals>.<listcomp>)r   rv   rt   r7   )rÕ   Zmetric_valuesZ
one_resultr�   Úmetric_nameZmetric_valueZis_higher_betterr\   r%   rÙ   r)   Ú_agg_cv_resultD  s    rÛ   é   T)r#   r:   r;   r¹   rº   r½   r¾   Úmetricsr>   r?   r¼   r»   rA   r¿   Úreturn_cvboosterr$   c           %      C   s€  t |tƒs tdt|ƒj› d�ƒ‚t | ¡} td| dd�} d}t| d ƒrX| d }d| d< t	|| d�} | d }|d	kr„t
d
|› d�ƒ‚td| dd�} | d du r¨|  d¡ |  dd¡}t |	ttfƒrÒtj|	| d�}n,t |	tƒrútj|	t|	jfi | ¤Žd�}nd}|du�r.t d¡D ]}|  |d¡ �q|| d< | | ¡ |¡ ttƒ}t|||| ||
|||d�	}|du �rrtƒ }n2t|ƒD ] \}}|j d|t|ƒ ¡ �qzt|ƒ}t  !|  dd	¡¡�rð| "t j#| d ||  dd¡td| dd� d¡d	kd�¡ dd„ |D ƒ}|| }t$|t%dƒd�}t$|t%dƒd�}t&|ƒD �]8}|D ] }|t j'|| |d	|dd�ƒ �q8|j(|d� t)| *|¡ƒ}|D ]D\}}}} }!||› d|› d�  +|¡ ||› d|› d �  +|!¡ �qxz*|D ] }|t j'|| |d	||d�ƒ �qÄW n| t j,�yd }" z`|"j-d |_-|j.D ]}#|j-|#_-�q|D ]}$||$ d|j-… ||$< �q"W Y d}"~" �qjW Y d}"~"n
d}"~"0 0 �q.|�rx||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 'rB   rC   Nr,   rD   rE   r+   r   rF   rG   rH   rI   FrJ   rM   Zmetric)	r¸   r¹   rº   r#   r»   r¼   r½   r¾   r¿   rO   rP   rQ   rR   r   rS   c                 S   s   h | ]}t |d dƒr|’qS rU   rV   rX   r%   r%   r)   rZ   ,  r1   zcv.<locals>.<setcomp>r[   r]   ra   ú z-meanz-stdvÚ	cvbooster)/rc   r   rd   re   rf   ri   rj   r   rk   r8   rl   rm   r2   rn   r   r   ro   r   rp   rq   r#   r   rr   rs   r   rg   rÔ   r4   rh   ru   rv   r3   r   rw   rx   ry   rz   r   r~   r   r€   rÛ   r‚   rt   rƒ   r}   r“   )%r#   r:   r;   r¹   rº   r½   r¾   rÝ   r>   r?   r¼   r»   rA   r¿   rÞ   rb   rI   r‡   Zmetric_aliasÚresultsrà   rˆ   r†   rY   r‰   rŠ   r‹   rŒ   Úresr�   rÚ   Zmetric_meanr�   Zmetric_std_devrŽ   ÚbstrÊ   r%   r%   r)   r   c  sê    t

ýý
þ
þ
÷

ýüûüÿúÿ
úÿ

*r   )r9   NNNNFN)r9   NrÜ   TTNNNNr   NFF)6r¶   ri   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__ZndarrayZ_LGBM_CustomMetricFunctionrn   Z_LGBM_PreprocFunctionr·   r8   Úboolr!   r    rÔ   rÛ   rÖ   r   r%   r%   r%   r)   Ú<module>   sÂ   (4ÿÿÿÿüÿÿÿ";       ÷



ö v 
öJ
þ"             ñ

ð