
    ^j3Z                       d Z ddlZddl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 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$m%Z%m&Z&m'Z'm(Z(m)Z)m*Z*m+Z+m,Z, ddl-m.Z.m/Z/ dd	l0m1Z1m2Z2m3Z3m4Z4m5Z5m6Z6m7Z7m8Z8m9Z9m:Z:m;Z;m<Z<m=Z=m>Z>m?Z? dd
l@mAZA erddl0mBZB g dZCeeeeeD   eeE   f      ej                  e?ej                  ej                  j                  f   ZJee
eej                     ej                  geej                  ej                  f   f   e
eej                     ej                  eej                     geej                  ej                  f   f   e
eej                     ej                  eej                     eej                     geej                  ej                  f   f   f   ZKee
eej                     ej                  ge%f   e
eej                     ej                  gee%   f   e
eej                     ej                  eej                     ge%f   e
eej                     ej                  eej                     gee%   f   e
eej                     ej                  eej                     eej                     ge%f   e
eej                     ej                  eej                     eej                     gee%   f   f   ZLeeMeLeeeMeLf      f   ZNeeJe)f   ZOdedeej                     fdZPdedej                  fdZQdedeej                     fdZR G d d      ZS G d d      ZTdZUdZVdZWdeeee	e	f   ee	   f      deMdeEdee	   fdZXdeeeO      deeeJeeJ   f      deee)ee)   f      deeeO      fd ZY G d! d"e;      ZZ G d# d$e<eZ      Z[ G d% d&e7eZ      Z\ G d' d(eZ      Z]y))z,Scikit-learn wrapper interface for LightGBM.    N)	signature)Path)TYPE_CHECKINGAnyCallableDictListOptionalTupleUnion   )_MULTICLASS_OBJECTIVESBoosterDatasetLGBMDeprecationWarningLightGBMError_choose_param_value_ConfigAliases_LGBM_BoosterBestScoreType%_LGBM_CategoricalFeatureConfiguration_LGBM_EvalFunctionResultType_LGBM_FeatureNameConfiguration_LGBM_GroupType_LGBM_InitScoreType_LGBM_LabelType_LGBM_PredictReturnType_LGBM_WeightType_log_warning)_EvalResultDictrecord_evaluation)6SKLEARN_CHECK_SAMPLE_WEIGHT_HAS_ALLOW_ZERO_WEIGHTS_ARGSKLEARN_INSTALLEDLGBMNotFittedError_LGBMAssertAllFinite_LGBMCheckClassificationTargets_LGBMCheckSampleWeight_LGBMClassifierBase_LGBMComputeSampleWeight_LGBMCpuCount_LGBMLabelEncoder_LGBMModelBase_LGBMRegressorBase_LGBMValidateData_sklearn_versionpd_DataFrame)train)_sklearn_Tags)LGBMClassifier	LGBMModel
LGBMRankerLGBMRegressordatasetreturnc                 p    | j                         }d}|!t        |t        j                        sJ |       |S )NzEstimators in lightgbm.sklearn should only retrieve query groups from a constructed Dataset. If you're seeing this message, it's a bug in lightgbm. Please report it at https://github.com/lightgbm-org/LightGBM/issues.)	get_group
isinstancenpndarray)r6   group	error_msgs      [/var/www/ramen.bs-engineer-server.com/venv/lib/python3.12/site-packages/lightgbm/sklearn.py#_get_group_from_constructed_datasetr@      s?    E	F  =Jubjj9D9D9L    c                 l    | j                         }d}t        |t        j                        sJ |       |S )NzEstimators in lightgbm.sklearn should only retrieve labels from a constructed Dataset. If you're seeing this message, it's a bug in lightgbm. Please report it at https://github.com/lightgbm-org/LightGBM/issues.)	get_labelr:   r;   r<   )r6   labelr>   s      r?   #_get_label_from_constructed_datasetrE      s;    E	F  eRZZ(3)3(LrA   c                 p    | j                         }d}|!t        |t        j                        sJ |       |S )NzEstimators in lightgbm.sklearn should only retrieve weights from a constructed Dataset. If you're seeing this message, it's a bug in lightgbm. Please report it at https://github.com/lightgbm-org/LightGBM/issues.)
get_weightr:   r;   r<   )r6   weightr>   s      r?   $_get_weight_from_constructed_datasetrI      s?    !F	F  >Z

