class_docstr: Implementation of the scikit-learn API for LightGBM.
class_docstr_tok: ["Implementation","of","the","scikit-learn","API","for","LightGBM","."]
docstr: Docstring is set after definition, using a template.
code: def fit(
      self,
      X: _LGBM_ScikitMatrixLike,
      y: _LGBM_LabelType,
      sample_weight: Optional[_LGBM_WeightType] = None,
      init_score: Optional[_LGBM_InitScoreType] = None,
      group: Optional[_LGBM_GroupType] = None,
      eval_set: Optional[List[_LGBM_ScikitValidSet]] = None,
      eval_names: Optional[List[str]] = None,
      eval_sample_weight: Optional[List[_LGBM_WeightType]] = None,
      eval_class_weight: Optional[List[float]] = None,
      eval_init_score: Optional[List[_LGBM_InitScoreType]] = None,
      eval_group: Optional[List[_LGBM_GroupType]] = None,
      eval_metric: Optional[_LGBM_ScikitEvalMetricType] = None,
      feature_name: _LGBM_FeatureNameConfiguration = "auto",
      categorical_feature: _LGBM_CategoricalFeatureConfiguration = "auto",
      callbacks: Optional[List[Callable]] = None,
      init_model: Optional[
          Union[str, Path, Booster, "LGBMModel"]
      ] = None,
  ) -> "LGBMModel":
      """Docstring is set after definition, using a template."""
      params = self._process_params(stage="fit")
  
      # Do not modify original args in fit function
      # Refer to https://github.com/microsoft/LightGBM/pull/2619
      eval_metric_list: List[Union[str, _LGBM_ScikitCustomEvalFunction]]
      if eval_metric is None:
          eval_metric_list = []
      elif isinstance(eval_metric, list):
          eval_metric_list = copy.deepcopy(eval_metric)
      else:
          eval_metric_list = [copy.deepcopy(eval_metric)]
  
      # Separate built-in from callable evaluation metrics
      eval_metrics_callable = [
          _EvalFunctionWrapper(f)
          for f in eval_metric_list
          if callable(f)
      ]
      eval_metrics_builtin = [
          m for m in eval_metric_list if isinstance(m, str)
      ]
  
      # concatenate metric from params (or default if not provided in params) and eval_metric
      params["metric"] = (
          [params["metric"]]
          if isinstance(params["metric"], (str, type(None)))
          else params["metric"]
      )
      params["metric"] = [
          e for e in eval_metrics_builtin if e not in params["metric"]
      ] + params["metric"]
      params["metric"] = [
          metric for metric in params["metric"] if metric is not None
      ]
  
      if not isinstance(X, (pd_DataFrame, dt_DataTable)):
          _X, _y = _LGBMCheckXY(
              X,
              y,
              accept_sparse=True,
              force_all_finite=False,
              ensure_min_samples=2,
          )
          if sample_weight is not None:
              sample_weight = _LGBMCheckSampleWeight(sample_weight, _X)
      else:
          _X, _y = X, y
  
      if self._class_weight is None:
          self._class_weight = self.class_weight
      if self._class_weight is not None:
          class_sample_weight = _LGBMComputeSampleWeight(
              self._class_weight, y
          )
          if sample_weight is None or len(sample_weight) == 0:
              sample_weight = class_sample_weight
          else:
              sample_weight = np.multiply(
                  sample_weight, class_sample_weight
              )
  
      self._n_features = _X.shape[1]
      # copy for consistency
      self._n_features_in = self._n_features
  
      train_set = Dataset(
          data=_X,
          label=_y,
          weight=sample_weight,
          group=group,
          init_score=init_score,
          categorical_feature=categorical_feature,
          params=params,
      )
  
      valid_sets: List[Dataset] = []
      if eval_set is not None:
  
          def _get_meta_data(collection, name, i):
              if collection is None:
                  return None
              elif isinstance(collection, list):
                  return collection[i] if len(collection) > i else None
              elif isinstance(collection, dict):
                  return collection.get(i, None)
              else:
                  raise TypeError(f"{name} should be dict or list")
  
          if isinstance(eval_set, tuple):
              eval_set = [eval_set]
          for i, valid_data in enumerate(eval_set):
              # reduce cost for prediction training data
              if valid_data[0] is X and valid_data[1] is y:
                  valid_set = train_set
              else:
                  valid_weight = _get_meta_data(
                      eval_sample_weight, "eval_sample_weight", i
                  )
                  valid_class_weight = _get_meta_data(
                      eval_class_weight, "eval_class_weight", i
                  )
                  if valid_class_weight is not None:
                      if (
                          isinstance(valid_class_weight, dict)
                          and self._class_map is not None
                      ):
                          valid_class_weight = {
                              self._class_map[k]: v
                              for k, v in valid_class_weight.items()
                          }
                      valid_class_sample_weight = (
                          _LGBMComputeSampleWeight(
                              valid_class_weight, valid_data[1]
                          )
                      )
                      if valid_weight is None or len(valid_weight) == 0:
                          valid_weight = valid_class_sample_weight
                      else:
                          valid_weight = np.multiply(
                              valid_weight, valid_class_sample_weight
                          )
                  valid_init_score = _get_meta_data(
                      eval_init_score, "eval_init_score", i
                  )
                  valid_group = _get_meta_data(
                      eval_group, "eval_group", i
                  )
                  valid_set = Dataset(
                      data=valid_data[0],
                      label=valid_data[1],
                      weight=valid_weight,
                      group=valid_group,
                      init_score=valid_init_score,
                      categorical_feature="auto",
                      params=params,
                  )
  
              valid_sets.append(valid_set)
  
      if isinstance(init_model, LGBMModel):
          init_model = init_model.booster_
  
      if callbacks is None:
          callbacks = []
      else:
          callbacks = copy.copy(
              callbacks
          )  # don't use deepcopy here to allow non-serializable objects
  
      evals_result: _EvalResultDict = {}
      callbacks.append(record_evaluation(evals_result))
  
      self._Booster = train(
          params=params,
          train_set=train_set,
          num_boost_round=self.n_estimators,
          valid_sets=valid_sets,
          valid_names=eval_names,
          feval=eval_metrics_callable,  # type: ignore[arg-type]
          init_model=init_model,
          feature_name=feature_name,
          callbacks=callbacks,
      )
  
      self._evals_result = evals_result
      self._best_iteration = self._Booster.best_iteration
      self._best_score = self._Booster.best_score
  
      self.fitted_ = True
  
      # free dataset
      self._Booster.free_dataset()
      del train_set, valid_sets
      return self
  
