pip install lightgbm★Prebuilt CPU wheels for all major platforms.import lightgbm as lgb★Core module — Dataset, train, cv, plotting.from lightgbm import LGBMClassifier, LGBMRegressor★scikit-learn-compatible estimators.lgb.__version__Check installed version.
lgb.Dataset(X, label=y)★Wraps data; discretizes features into bins.lgb.Dataset(X_val, y_val, reference=train_set)★Validation set aligned to training bins.lgb.Dataset(X, label=y, categorical_feature=['c1','c2'])Native categorical handling — no one-hot.lgb.Dataset(X, label=y, weight=w)Per-row sample weights.train_set.set_weight(w)Set weight after construction.lgb.Dataset(csr_matrix)Accepts scipy sparse matrices directly.
bst = lgb.train(params, train_set, num_boost_round=100)★Core training loop; returns a Booster.lgb.train(…, valid_sets=[val_set], valid_names=['valid'])★Track metrics on held-out data each round.lgb.train(…, callbacks=[…])★Modern way to attach early stopping / logging.bst.predict(X_test)★Predict using all trees (or best_iteration).bst.predict(X, num_iteration=bst.best_iteration)Predict up to the best early-stopped round.bst.predict(X, pred_contrib=True)SHAP-style per-feature contributions.
LGBMRegressor(**params).fit(X, y)★Regression estimator; default objective 'regression'.LGBMClassifier(**params).fit(X, y)★Binary/multiclass; default objective 'binary'.model.fit(X, y, eval_set=[(X_val,y_val)])★Enables validation tracking + early stopping.model.predict(X_test)★Class labels (classifier) or values (regressor).model.predict_proba(X_test)Class probabilities — classifier only.LGBMRanker(**params).fit(X, y, group=train_groups)Learning-to-rank; needs query group sizes.model.booster_ / model.feature_importances_Underlying Booster and importances array.
num_leaves31★Max leaves per tree — the main complexity knob.max_depth-1★Cap tree depth;-1= no limit. Tree still grows leaf-wise.learning_rate0.1★Shrinkage per tree (aliaseta).n_estimators100★Boosting rounds —num_boost_roundin native API.boosting_type'gbdt'gbdt·dart(dropout trees) ·rf(random forest).objective'regression'Task + loss function — see card 09.
min_data_in_leaf20★Min samples per leaf — the anti-overfit knob (aliasmin_child_samples).min_sum_hessian_in_leaf1e-3Min Hessian sum per leaf (aliasmin_child_weight).lambda_l1/lambda_l20.0L1/L2 leaf-weight penalties (aliasesreg_alpha/reg_lambda).min_gain_to_split0.0Minimum gain to accept a split (aliasmin_split_gain).max_bin255Fewer bins → coarser splits → more regularization.path_smooth0.0Shrinks leaf output toward its parent's — helps sparse leaves.
feature_fraction1.0★Fraction of features sampled per tree (aliascolsample_bytree).bagging_fraction+bagging_freq★Row sub-sampling every k rounds (aliassubsample). Needsbagging_freq>0to activate.feature_fraction_bynode1.0Re-sample features at every split, not just per tree.extra_treesFalseExtremely-randomized trees — one random threshold per feature.data_sample_strategy='goss'Gradient-based One-Side Sampling instead of bagging.
categorical_feature=['c1','c2']★By name (Dataset) or index; ~8× faster than one-hot.df['col'].astype('category')★pandas categorical dtype is auto-detected.max_cat_to_onehot4≤ this many categories → one-vs-rest split.max_cat_threshold32Cap on split points searched for larger categoricals.cat_smooth/cat_l210.0Smoothing/L2 to reduce noise in low-count categories.
objective='regression'★L2 loss (default); alsol1,huber,quantile,poisson,gamma,tweedie.objective='binary'★Log-loss classification; labels must be {0, 1}.objective='multiclass', num_class=k★Softmax over k classes.objective='lambdarank'Pairwise ranking; needsgroup/query data.objective='rank_xendcg'Faster ranking loss, similar accuracy to lambdarank.
metric='rmse'/'l1'/'mape'Regression metrics.metric='binary_logloss'/'auc'★Binary classification metrics.metric='multi_logloss'Multiclass log-loss.metric='ndcg'/'map'Ranking metrics; use witheval_at.metric=['auc','binary_logloss']Multiple metrics — all logged, first used for early stopping iffirst_metric_only.
lgb.early_stopping(stopping_rounds=50)★Stop if a metric hasn't improved in N rounds.lgb.log_evaluation(period=10)★Print validation metrics every N rounds.lgb.record_evaluation(eval_result)Capture metric history into a dict for plotting.callbacks=[lgb.early_stopping(50), lgb.log_evaluation(10)]★Pass a list totrain()or.fit().bst.best_iteration / model.best_iteration_Round selected by early stopping.
lgb.cv(params, train_set, nfold=5)★Returns per-round mean/stdv of each metric.lgb.cv(…, stratified=True, shuffle=True)Stratified folds for classification (default True).lgb.cv(…, callbacks=[lgb.early_stopping(50)])Early stop each fold consistently.lgb.cv(…, return_cvbooster=True)Get the fitted per-fold boosters back.
bst.feature_importance(importance_type='split')★Counts of times a feature was split on (or'gain').lgb.plot_importance(bst)★Bar chart of feature importances.lgb.plot_metric(eval_result)Training/validation curve over rounds.lgb.plot_tree(bst, tree_index=0)Render one tree's structure.lgb.create_tree_digraph(bst)Graphviz digraph of a single tree.
bst.save_model('model.txt')★Human-readable native format.lgb.Booster(model_file='model.txt')★Reload a native Booster for prediction.bst.model_to_string()Serialize to an in-memory string.joblib.dump(model, 'model.pkl')★Pickle the sklearn-wrapper estimator instead.lgb.train(…, init_model='model.txt')Continue training from a saved model.
num_leaves = 2**max_depthoverfitsFull-depth leaf count is too many for leaf-wise growth — use fewer.pd.get_dummies(df)avoidDon't one-hot categoricals — passcategorical_featureinstead.callbacks=[lgb.early_stopping(50)]needs valid_setsErrors without a validation set + metric; no effect underdart.feature_pre_filterdefault TrueSilently drops features when re-tuningmin_data_in_leafon a reused Dataset — setFalse.zero_as_missingdefault FalseZeros are not treated as missing unless you opt in.