;FYF;MrA   c                   v    e Zd ZdZdefdZdej                  dede	ej                  ej                  f   fdZ
y)	_ObjectiveFunctionWrapperz#Proxy class for objective function.funcc                     || _         y)aJ	  Construct a proxy class.

        This class transforms objective function to match objective function with signature ``new_func(preds, dataset)``
        as expected by ``lightgbm.engine.train``.

        Parameters
        ----------
        func : callable
            Expects a callable with following signatures:
            ``func(y_true, y_pred)``,
            ``func(y_true, y_pred, weight)``
            or ``func(y_true, y_pred, weight, group)``
            and returns (grad, hess):

                y_true : numpy 1-D array of shape = [n_samples]
                    The target values.
                y_pred : numpy 1-D array of shape = [n_samples] or numpy 2-D array of shape = [n_samples, n_classes] (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.
                weight : numpy 1-D array of shape = [n_samples]
                    The weight of samples. Weights should be non-negative.
                group : numpy 1-D array
                    Group/query data.
                    Only used in the learning-to-rank task.
                    sum(group) = n_samples.
                    For example, if you have a 100-document dataset with ``group = [10, 20, 40, 10, 10, 10]``, that means that you have 6 groups,
                    where the first 10 records are in the first group, records 11-30 are in the second group, records 31-70 are in the third group, etc.
                grad : numpy 1-D array of shape = [n_samples] or numpy 2-D array of shape [n_samples, n_classes] (for multi-class task)
                    The value of the first order derivative (gradient) of the loss
                    with respect to the elements of y_pred for each sample point.
                hess : numpy 1-D array of shape = [n_samples] or numpy 2-D array of shape = [n_samples, n_classes] (for multi-class task)
                    The value of the second order derivative (Hessian) of the loss
                    with respect to the elements of y_pred for each sample point.

        .. note::

            For multi-class task, y_pred is a numpy 2-D array of shape = [n_samples, n_classes],
            and grad and hess should be returned in the same format.
        NrL   selfrL   s     r?   __init__z"_ObjectiveFunctionWrapper.__init__   s    R 	rA   predsr6   r7   c                 \   t        |      }t        t        | j                        j                        }|dk(  r| j                  ||      \  }}||fS t        |      }|dk(  r| j                  |||      \  }}||fS |dk(  rt        |      }| j                  ||||      S t        d|       )a  Call passed function with appropriate arguments.

        Parameters
        ----------
        preds : numpy 1-D array of shape = [n_samples] or numpy 2-D array of shape = [n_samples, n_classes] (for multi-class task)
            The predicted values.
        dataset : Dataset
            The training dataset.

        Returns
        -------
        grad : numpy 1-D array of shape = [n_samples] or numpy 2-D array of shape = [n_samples, n_classes] (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 of shape = [n_samples] or numpy 2-D array of shape = [n_samples, n_classes] (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.
                 zESelf-defined objective function should have 2, 3 or 4 arguments, got rE   lenr   rL   
parametersrI   r@   	TypeError)	rP   rR   r6   labelsargcgradhessrH   r=   s	            r?   __call__z"_ObjectiveFunctionWrapper.__call__   s    . 5W=9TYY'22319651JD$:5g>1965&9JD$:197@E99VUFE::_`d_efggrA   N)__name__
__module____qualname____doc__#_LGBM_ScikitCustomObjectiveFunctionrQ   r;   r<   r   r   r_    rA   r?   rK   rK      sN    -)@ )V&hzz&h &h 
rzz2::%	&	&hrA   rK   c            	       T    e Zd ZdZdefdZdej                  dede	e
ee
   f   fdZy)	_EvalFunctionWrapperz$Proxy class for evaluation function.rL   c                     || _         y)a	  Construct a proxy class.

        This class transforms evaluation function to match evaluation function with signature ``new_func(preds, dataset)``
        as expected by ``lightgbm.engine.train``.

        Parameters
        ----------
        func : callable
            Expects a callable with following signatures:
            ``func(y_true, y_pred)``,
            ``func(y_true, y_pred, weight)``
            or ``func(y_true, y_pred, weight, group)``
            and returns (metric_name, metric_value, maximize) or
            list of (metric_name, metric_value, maximize):

                y_true : numpy 1-D array of shape = [n_samples]
                    The target values.
                y_pred : numpy 1-D array of shape = [n_samples] or numpy 2-D array shape = [n_samples, n_classes] (for multi-class task)
                    The predicted values.
                    In case of custom ``objective``, 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.
                weight : numpy 1-D array of shape = [n_samples]
                    The weight of samples. Weights should be non-negative.
                group : numpy 1-D array
                    Group/query data.
                    Only used in the learning-to-rank task.
                    sum(group) = n_samples.
                    For example, if you have a 100-document dataset with ``group = [10, 20, 40, 10, 10, 10]``, that means that you have 6 groups,
                    where the first 10 records are in the first group, records 11-30 are in the second group, records 31-70 are in the third group, etc.
                metric_name : str
                    Unique identifier for the metric (e.g. "custom_adjusted_mse").
                metric_value : float
                    Value of the evaluation metric.
                maximize : bool
                    Are higher values better? e.g. ``True`` for AUC and ``False`` for binary error.
        NrN   rO   s     r?   rQ   z_EvalFunctionWrapper.__init__   s    J 	rA   rR   r6   r7   c                 @   t        |      }t        t        | j                        j                        }|dk(  r| j                  ||      S t        |      }|dk(  r| j                  |||      S |dk(  rt        |      }| j                  ||||      S t        d|       )a  Call passed function with appropriate arguments.

        Parameters
        ----------
        preds : numpy 1-D array of shape = [n_samples] or numpy 2-D array of shape = [n_samples, n_classes] (for multi-class task)
            The predicted values.
        dataset : Dataset
            The training dataset.

        Returns
        -------
        metric_name : str
            Unique identifier for the metric (e.g. "custom_adjusted_mse").
        metric_value : float
            Value of the evaluation metric.
        maximize : bool
            Are higher values better? e.g. ``True`` for AUC and ``False`` for binary error.
        rT   rU   rV   z@Self-defined eval function should have 2, 3 or 4 arguments, got rW   )rP   rR   r6   r[   r\   rH   r=   s          r?   r_   z_EvalFunctionWrapper.__call__  s    . 5W=9TYY'2231999VU++5g>1999VUF33197@E99VUFE::Z[_Z`abbrA   N)r`   ra   rb   rc   _LGBM_ScikitCustomEvalFunctionrQ   r;   r<   r   r   r   r	   r_   re   rA   r?   rg   rg      sM    .%; %N$czz$c $c 
+T2N-OO	P	$crA   rg   a  
    Build a gradient boosting model from the training set (X, y).

    Parameters
    ----------
    X : {X_shape}
        Input feature matrix.

        .. versionadded:: 4.2.0
            Support for ``pyarrow`` inputs

        .. versionadded:: 4.7.0
            Support for ``polars`` inputs

    y : {y_shape}
        The target values (class labels in classification, real numbers in regression).

        .. versionadded:: 4.2.0
            Support for ``pyarrow`` inputs

        .. versionadded:: 4.7.0
            Support for ``polars`` inputs

    sample_weight : {sample_weight_shape}
        Weights of training data. Weights should be non-negative.

        .. versionadded:: 4.2.0
            Support for ``pyarrow`` inputs

        .. versionadded:: 4.7.0
            Support for ``polars`` inputs

    init_score : {init_score_shape}
        Init score of training data.

        .. versionadded:: 4.2.0
            Support for ``pyarrow`` inputs

        .. versionadded:: 4.7.0
            Support for ``polars`` inputs

    group : {group_shape}
        Group/query data.
        Only used in the learning-to-rank task.
        sum(group) = n_samples.
        For example, if you have a 100-document dataset with ``group = [10, 20, 40, 10, 10, 10]``, that means that you have 6 groups,
        where the first 10 records are in the first group, records 11-30 are in the second group, records 31-70 are in the third group, etc.

        .. versionadded:: 4.2.0
            Support for ``pyarrow`` inputs

        .. versionadded:: 4.7.0
            Support for ``polars`` inputs

    eval_set : list or None, optional (default=None)
        .. deprecated:: 4.7.0
            A list of (X, y) tuple pairs to use as validation sets.
            Use ``eval_X`` and ``eval_y`` instead.
    eval_names : list of str, or None, optional (default=None)
        Unique identifiers for each evaluation dataset.
        Should be the same length as ``eval_set`` / ``eval_X``.
    eval_sample_weight : {eval_sample_weight_shape}
        Weights of eval data. Weights should be non-negative.
    eval_class_weight : list or None, optional (default=None)
        Class weights of eval data.
    eval_init_score : {eval_init_score_shape}
        Init score of eval data.
    eval_group : {eval_group_shape}
        Group data of eval data.
    eval_metric : str, callable, list or None, optional (default=None)
        If str, it should be a built-in evaluation metric to use.
        If callable, it should be a custom evaluation metric, see note below for more details.
        If list, it can be a list of built-in metrics, a list of custom evaluation metrics, or a mix of both.
        In either case, the ``metric`` from the model parameters will be evaluated and used as well.
        Default: 'l2' for LGBMRegressor, 'logloss' for LGBMClassifier, 'ndcg' for LGBMRanker.
    feature_name : list of str, or 'auto', optional (default='auto')
        Feature names.
        If 'auto' and data is pandas DataFrame, data columns names are used.
    categorical_feature : list of str or int, or 'auto', optional (default='auto')
        Categorical features.
        If list of int, interpreted as indices.
        If list of str, interpreted as feature names (need to specify ``feature_name`` as well).
        If 'auto' and data is pandas DataFrame, pandas unordered categorical columns are used.
        All values in categorical features will be cast to int32 and thus should be less than int32 max value (2147483647).
        Large values could be memory consuming. Consider using consecutive integers starting from zero.
        All negative values in categorical features will be treated as missing values.
        The output cannot be monotonically constrained with respect to a categorical feature.
        Floating point numbers in categorical features will be rounded towards 0.
    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.
    init_model : str, pathlib.Path, Booster, LGBMModel or None, optional (default=None)
        Filename of LightGBM model, Booster instance or LGBMModel instance used for continue training.
    eval_X : {X_shape}, or tuple of such inputs, or None, optional (default=None)
        Feature matrix or tuple thereof, e.g. ``(X_val0, X_val1)``, to use as validation sets.

        .. versionadded:: 4.7.0

    eval_y : {y_shape}, or tuple of such inputs, or None, optional (default=None)
        Target values or tuple thereof, e.g. ``(y_val0, y_val1)``, to use as validation sets.

        .. versionadded:: 4.7.0

    Returns
    -------
    self : LGBMModel
        Returns self.
    aR  
    Note
    ----
    Custom eval function expects a callable with following signatures:
    ``func(y_true, y_pred)``, ``func(y_true, y_pred, weight)`` or
    ``func(y_true, y_pred, weight, group)``
    and returns (metric_name, metric_value, maximize) or
    list of (metric_name, metric_value, maximize):

        y_true : numpy 1-D array of shape = [n_samples]
            The target values.
        y_pred : numpy 1-D array of shape = [n_samples] or numpy 2-D array of shape = [n_samples, n_classes] (for multi-class task)
            The predicted values.
            In case of custom ``objective``, 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.
        weight : numpy 1-D array of shape = [n_samples]
            The weight of samples. Weights should be non-negative.
        group : numpy 1-D array
            Group/query data.
            Only used in the learning-to-rank task.
            sum(group) = n_samples.
            For example, if you have a 100-document dataset with ``group = [10, 20, 40, 10, 10, 10]``, that means that you have 6 groups,
            where the first 10 records are in the first group, records 11-30 are in the second group, records 31-70 are in the third group, etc.
        metric_name : str
            Unique identifier for the metric (e.g. "custom_adjusted_mse").
        metric_value : float
            Value of the evaluation metric.
        maximize : bool
            Are higher values better? e.g. ``True`` for AUC and ``False`` for binary error.
a_  
    {description}

    Parameters
    ----------
    X : {X_shape}
        Input features matrix.
    raw_score : bool, optional (default=False)
        Whether to predict raw scores.
    start_iteration : int, optional (default=0)
        Start index of the iteration to predict.
        If <= 0, starts from the first iteration.
    num_iteration : int or None, optional (default=None)
        Total number of iterations used in the prediction.
        If None, if the best iteration exists and start_iteration <= 0, the best iteration is used;
        otherwise, all iterations from ``start_iteration`` are used (no limits).
        If <= 0, all iterations from ``start_iteration`` are used (no limits).
    pred_leaf : bool, optional (default=False)
        Whether to predict leaf index.
    pred_contrib : bool, optional (default=False)
        Whether to predict feature contributions.

        .. note::

            If you want to get more explanations for your model's predictions using SHAP values,
            like SHAP interaction values,
            you can install the shap package (https://github.com/slundberg/shap).
            Note that unlike the shap package, with ``pred_contrib`` we return a matrix with an extra
            column, where the last column is the expected value.

    validate_features : bool, optional (default=False)
        If True, ensure that the features used to predict match the ones used to train.
        Used only if data is pandas DataFrame.
    **kwargs
        Other parameters for the prediction.

    Returns
    -------
    {output_name} : {predicted_result_shape}
        The predicted values.
    X_leaves : {X_leaves_shape}
        If ``pred_leaf=True``, the predicted leaf of every tree for each sample.
    X_SHAP_values : {X_SHAP_values_shape}
        If ``pred_contrib=True``, the feature contributions for each sample.
    
collectionnameic                     | yt        | t              rt        |       |kD  r| |   S yt        | t              r| j	                  |d      S t        | d      )z?Try to extract the ith element of one of the ``eval_*`` inputs.Nz should be dict or list)r:   listrX   dictgetrZ   rk   rl   rm   s      r?   _extract_evaluation_meta_datars     s`     	J	%
 z?Qa= 	J	%~~a&&4& 7899rA   eval_seteval_Xeval_yc                    | Bd}t        j                  |t        d       ||t        d      t	        | t
              r| gS | S |du |du k7  rt        d      | |t	        |t
              t	        |t
              k7  rt        d      t	        |t
              r2t	        |t
              r"t        |      t        |      k7  rt        d      t	        |t
              r)t	        |t
              rt        t        ||d	            } | S ||fg} | S )
z>Validate eval args.

    Returns
    -------
    eval_set
    NzIThe argument 'eval_set' is deprecated, use 'eval_X' and 'eval_y' instead.rT   )category
stacklevelzASpecify either 'eval_set' or 'eval_X' and 'eval_y', but not both.z9You must specify eval_X and eval_y, not just one of them.zKIf eval_X is a tuple, y_val must be a tuple of same length, and vice versa.Tstrict)	warningswarnr   
ValueErrorr:   tuplerX   ro   zip)rt   ru   rv   msgs       r?   _validate_eval_set_Xyr     s    Yc$:qI!3`aah&:O$FdN+TUUF.fe$
65(AAjkkfe$FE)B6{c&k) !noofe$FE)BCt<=H O  ()HOrA   c            *       \    e Zd ZdZddddddddd	d
ddddd	d	dddddededededededeeee	f      deee
ef      dedededededededed eeeej                  j                  ej                  j                  f      d!ee   d"ed#ef(d$Zd%e
eef   fd&Zed'd(d)e
eef   d%d(fd*       Zd%ed(   f fd+Zd%efd,Zdod-ed%e
eef   f fd.Zd/ed%d fd0Zd1ed%e
eef   fd2Zd!ee   d%efd3Z	 	 	 	 	 	 	 	 	 	 	 	 	 	 dpddd4d5ed6ed7ee   d8ee   d9ee   d:ee e!      d;ee e      d<ee e      d=ee e      d>ee e      d?ee e      d@ee"   dAe#dBe$dCee e%      dDeeee&e'd f      dEeeee(e   f      dFeeee(e   f      d%d f&dGZ)e*jW                  dHdIdJdKdLdMdNdOP      dQz   e,z   e)_        	 	 	 	 	 	 dqd5edRedSedTee   dUedVedWed#ed%e-fdXZ.e/jW                  dYdZd[d\d]d^_      e._        e0d%efd`       Z1e0d%efda       Z2e2jf                  dbed%dfdc       Z2e0d%e4fdd       Z5e0d%efde       Z6e0d%eee	f   fdf       Z7e0d%efdg       Z8e0d%efdh       Z9e0d%e'fdi       Z:e0d%e;fdj       Z<e0d%ejz                  fdk       Z>e0d%e e   fdl       Z?e0d%ejz                  fdm       Z@e@j                  drdn       Z@ xZBS )sr3   z4Implementation of the scikit-learn API for LightGBM.gbdt   皙?d   @ N        MbP?         ?r   splitboosting_type
num_leaves	max_depthlearning_raten_estimatorssubsample_for_bin	objectiveclass_weightmin_split_gainmin_child_weightmin_child_samples	subsamplesubsample_freqcolsample_bytree	reg_alpha
reg_lambdarandom_staten_jobsimportance_typer   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   kwargsc                
   t         st        d      || _        || _        || _        || _        || _        || _        || _        |	| _	        |
| _
        || _        || _        || _        || _        || _        || _        || _        || _        || _        d| _        i | _        i | _        d| _        i | _        || _        || _        d| _        d| _        d| _        d| _        d| _        d| _         d| _!         | jD                  di | y)a  Construct a gradient boosting model.

        Parameters
        ----------
        boosting_type : str, optional (default='gbdt')
            'gbdt', traditional Gradient Boosting Decision Tree.
            'dart', Dropouts meet Multiple Additive Regression Trees.
            'rf', Random Forest.
        num_leaves : int, optional (default=31)
            Maximum tree leaves for base learners.
        max_depth : int, optional (default=-1)
            Maximum tree depth for base learners, <=0 means no limit.
            If setting this to a positive value, consider also changing ``num_leaves`` to ``<= 2^max_depth``.
        learning_rate : float, optional (default=0.1)
            Boosting learning rate.
            You can use ``callbacks`` parameter of ``fit`` method to shrink/adapt learning rate
            in training using ``reset_parameter`` callback.
            Note, that this will ignore the ``learning_rate`` argument in training.
        n_estimators : int, optional (default=100)
            Number of boosted trees to fit.
        subsample_for_bin : int, optional (default=200000)
            Number of samples for constructing bins.
        objective : str, callable or None, optional (default=None)
            Specify the learning task and the corresponding learning objective or
            a custom objective function to be used (see note below).
            Default: 'regression' for LGBMRegressor, 'binary' or 'multiclass' for LGBMClassifier, 'lambdarank' for LGBMRanker.
        class_weight : dict, 'balanced' or None, optional (default=None)
            Weights associated with classes in the form ``{class_label: weight}``.
            Use this parameter only for multi-class classification task;
            for binary classification task you may use ``is_unbalance`` or ``scale_pos_weight`` parameters.
            Note, that the usage of all these parameters will result in poor estimates of the individual class probabilities.
            You may want to consider performing probability calibration
            (https://scikit-learn.org/stable/modules/calibration.html) of your model.
            The 'balanced' mode uses the values of y to automatically adjust weights
            inversely proportional to class frequencies in the input data as ``n_samples / (n_classes * np.bincount(y))``.
            If None, all classes are supposed to have weight one.
            Note, that these weights will be multiplied with ``sample_weight`` (passed through the ``fit`` method)
            if ``sample_weight`` is specified.
        min_split_gain : float, optional (default=0.)
            Minimum loss reduction required to make a further partition on a leaf node of the tree.
        min_child_weight : float, optional (default=1e-3)
            Minimum sum of instance weight (Hessian) needed in a child (leaf).
        min_child_samples : int, optional (default=20)
            Minimum number of data needed in a child (leaf).
        subsample : float, optional (default=1.)
            Subsample ratio of the training instance.
        subsample_freq : int, optional (default=0)
            Frequency of subsample, <=0 means no enable.
        colsample_bytree : float, optional (default=1.)
            Subsample ratio of columns when constructing each tree.
        reg_alpha : float, optional (default=0.)
            L1 regularization term on weights.
        reg_lambda : float, optional (default=0.)
            L2 regularization term on weights.
        random_state : int, RandomState object or None, optional (default=None)
            Random number seed.
            If int, this number is used to seed the C++ code.
            If RandomState or Generator object (numpy), a random integer is picked based on its state to seed the C++ code.
            If None, default seeds in C++ code are used.
        n_jobs : int or None, optional (default=None)
            Number of parallel threads to use for training (can be changed at prediction time by
            passing it as an extra keyword argument).

            For better performance, it is recommended to set this to the number of physical cores
            in the CPU.

            Negative integers are interpreted as following joblib's formula (n_cpus + 1 + n_jobs), just like
            scikit-learn (so e.g. -1 means using all threads). A value of zero corresponds the default number of
            threads configured for OpenMP in the system. A value of ``None`` (the default) corresponds
            to using the number of physical cores in the system (its correct detection requires
            either the ``joblib`` or the ``psutil`` util libraries to be installed).

            .. versionchanged:: 4.0.0

        importance_type : str, optional (default='split')
            The type of feature importance to be filled into ``feature_importances_``.
            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.
        **kwargs
            Other parameters for the model.
            Check http://lightgbm.readthedocs.io/en/latest/Parameters.html for more parameters.

            .. warning::

                \*\*kwargs is not supported in sklearn, it may cause unexpected issues.

        Note
        ----
        A custom objective function can be provided for the ``objective`` parameter.
        In this case, it should have the signature
        ``objective(y_true, y_pred) -> grad, hess``,
        ``objective(y_true, y_pred, weight) -> grad, hess``
        or ``objective(y_true, y_pred, weight, group) -> grad, hess``:

            y_true : numpy 1-D array of shape = [n_samples]
                The target values.
            y_pred : numpy 1-D array of shape = [n_samples] or numpy 2-D array of shape = [n_samples, n_classes] (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.
            weight : numpy 1-D array of shape = [n_samples]
                The weight of samples. Weights should be non-negative.
            group : numpy 1-D array
                Group/query data.
                Only used in the learning-to-rank task.
                sum(group) = n_samples.
                For example, if you have a 100-document dataset with ``group = [10, 20, 40, 10, 10, 10]``, that means that you have 6 groups,
                where the first 10 records are in the first group, records 11-30 are in the second group, records 31-70 are in the third group, etc.
            grad : numpy 1-D array of shape = [n_samples] or numpy 2-D array of shape = [n_samples, n_classes] (for multi-class task)
                The value of the first order derivative (gradient) of the loss
                with respect to the elements of y_pred for each sample point.
            hess : numpy 1-D array of shape = [n_samples] or numpy 2-D array of shape = [n_samples, n_classes] (for multi-class task)
                The value of the second order derivative (Hessian) of the loss
                with respect to the elements of y_pred for each sample point.

        For multi-class task, y_pred is a numpy 2-D array of shape = [n_samples, n_classes],
        and grad and hess should be returned in the same format.
        zyscikit-learn is required for lightgbm.sklearn. You must install scikit-learn and restart your session to use this module.Nr   Fre   )#r"   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   _Booster_evals_result_best_score_best_iteration_other_params
_objectiver   _class_weight
_class_map_fitted_with_feature_names_n_features_n_features_in_classes
_n_classes
set_params)rP   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   s                        r?   rQ   zLGBMModel.__init__B  s"   \ !] 
 +"$"*(!2, 0!2", 0"$(.+/.079$&-/#(9=4805' "#%.2!!&!rA   r7   c                     d}dd|||d}t        j                  d      ^}}}t        |      t        |      fdk  rd|d<   d	g d
|dS )Na  In LightGBM, setting a sample's weight to 0 can produce a different result than omitting the sample. Such samples intentionally still affect count-based measures like 'min_data_in_leaf' (https://github.com/lightgbm-org/LightGBM/issues/5626#issuecomment-1712706678) and the estimated distribution of features for Dataset construction (see https://github.com/lightgbm-org/LightGBM/issues/5553).zscikit-learn incorrectly asserts that private attributes cannot be set in __init__: (see https://github.com/lightgbm-org/LightGBM/issues/2628)aS  Beginning in scikit-learn 1.9, by default estimators are expected to reject sample weight arrays that are all-0. LightGBM intentionally accepts such arrays. LightGBM supports some operations where training on an all-0-weight input could make sense, like batch updates with training continuation or manual model creation with forced splits.)check_no_attributes_set_in_init#check_all_zero_sample_weights_errorcheck_sample_weight_equivalence-check_sample_weight_equivalence_on_dense_data.check_sample_weight_equivalence_on_sparse_data.)r   rT   zdecision_function() returns raw margins while predict_proba() applies sigmoid in C++ independently, causing different tie structures after rounding. scikit-learn >= 1.2 relaxed this check to accept monotonically consistent scores. check_decision_proba_consistencyT)2darraysparse1dlabels)	allow_nanX_types_xfail_checks)r.   r   int)rP   check_sample_weight_strxfail_checkssklearn_majorsklearn_minor_s         r?   
_more_tagszLGBMModel._more_tags  s    o 	 M
m
 0G=T>U
$ ,<+A+A#+F(}qM 23f<d ;< 8)
 	
rA   tagsr1   	tags_dictc                     |d   | j                   _        d|d   v | j                   _        d|d   v | j                  _        | S )aS  Update ``sklearn.utils.Tags`` inherited from ``scikit-learn`` base classes.

        ``scikit-learn`` 1.6 introduced a dataclass-based interface for estimator tags.
        ref: https://github.com/scikit-learn/scikit-learn/pull/29677

        This method handles updating that instance based on the value in ``self._more_tags()``.
        r   r   r   r   )