imports: import copy
  from inspect import signature
  from pathlib import Path
  from typing import Any, Callable, Dict, List, Optional, Tuple, Union
  import numpy
  import scipy.sparse
  from .basic import Booster, Dataset, LightGBMError, _choose_param_value, _ConfigAliases, _LGBM_BoosterBestScoreType, _LGBM_CategoricalFeatureConfiguration, _LGBM_EvalFunctionResultType, _LGBM_FeatureNameConfiguration, _LGBM_GroupType, _LGBM_InitScoreType, _LGBM_LabelType, _LGBM_WeightType, _log_warning
  from .callback import _EvalResultDict, record_evaluation
  from .compat import SKLEARN_INSTALLED, LGBMNotFittedError, _LGBMAssertAllFinite, _LGBMCheckArray, _LGBMCheckClassificationTargets, _LGBMCheckSampleWeight, _LGBMCheckXY, _LGBMClassifierBase, _LGBMComputeSampleWeight, _LGBMCpuCount, _LGBMLabelEncoder, _LGBMModelBase, _LGBMRegressorBase, dt_DataTable, np_random_Generator, pd_DataFrame
  from .engine import train
label_desc: Use image node_id 8 for calling the LGBMModel obj's underlying member method code with example usage: obj.fit(X, y, sample_weight, init_score, group, eval_set, eval_names, eval_sample_weight, eval_class_weight, eval_init_score, eval_group, eval_metric, feature_name, categorical_feature, callbacks, init_model) and returns: self, None, unknown, collection