input_tagsr   r   target_tagsone_d_labelsr   r   s     r?   _update_sklearn_tags_from_dictz(LGBMModel._update_sklearn_tags_from_dict%  sH     %.k$:!!)Yy-A!A(2i	6J(J%rA   c                     t        t        d      sdt         }t        |      | j	                  t
        |          | j                               S )N__sklearn_tags__zW__sklearn_tags__() should not be called when using scikit-learn<1.6. Detected version: r   )hasattrr+   r.   AttributeErrorr   superr   r   )rP   err_msg	__class__s     r?   r   zLGBMModel.__sklearn_tags__7  sa     ~'9:%%5$68  !)) 22)+oo' 3 
 	
rA   c                     t        | dd      S )Nfitted_F)getattrrP   s    r?   __sklearn_is_fitted__zLGBMModel.__sklearn_is_fitted__H  s    tY..rA   deepc                    t         |   |      }t        j                  |       }t        t	        |j
                  j                  d   dd            r|j
                  j                  d   |_        n|j
                  j                  d   |_        |j                  |j
                  j                  ||             |j                  | j                         |S )ag  Get parameters for this estimator.

        Parameters
        ----------
        deep : bool, optional (default=True)
            If True, will return the parameters for this estimator and
            contained subobjects that are estimators.

        Returns
        -------
        params : dict
            Parameter names mapped to their values.
        )r   r   
get_paramsNr   )	r   r   copycallabler   r   	__bases__updater   )rP   r   paramscpr   s       r?   r   zLGBMModel.get_paramsK  s    B ##.YYt_GBLL2215|TJK<<11!4BL <<11!4BLbll--b$78d(()rA   r   c                     |j                         D ]@  \  }}t        | ||       t        | d|       rt        | d| |       || j                  |<   B | S )zSet the parameters of this estimator.

        Parameters
        ----------
        **params
            Parameter names with their new values.

        Returns
        -------
        self : object
            Returns self.
        r   )itemssetattrr   r   )rP   r   keyvalues       r?   r   zLGBMModel.set_paramsy  sb     !,,. 	,JCD#u%tqY'#i/&+Ds#		,
 rA   stagec                 J   |dv sJ | j                         }|j                  dd       t        j                  d      D ]4  }||v s|j                  |      }t	        d| d       |dk(  s.|| _        6 |dk(  rv| j
                  jt        | t              rd| _        nRt        | t              r| j                  dkD  rd	| _        n+d
| _        n#t        | t              rd| _        nt        d      t        | j
                        r$|dk(  rt        | j
                        |d<   nd|d<   n| j
                  |d<   |j                  dd       |j                  dd       |j                  dd       t        |d   t        j                  j                         rC|d   j#                  t        j$                  t        j&                        j(                        |d<   nrt        |d   t        j                  j*                        rKt-        |d   j/                  t        j$                  t        j&                        j(                              |d<   | j                  dkD  r;t        j                  d      D ]  }|j                  |d        | j                  |d<   t1        | d      rP| j2                  }t        j                  d      D ]'  }||v st	        d| d       |j                  |      }) ||d<   t        | j
                  t4              r| j
                  nd}|It        | t              rd}n6t        | t              r| j                  dkD  rdnd}nt        | t              rd}t7        d||      }|dk(  r.t7        d|| j8                        }| j;                  |d         |d<   |S )ap  Process the parameters of this estimator based on its type, parameter aliases, etc.

        Parameters
        ----------
        stage : str
            Name of the stage (can be ``fit`` or ``predict``) this method is called from.

        Returns
        -------
        processed_params : dict
            Processed parameter names mapped to their values.
        >   fitpredictr   NzFound 'z8' in params. Will use it instead of 'objective' argumentr   
regressionrT   
multiclassbinary
lambdarankzUnknown LGBMModel type.Noner   r   r   r   	num_class_eval_ateval_atz6' in params. Will use it instead of 'eval_at' argumentl2multi_loglossbinary_loglossndcgmetricnum_threads)r   popr   rq   r   r   r:   r5   r2   r   r4   r~   r   rK   r;   randomRandomStaterandintiinfoint32max	Generatorr   integersr   r   strr   r   _process_n_jobs)rP   r   r   aliasobjr   original_metrics          r?   _process_paramszLGBMModel._process_params  s&    ****"

;%#''4 	*Ejj'wug-efgE>&)DO	* E>&dM2&2DOn5**6*2j1&2DO$%>??DOO$~&?&P{#&,{#"&//F;

$d+

>4(

>4(f^,bii.C.CD%+N%;%C%CBHHRXXDVDZDZ%[F>"~.		0C0CD%()?)H)HRTRZRZI[I_I_)`%aF>"??Q'++K8 (

5$'("&//F;4$mmG'++I6 0F? 75'1g!hi$jj/G0 !(F9 .8-M$//SW"$."&D.159__q5H/N^D*-"( %XvG E>(LF$($8$89N$OF=!rA   c                 h    |t        d      }|S |dk  rt        t        d      dz   |z   d      }|S )a  Convert special values of n_jobs to their actual values according to the formulas that apply.

        Parameters
        ----------
        n_jobs : int or None
            The original value of n_jobs, potentially having special values such as 'None' or
            negative integers.

        Returns
        -------
        n_jobs : int
            The value of n_jobs with special values converted to actual number of threads.
        T)only_physical_coresr   Fr   )r)   r  )rP   r   s     r?   r  zLGBMModel._process_n_jobs  sD     >"t<F  aZ5AAENPQRFrA   ru   rv   Xysample_weight
init_scorer=   rt   
eval_nameseval_sample_weighteval_class_weighteval_init_score
eval_groupeval_metricfeature_namecategorical_feature	callbacks
init_modelru   rv   c          
      ,	   | j                  d      }|g }n<t        |t              rt        j                  |      }nt        j                  |      g}|D cg c]  }t        |      st        |       }}|D cg c]  }t        |t              s| }}t        |d   t        t        d      f      r|d   gn|d   |d<   |D cg c]  }||d   vs| c}|d   z   |d<   |d   D cg c]  }||	 c}|d<   t        |t              r||}}|j                  d   | _        nyt        j                  |      r,||}}t        j                  |      j                  d   | _        n8t!        | ||dddd	      \  }}|!t"        rt%        ||d
      }nt%        ||      }| j&                  | j(                  | _        | j&                  ?t+        | j&                  |      }|t-        |      dk(  r|}nt/        j0                  ||      }t3        ||||||||      }g }t5        |||      }|H|;t-        |      t-        |      k7  r$t7        dt-        |       dt-        |       d      t9        |      D ]  \  } }!|!d   |u r
|!d   |u r|}"nt;        |d|       }#t;        |	d|       }$|$t        |$t<              r<| j>                  0|$jA                         D %&ci c]  \  }%}&| j>                  |%   |& }$}%}&t+        |$|!d         }'|#t-        |#      dk(  r|'}#nt/        j0                  |#|'      }#t;        |
d|       }(t;        |d|       })t3        |!d   |!d   |#|)|(d|      }"|jC                  |"        t        |tD              r|jF                  }|g }nt        j                  |      }i }*|jC                  tI        |*             tK        ||| jL                  |||||      | _'        | jN                  jQ                         | _)        |jT                  | _+        |*| _,        | jN                  jZ                  | _.        | jN                  j^                  | _0        d| _1        | jN                  je                          ~~| S c c}w c c}w c c}w c c}w c c}&}%w )4Docstring is set after definition, using a template.r   r   Nr   r   TFrT   resetaccept_sparseensure_all_finiteensure_min_samples)allow_all_zero_weightsr   )datarD   rH   r=   r  r  r  r   )rt   ru   rv   zLength of eval_group (z#) not equal to length of eval_set ()r  rr   r  r  r  auto)r%  rD   rH   r=   r  r  r   )r   	train_setnum_boost_round
valid_setsvalid_namesfevalr  r  )3r
  r:   ro   r   deepcopyr   rg   r  typer/   shapen_features_in_nwdis_into_dataframenwfrom_nativer-   r!   r&   r   r   r(   rX   r;   multiplyr   r   r~   	enumeraters   rp   r   r   appendr3   booster_r    r0   r   r   num_featurer   _has_non_default_feature_namesr   r   best_iterationr   
best_scorer   r   free_dataset)+rP   r  r  r  r  r=   rt   r  r  r  r  r  r  r  r  r  r  ru   rv   r   eval_metric_listfeval_metrics_callablemeval_metrics_builtiner   _X_yclass_sample_weightr(  r*  rm   
valid_data	valid_setvalid_weightvalid_class_weightkvvalid_class_sample_weightvalid_init_scorevalid_groupevals_results+                                              r?   r   zLGBMModel.fit  s   . %%E%2
 !T*#}}[9 $k :; CS bQV^_`Va!5a!8 b b+;Raz!S?QRR 2<F8<LsTXY]T^N_1`F8,-flmufvx';Y!qxHX?XAY\bck\llx171AXvVEWFXxa&B"$((1+D""1%B"$.."3"9"9!"<D '""'#$FB (I$:="ei$jM$:="$MM%!%!2!2D)":4;M;Mq"Q$M(:a(? 3 "M;N O ! 3%	
	 %'
((6RXY%z?c(m3$0Z0AAdehiqerdsstu  "+8!4 +-:a=A%*Q-1*< )I#@#51$L
 *G#40*&
 *5%&8$?DOOD_TfTlTlTn1oDAq$//!2Da2G1o.1o4LM_aklman4o1'/3|3D3I+DL+-;;|E^+_L'D#2.($
 #@#-)#K
 !('](m+)#3,2%!I !!),W+-Z j),#,,JI		),I(**<89 --!"'!	
   ==446 +4*R*R')#}};;==33 	""$zo !cR ZXV 2ps6   Q<)Q<<RRRR,R4RRznumpy array, pandas DataFrame, pyarrow Table, polars DataFrame, scipy.sparse, list of lists of int or float of shape = [n_samples, n_features]znumpy array, pandas DataFrame, pandas Series, list of int or float, pyarrow ChunkedArray or polars Series of shape = [n_samples]znumpy array, pandas Series, list of int or float, pyarrow ChunkedArray, polars Series of shape = [n_samples] or None, optional (default=None)aB  numpy array, pandas DataFrame, pandas Series, list of int or float, list of lists, pyarrow ChunkedArray, pyarrow Table, polars Series, polars DataFrame of shape = [n_samples] or shape = [n_samples * n_classes] (for multi-class task) or shape = [n_samples, n_classes] (for multi-class task) or None, optional (default=None)zwnumpy array, pandas Series, pyarrow ChunkedArray, polars Series, list of int or float, or None, optional (default=None)zZlist of array (same types as ``sample_weight`` supports), or None, optional (default=None)zWlist of array (same types as ``init_score`` supports), or None, optional (default=None)zRlist of array (same types as ``group`` supports), or None, optional (default=None))X_shapey_shapesample_weight_shapeinit_score_shapegroup_shapeeval_sample_weight_shapeeval_init_score_shapeeval_group_shapez

	raw_scorestart_iterationnum_iteration	pred_leafpred_contribvalidate_featuresc           
         | j                         st        d      t        |t              s&t	        j
                  |      st        | |dddd      }| j                  d      }	t        j                  dd	d
ddddg|j                          D ]  }
|	j                  |
d        |	j                  |       t        d|	| j                        }	| j                  |	d         |	d<    | j                   j"                  |f||||||d|	S )r  z;Estimator not fitted, call fit before exploiting the model.FTr   r  r   r  r%  r  rY  rZ  r[  r\  r]  Nr   )rY  rZ  r[  r\  r]  r^  )r   r#   r:   r/   r1  r2  r-   r
  r   get_by_aliaskeysr   r   r   r   r  r   r   )rP   r  rY  rZ  r[  r\  r]  r^  r   predict_paramsr  s              r?   r   zLGBMModel.predict  s2    ))+$%bcc!\*33H3H3K!
 ""'#$A" --I->#00	
 [[]	
 
	,E ud+
	, 	f% -]NDKKX(,(<(<^M=Z([}%$t}}$$	
+'%/	
 	
 		
rA   z+Return the predicted value for each sample.mnumpy array, pandas DataFrame, scipy.sparse, list of lists of int or float of shape = [n_samples, n_features]predicted_resultCarray-like of shape = [n_samples] or shape = [n_samples, n_classes]Varray-like of shape = [n_samples, n_trees] or shape = [n_samples, n_trees * n_classes]array-like of shape = [n_samples, n_features + 1] or shape = [n_samples, (n_features + 1) * n_classes] or list with n_classes length of such objectsdescriptionrQ  output_namepredicted_result_shapeX_leaves_shapeX_SHAP_values_shapec                 P    | j                         st        d      | j                  S )3:obj:`int`: The number of features of fitted model.z1No n_features found. Need to call fit beforehand.)r   r#   r   r   s    r?   n_features_zLGBMModel.n_features_
  (     ))+$%XYYrA   c                 P    | j                         st        d      | j                  S )ro  z4No n_features_in found. Need to call fit beforehand.)r   r#   r   r   s    r?   r0  zLGBMModel.n_features_in_  s(     ))+$%[\\"""rA   r   c                     || _         y)a  Set number of features found in passed-in dataset.

        Starting with ``scikit-learn`` 1.6, ``scikit-learn`` expects to be able to directly
        set this property in functions like ``validate_data()``.

        .. note::

            Do not call ``estimator.n_features_in_ = some_int`` or anything else that invokes
            this method. It is only here for compatibility with ``scikit-learn`` validation
            functions used internally in ``lightgbm``.
        N)r   )rP   r   s     r?   r0  zLGBMModel.n_features_in_  s     $rA   c                 P    | j                         st        d      | j                  S )z,:obj:`dict`: The best score of fitted model.z1No best_score found. Need to call fit beforehand.)r   r#   r   r   s    r?   best_score_zLGBMModel.best_score_'  rq  rA   c                 P    | j                         st        d      | j                  S )zc:obj:`int`: The best iteration of fitted model if ``early_stopping()`` callback has been specified.zRNo best_iteration found. Need to call fit with early_stopping callback beforehand.)r   r#   r   r   s    r?   best_iteration_zLGBMModel.best_iteration_.  s.     ))+$d  ###rA   c                 P    | j                         st        d      | j                  S )zT:obj:`str` or :obj:`callable`: The concrete objective used while fitting this model.z0No objective found. Need to call fit beforehand.)r   r#   r   r   s    r?   
objective_zLGBMModel.objective_7  s&     ))+$%WXXrA   c                 l    | j                         st        d      | j                  j                         S )  :obj:`int`: True number of boosting iterations performed.

        This might be less than parameter ``n_estimators`` if early stopping was enabled or
        if boosting stopped early due to limits on complexity like ``min_gain_to_split``.

        .. versionadded:: 4.0.0
        z3No n_estimators found. Need to call fit beforehand.r   r#   r   current_iterationr   s    r?   n_estimators_zLGBMModel.n_estimators_>  s/     ))+$%Z[[}}..00rA   c                 l    | j                         st        d      | j                  j                         S )r{  z-No n_iter found. Need to call fit beforehand.r|  r   s    r?   n_iter_zLGBMModel.n_iter_K  s/     ))+$%TUU}}..00rA   c                 P    | j                         st        d      | j                  S )z.Booster: The underlying Booster of this model.z.No booster found. Need to call fit beforehand.)r   r#   r   r   s    r?   r8  zLGBMModel.booster_X  &     ))+$%UVV}}rA   c                 P    | j                         st        d      | j                  S )zK:obj:`dict`: The evaluation results if validation sets have been specified.z<No results found. Need to call fit with eval_set beforehand.)r   r#   r   r   s    r?   evals_result_zLGBMModel.evals_result__  s(     ))+$%cdd!!!rA   c                     | j                         st        d      | j                  j                  | j                        S )a  :obj:`array` of shape = [n_features]: The feature importances (the higher, the more important).

        .. note::

            ``importance_type`` attribute is passed to the function
            to configure the type of importance values to be extracted.
        z:No feature_importances found. Need to call fit beforehand.)r   )r   r#   r   feature_importancer   r   s    r?   feature_importances_zLGBMModel.feature_importances_f  s:     ))+$%abb}}//@T@T/UUrA   c                 l    | j                         st        d      | j                  j                         S )z:obj:`list` of shape = [n_features]: The names of features.

        .. note::

            If input does not contain feature names, they will be added during fitting in the format ``Column_0``, ``Column_1``, ..., ``Column_N``.
        z3No feature_name found. Need to call fit beforehand.)r   r#   r   r  r   s    r?   feature_name_zLGBMModel.feature_name_s  s/     ))+$%Z[[}}))++rA   c                     | j                         st        d      | j                  s"t        dt	        |       j
                   d      t        j                  | j                        S )ao  :obj:`array` of shape = [n_features]: scikit-learn compatible version of ``.feature_name_``.

        Only available when training data had feature names (e.g. a pandas DataFrame).
        When training was done with data without feature names (e.g. a numpy array),
        accessing this attribute raises ``AttributeError``.

        .. versionadded:: 4.5.0
        z8No feature_names_in_ found. Need to call fit beforehand.'z' object has no attribute 'feature_names_in_'. The training data did not have feature names (e.g. was a numpy array rather than a pandas DataFrame).)	r   r#   r   r   r.  r`   r;   arrayr  r   s    r?   feature_names_in_zLGBMModel.feature_names_in_  sg     ))+$%_``.. DJ''( )K K 
 xx**++rA   c                      y)as  Intercept calls to delete ``feature_names_in_``.

        Some code paths in ``scikit-learn`` try to delete the ``feature_names_in_`` attribute
        on estimators when a new training dataset that doesn't have features is passed.
        LightGBM has custom handling of feature names and has chosen to opt out of this behavior.

        However, that behavior is coupled to ``scikit-learn`` automatically updating
        ``n_features_in_`` in those same code paths, which is necessary for compliance
        with its API (via argument ``reset`` to functions like ``validate_data()`` and
        ``check_array()``).

        .. note::

            Do not call ``del estimator.feature_names_in_`` or anything else that invokes
            this method. It is only here for compatibility with ``scikit-learn`` validation
            functions used internally in ``lightgbm``.
        Nre   r   s    r?   r  zLGBMModel.feature_names_in_  s    & 	rA   )T)NNNNNNNNNNr'  r'  NNFr   NFFF)r7   N)Cr`   ra   rb   rc   r  r   floatr
   r   rd   r   r;   r   r   r  r   rQ   r   staticmethodr   r   boolr   r   r   r
  r  _LGBM_ScikitMatrixLiker   r   r   r   r	   _LGBM_ScikitValidSet_LGBM_ScikitEvalMetricTyper   r   r   r   r   r   r   _lgbmmodel_doc_fitformat_lgbmmodel_doc_custom_eval_noter   r   _lgbmmodel_doc_predictpropertyrp  r0  setterr   ru  rw  ry  r~  r  r8  r   r  r<   r  r  r  deleter__classcell__r   s   @r?   r3   r3   ?  s   >
 $"!'OS37 #"&!#"%Y] $&+t" t" 	t"
 t" t" t" t" E#'J"JKLt" uT3Y/0t" t"  t" t" t" t"   !t"" #t"$ %t"& uS"))*?*?ATAT%TUV't"( )t"* +t", -t"t'
DcN '
R  S> 
	 "
(?"; 
"/t /,t ,tCH~ ,\3 ; (TS TT#s(^ Tlhsm  0 5948+/9=*.?C37?C6:<@7=EK.2GK#{& Z^KO){!{ {   01	{
 01{ ({ 4 456{ T#Y'{ %T*:%;<{ $DK0{ "$':";<{ T/23{ 89{ 5{ C{  DN+!{" U3g{#BCD#{& 5u=S7TTUV'{( o0FFGH){* 
+{| 	!! e W !p b R &B"{q 	" 		
 
	 *	* K$   '+""'<
!<
 <
 	<

  }<
 <
 <
  <
 <
 
!<
| -33A&do s 4 GO  S     # # # $C $D $ $  7     $ $ $ E#'J"JK   
1s 
1 
1 
1 
1 
1 '   " " " 
Vbjj 
V 
V 	,tCy 	, 	, ,2:: , ,&  rA   r3   c            +           e Zd ZdZddddddddd	d
ddddd	d	dddddededededededeeee	f      deee
ef      dedededededededed eeeej                  j                  ej                  j                  f      d!ee   d"ed#ed$df* fd%Zej                   j                  e_        d$e
eef   fd&ZdA fd'Z	 	 	 	 	 	 	 	 	 	 	 dBddd(d)ed*ed+ee   d,ee   d-eee      d.eee      d/eee      d0eee      d1ee   d2ed3ed4eee      d5eeeeeef      d6eeee e   f      d7eeee e   f      d$d f  fd8Z!ejB                  j                  jE                  d9d:      Z#e#de#jI                  d;       e#e#jI                  d<      d z   Z#e#de#jI                  d=       e#e#jI                  d>      d z   Z#e#de#jI                  d?       e#e#jI                  d@      d z   e!_         xZ%S )Cr5   zLightGBM regressor.r   r   r   r   r   r   Nr   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r7   c                    t        |   di d|d|d|d|d|d|d|d|d	|	d
|
d|d|d|d|d|d|d|d|d|| y Nr   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   re   r   rQ   rP   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   s                        r?   rQ   zLGBMRegressor.__init__      0 	 	
'	
!	
  	
 (		

 &	
 0	
  	
 &	
 *	
 .	
 0	
  	
 *	
 .	
  	
  "!	
" &#	
$ %	
& ,)	
rA   c                     t        t        t        dd             rt        j                  |       }ni }|j	                  t
        j                  |              |S Nr   )r   r   r,   r   r   r3   rP   r   s     r?   r   zLGBMRegressor._more_tags  sE    G.dCD%006DDI((./rA   c                      t         |          S )N)r   r   )rP   r   s    r?   r   zLGBMRegressor.__sklearn_tags__  s    w'))rA   r  r  r  r  r  rt   r  r  r  r  r  r  r  r  ru   rv   c                D    t         |   |||||||||||	|
|||       | S )*Docstring is inherited from the LGBMModel.)r  r  rt   ru   rv   r  r  r  r  r  r  r  r  )r   r   )rP   r  r  r  r  rt   r  r  r  r  r  r  r  r  ru   rv   r   s                   r?   r   zLGBMRegressor.fit  sJ    ( 	'!!1+#% 3! 	 	
" rA   self : LGBMModelzself : LGBMRegressorgroup :
eval_set :eval_class_weight :eval_init_score :eval_group :eval_metric :r7   r1   )NNNNNNNr'  r'  NN)&r`   ra   rb   rc   r  r   r  r
   r   rd   r   r;   r   r   r  r   rQ   r3   r   r   r  r   r   r   r	   r  r  r   r   r   r   r   r   r   replace	_base_docfindr  r  s   @r?   r5   r5     s    $"!'OS37 #"&!#"%Y] $&+-
 -
 	-

 -
 -
 -
 -
 E#'J"JKL-
 uT3Y/0-
 -
  -
 -
 -
 -
   !-
" #-
$ %-
& uS"))*?*?ATAT%TUV'-
( )-
* +-
, --
. 
/-
^ !))11HDcN * 59489=*.?C?C<@7=EK.2EI%  Z^KO#%!% %   01	%
 01% 4 456% T#Y'% %T*:%;<% "$':";<% 89% 5% C% DN+% U3gy#@AB%  5u=S7TTUV!%" o0FFGH#%$ 
%%N %%--.@BXYI-INN9-.
INN<02
3	4  AINN+@ABYy~~^qOrOtEuuI<inn^<=	)..YhJiJk@llCKKrA   r5   c            +           e Zd ZdZddddddddd	d
ddddd	d	dddddededededededeeee	f      deee
ef      dedededededededed eeeej                  j                  ej                  j                  f      d!ee   d"ed#ed$df* fd%Zej                   j                  e_        d$e
eef   fd&ZdU fd'Z	 	 	 	 	 	 	 	 	 	 	 	 dVddd(d)ed*ed+ee   d,ee   d-eee      d.eee      d/eee      d0eee      d1eee      d2ee   d3ed4ed5eee      d6eeeeeef      d7eeee e   f      d8eeee e   f      d$d f" fd9Z!ejB                  j                  jE                  d:d;      Z#e#de#jI                  d<       e#e#jI                  d=      d z   Z#e#de#jI                  d>       e#e#jI                  d?      d z   e!_        	 	 	 	 	 	 dWd)edAe%dBedCee   dDe%dEe%dFe%d#ed$e&fdGZ'ejN                  j                  e'_        	 	 	 	 	 	 dWd)edAe%dBedCee   dDe%dEe%dFe%d#ed$e&f fdHZ(e)jU                  dIdJdKdLdMdNO      e(_        ddd@dPd)edBedCee   dFe%d#ed$e&f fdQZ+e,d$ejZ                  fdR       Z.e,d$efdS       Z/e,d$e%fdT       Z0 xZ1S )Xr2   zLightGBM classifier.r   r   r   r   r   r   Nr   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r7   c                    t        |   di d|d|d|d|d|d|d|d|d	|	d
|
d|d|d|d|d|d|d|d|d|| y r  r  r  s                        r?   rQ   zLGBMClassifier.__init__!  r  rA   c                     t        t        t        dd             rt        j                  |       }ni }|j	                  t
        j                  |              |S r  )r   r   r'   r   r   r3   r  s     r?   r   zLGBMClassifier._more_tagsR  sE    G/tDE&11$7DDI((./rA   c                 l    t         |          }|"d|j                  _        d|j                  _        |S )NTF)r   r   classifier_tagsmulti_classmulti_label)rP   r   r   s     r?   r   zLGBMClassifier.__sklearn_tags__\  s7    w')/3D  ,/4D  ,rA   r  r  r  r  r  rt   r  r  r  r  r  r  r  r  r  ru   rv   c                   t        |       t        |       t               j                  |      | _        | j                  j                  |      }t        t        | j                  j                  | j                  j                  | j                  j                        d            | _	        t        | j                  t              r@| j                  j                         D ci c]  \  }}| j                  |   | c}}| _        | j                  j                  | _        t        | j                        | _        | j"                  d| _        t'        |
      st        |
t(              r|
}nt        |
t*              r|
g}ng }| j,                  r(t/        |      D ]  \  }}|dv rd||<   |dv sd||<    n't/        |      D ]  \  }}|dv rd	||<   |d
v sd||<    |}
d}|gt        |t0              r|g}g }|D ]M  \  }}||u r||u r|j3                  ||f       "|j3                  || j                  j                  |      f       O t4        |   |||||||||||	|
||||       | S c c}}w )r  Trz   N>   loglossr   r   >   errorbinary_errormulti_error>   r  r   r   >   r  r  r  )r  r  rt   r  ru   rv   r  r  r  r  r  r  r  r  )r$   r%   r*   r   _le	transformrp   r   classes_r   r:   r   r   r   r   rX   r   r   r   r   ro   r  _LGBMClassifier__is_multiclassr6  r   r7  r   )rP   r  r  r  r  rt   r  r  r  r  r  r  r  r  r  ru   rv   rE  rK  rL  r>  indexr   r*  valid_xvalid_yr   s                             r?   r   zLGBMClassifier.fitc  s   * 	Q'*$&**1-XX"s488#4#4dhh6H6HIZIZ6[dhijd''.DHDUDUD[D[D]!^DAq$//!"4a"7!^D))dmm,>>!"DO $+t,#. K-$/= #% ##%./?%@ @ME6!>>2A(/#<<2?(/	@ &//?%@ AME6!==2B(/#;;2@(/	A
 +K <@
(E*$:J$, N a<GqL%%wm4%%w0B0B70K&LM	N 	'!!1/+#% 3!! 	 	
$ y "_s   %I-r  zself : LGBMClassifierr  r  r  r  FrY  rZ  r[  r\  r]  r^  c                      | j                   d|||||||d|}	t        | j                        s|s|s|r|	S t        j                  |	d      }
| j
                  j                  |
      S )r  r  rY  rZ  r[  r\  r]  r^  r   )axisre   )predict_probar   r   r;   argmaxr  inverse_transform)rP   r  rY  rZ  r[  r\  r]  r^  r   resultclass_indexs              r?   r   zLGBMClassifier.predict  sx     $## 	
+'%/	
 	
 DOO$	Y,M))F3K88--k::rA   c                 @   t        |   d|||||||d|}	t        | j                        r|s|s|st	        d       |	S | j
                  s|s|s|r|	S d}
t        |	t        j                        sJ |
       t        j                  d|	z
  |	f      j                         S )r  r  z}Cannot compute class probabilities or labels due to the usage of customized objective function.
Returning raw scores instead.zpredict() should return np.ndarray when pred_contrib=False. If you're seeing this message, it's a bug in lightgbm. Please report it at https://github.com/lightgbm-org/LightGBM/issues.r   re   )r   r   r   r   r   r  r:   r;   r<   vstack	transpose)rP   r  rY  rZ  r[  r\  r]  r^  r   r  r>   r   s              r?   r  zLGBMClassifier.predict_proba  s      	
+'%/	
 	
 DOO$i90
 M!!Y)|MN  fbjj1<9<199cFlF34>>@@rA   z@Return the predicted probability for each class for each sample.rc  predicted_probabilityre  rf  rg  rh  )rZ  r[  r^  c          	      .    t        |   d|d|||d|S )a  Return the raw margin score for each sample.

        .. versionadded:: 4.7.0

        Parameters
        ----------
        X : numpy array, pandas DataFrame, scipy.sparse, list of lists of int or float of shape = [n_samples, n_features]
            Input features matrix.
        start_iteration : int, optional (default=0)
            Start index of the iteration to predict.
            If <= 0, starts from the first iteration.
        num_iteration : int or None, optional (default=None)
            Total number of iterations used in the prediction.
            If None, if the best iteration exists and start_iteration <= 0, the best iteration is used;
            otherwise, all iterations from ``start_iteration`` are used (no limits).
            If <= 0, all iterations from ``start_iteration`` are used (no limits).
        validate_features : bool, optional (default=False)
            If True, ensure that the features used to predict match the ones used to train.
            Used only if data is pandas DataFrame.
        **kwargs
            Other parameters forwarded to ``predict()``.

        Returns
        -------
        raw_score : array-like of shape = [n_samples] or shape = [n_samples, n_classes]
            The predicted values.
        T)r  rY  rZ  r[  r^  re   )r   r   )rP   r  rZ  r[  r^  r   r   s         r?   decision_functionz LGBMClassifier.decision_function  s5    H w 
+'/
 
 	
rA   c                 P    | j                         st        d      | j                  S )z;:obj:`array` of shape = [n_classes]: The class label array..No classes found. Need to call fit beforehand.)r   r#   r   r   s    r?   r  zLGBMClassifier.classes_>  r  rA   c                 P    | j                         st        d      | j                  S )z":obj:`int`: The number of classes.r  )r   r#   r   r   s    r?   
n_classes_zLGBMClassifier.n_classes_E  s&     ))+$%UVVrA   c                     | j                   dkD  xs. t        | j                  t              xr | j                  t        v S )zI:obj:`bool`:  Indicator of whether the classifier is used for multiclass.rT   )r   r:   r   r  r   r   s    r?   __is_multiclasszLGBMClassifier.__is_multiclassL  s2     "vz$//3'G'uDOO_uLuvrA   r  )NNNNNNNNr'  r'  NNr  )2r`   ra   rb   rc   r  r   r  r
   r   rd   r   r;   r   r   r  r   rQ   r3   r   r   r  r   r   r   r	   r  r  r   r   r   r   r   r   r   r  r  r  r  r   r   r  r  r  r  r  r<   r  r  r  r  r  s   @r?   r2   r2     st    $"!'OS37 #"&!#"%Y] $&+-
 -
 	-

 -
 -
 -
 -
 E#'J"JKL-
 uT3Y/0-
 -
  -
 -
 -
 -
   !-
" #-
$ %-
& uS"))*?*?ATAT%TUV'-
( )-
* +-
, --
. 
/-
^ !))11HDcN  59489=*.?C37?C<@7=EK.2EIW" Z^KO%W!W W   01	W
 01W 4 456W T#Y'W %T*:%;<W $DK0W "$':";<W 89W 5W CW DN+W U3gy#@ABW" 5u=S7TTUV#W$ o0FFGH%W& 
'Wr %%--.@BYZI-INN9-.
INN<02
3	4  <inn^<=	)..YhJiJk@llCK
   '+""';!; ; 	;
  }; ; ;  ; ; 
!;8  ''//GO
   '+""'%A!%A %A 	%A
  }%A %A %A  %A %A 
!%AN 399V+do s : M  !'+"'+
!+
 	+

  }+
  +
 +
 
!+
Z "**   C   w w wrA   r2   c            +           e Zd ZdZddddddddd	d
ddddd	d	dddddededededededeeee	f      deee
ef      dedededededededed eeeej                  j                  ej                  j                  f      d!ee   d"ed#ed$df* fd%Zej                   j                  e_        	 	 	 	 	 	 	 	 	 	 	 	 	 	 dAddd&d'ed(ed)ee   d*ee   d+ee   d,eee      d-eee      d.eee      d/eee      d0eee      d1ee   d2eee   eed3f   f   d4ed5ed6eee      d7eeeeeef      d8eeeee   f      d9eeeee   f      d$d f& fd:Z ej@                  j                  jC                  d;d<      Z"e"de"jG                  d=       e"e"jG                  d>      d z   e _        e j                  Z"e"jI                  d?      \  Z%Z&Z'e% d@e& e' e _         xZ(S )Br4   a!  LightGBM ranker.

    .. warning::

        scikit-learn doesn't support ranking applications yet,
        therefore this class is not really compatible with the sklearn ecosystem.
        Please use this class mainly for training and applying ranking models in common sklearnish way.
    r   r   r   r   r   r   Nr   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r7   c                    t        |   di d|d|d|d|d|d|d|d|d	|	d
|
d|d|d|d|d|d|d|d|d|| y r  r  r  s                        r?   rQ   zLGBMRanker.__init__^  r  rA   r  r  r  r  r  r=   rt   r  r  r  r  r  r   .r  r  r  r  ru   rv   c                    |t        d      |
|||t        d      || _        t        |   |||||||||||	|
|||||       | S )r  z!Should set group for ranking taskzLeval_group cannot be None if any of eval_set, eval_X, or eval_y are provided)r  r  r=   rt   r  ru   rv   r  r  r  r  r  r  r  r  )r~   r   r   r   )rP   r  r  r  r  r=   rt   r  r  r  r  r  r   r  r  r  r  ru   rv   r   s                      r?   r   zLGBMRanker.fit  s    0 =@AA8#76;MQWQckll'!!1+!#% 3!# 	 	
& rA   r  zself : LGBMRankerr  r  zfeature_name :zeval_at : list or tuple of int, optional (default=(1, 2, 3, 4, 5))
        The evaluation positions of the specified metric.
    )NNNNNNNNN)r   rT   rU   rV      r'  r'  NN))r`   ra   rb   rc   r  r   r  r
   r   rd   r   r;   r   r   r  r   rQ   r3   r  r   r   r   r   r	   r  r  r   r   r   r   r   r   r   r  r  r  	partition_before_feature_name_feature_name_after_feature_namer  r  s   @r?   r4   r4   R  s    $"!'OS37 #"&!#"%Y] $&+-
 -
 	-

 -
 -
 -
 -
 E#'J"JKL-
 uT3Y/0-
 -
  -
 -
 -
 -
   !-
" #-
$ %-
& uS"))*?*?ATAT%TUV'-
( )-
* +-
, --
. 
/-
^ !))11H 5948+/9=*.?C?C6:<@5D7=EK.2EI#2& Z^KO)2!2 2   01	2
 012 (2 4 4562 T#Y'2 %T*:%;<2 "$':";<2 T/232 892 tCy%S/122 52 C2  DN+!2" U3gy#@AB#2& 5u=S7TTUV'2( o0FFGH)2* 
+2h %%--.@BUVI9INN#89:
INN#679
:	; K I?H?R?RSc?d<-)<+, -O'(,CKKrA   r4   )^rc   r   r|   inspectr   pathlibr   typingr   r   r   r   r	   r
   r   r   narwhalsr3  narwhals.dependenciesdependenciesr1  narwhals.typingnwtnumpyr;   scipy.sparsescipybasicr   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   callbackr   r    compatr!   r"   r#   r$   r%   r&   r'   r(   r)   r*   r+   r,   r-   r.   r/   enginer0   r1   __all__r  r   r<   IntoDataFramer   spmatrixr  rd   rj   r  r  r  r@   rE   rI   rK   rg   r  r  r  rs   r   r3   r5   r2   r4   re   rA   r?   <module>r     s   2     S S S  #       & 9    " % tE{DI%	&'JJ	LL	  ',	"**	rzz*bjj"**$%	'
 	"**	rzz8BJJ+?@bjj"**$%	'
 	"**	rzz8BJJ+?"**AUVbjj"**$%	'' #" "'	"**	rzz*$	& 	"**	rzz*)*	,
 	"**	rzz8BJJ+?@$	& 	"**	rzz8BJJ+?@)*	,
 	"**	rzz8BJJ+?"**AUV$	& 	"**	rzz8BJJ+?"**AUV)*	,-" : #"s22	346 
 3_DE  Xbjj=Q  RZZ ' hrzz>R Th ThnNc Nchk Z# >, ^:tCH~tCy89:: : 	:
 c]:0!t012! U159O3PPQR! U?E/,BBCD	!
 d'()!Hg gTpm&	 pmfsw() swl	z, z,rA   