pip install catboost★CPU + GPU support in one wheel.from catboost import CatBoostClassifier★Binary / multi-class / multilabel.from catboost import CatBoostRegressor★Regression, incl. multi-target & uncertainty.from catboost import CatBoostRankerLearning-to-rank (needs group_id).from catboost import Pool, cv, sum_models★Data container, CV, model averaging.from catboost import utilsROC curves, thresholds, metric eval (card 17).catboost.__version__Check installed version.
Pool(X, y, cat_features=[...])★Wraps features + labels + column roles.model.fit(X, y, cat_features=[...])★fit() also takes raw arrays/DataFrames — Pool optional.Pool('data.tsv', column_description='cd')Load straight from file; utils.create_cd() writes the cd.Pool(…, weight=w, group_id=g)Sample weights; query groups for ranking.Pool(…, text_features=[...], embedding_features=[...])Raw text and float-vector columns as native types.pool.set_baseline(preds)Boost on top of another model's raw predictions.pool.quantize()speedPre-bin once; reuse across many training runs.pool.get_feature_names() · pool.num_row()Inspect after loading.
cat_features=[idx or name, ...]★coreNever one-hot these yourself — kills feature combinations.# Ordered Target Statistics + priordefaultEncodes each row from earlier rows only (formula below) — no target leak.one_hot_max_size=2Cardinality ≤ this → one-hot instead of CTR stats.max_ctr_complexity=4Max cat columns combined into CTR interaction features.simple_ctr= · combinations_ctr=[...]Fine-grained control of CTR types (Borders, Counter…).text_features=[...]Auto tokenization + dictionaries + BoW/NaiveBayes features.from catboost.text_processing import Tokenizer, DictionaryStandalone text-processing module.has_time=TrueUse given row order (time series), not random permutations.float cat columnserrorCategorical columns must be int or string — cast floats first.
iterations=1000★Trees to build; aliases n_estimators, num_boost_round.learning_rate=None → auto★Auto-picked from data size & iterations; else 0.03.depth=6★Tree depth; typical 4–10 (16 max for Lossguide).loss_function='Logloss'★Sets the ML task — full menu in card 20.eval_metric='AUC'★Watched metric for OD & best-model; ≠ optimized loss.custom_metric=['F1','Precision']Extra metrics logged, never optimized.random_seed=42Reproducibility of permutations & sampling.iterations + n_estimators togethererrorUsing two aliases of one param raises an error.
grow_policy='SymmetricTree'defaultOne split condition per level — fast, regularized.grow_policy='Depthwise'XGBoost-style: split all non-terminal leaves per level.grow_policy='Lossguide'LightGBM-style: best-leaf-first until max_leaves.min_data_in_leaf=1Min samples per leaf — Depthwise/Lossguide only.max_leaves=31Lossguide only; >64 slows training badly.score_function='Cosine'Split scoring: Cosine · L2 · NewtonL2 · NewtonCosine.non-symmetric treescaveatExport only to cbm/json; ~10× slower prediction; no PredictionDiff.
boosting_type='Ordered'signatureUnbiased; best on small data; slower. Auto-chosen by size.boosting_type='Plain'Classic GBDT scheme — default for larger datasets.bootstrap_type='MVS'|'Bayesian'|'Bernoulli'|'Poisson'Row-weight sampling; MVS(0.8) common CPU default.subsample=0.8Row fraction — Bernoulli/Poisson/MVS bootstraps.bagging_temperature=1Bayesian bootstrap intensity (0 = off).rsm=1.0Feature fraction per split (colsample_bylevel); CPU.leaf_estimation_method='Newton'|'Gradient'|'Exact'+ leaf_estimation_iterations steps per leaf.langevin=TrueSGLBStochastic Gradient Langevin Boosting — enables uncertainty.
l2_leaf_reg=3.0★L2 on leaf values (reg_lambda); raise to regularize.random_strength=1Noise added to split scores — decorrelates trees.model_size_reg=0.5Penalize CTR-heavy splits to shrink model size.monotone_constraints={'price':-1,'age':1}Force non-increasing (-1) / non-decreasing (1) response.ignored_features=[...]Exclude columns without rebuilding the dataset.feature_weights= · first_feature_use_penalties=Bias split selection toward/away from features.nan_mode='Min'★NaN → min ('Min', default) / max ('Max') / error ('Forbidden'). No imputation needed.
auto_class_weights='Balanced'★Auto multipliers from class totals (formula below).auto_class_weights='SqrtBalanced'Softer √-scaled variant.class_weights=[1, 10] or {'a':1,'b':10}Manual per-class multipliers.scale_pos_weight=neg/posBinary shortcut: weight of class 1.class_weights + auto_class_weightsconflictMutually exclusive; also skews predicted probabilities — recalibrate if you need true probs.
model.fit(train_pool, eval_set=val_pool)★eval_set accepts Pool, (X,y), or a list of them.model.fit(…, verbose=100, plot=True)Log every N iters; live Jupyter chart.model.fit(…, init_model=prev)Continue boosting from an existing model.save_snapshot=True, snapshot_file='snap'Crash-safe: rerun the same script to resume.sum_models([m1, m2], weights=[.5,.5])Blend trained models into one artifact.to_classifier(m) · to_regressor(m)Convert generic CatBoost to typed estimator.baseline=predsTwo-stage modeling: boost on residuals of a base model.
eval_set=(X_val, y_val)★Scored per iteration by eval_metric.early_stopping_rounds=50★Sets OD type to Iter: stop after N stale rounds.use_best_model=True★Shrink final model to the best iteration.use_best_model without eval_setignoredSilently does nothing without validation data.od_type='IncToDec', od_pval=1e-5…1e-10Statistical detector alternative to plain Iter.model.get_best_iteration() · best_score_Where and how good the optimum was.model.shrink(ntree_end=N)Manually truncate a trained model to N trees.
model.predict(X)★Labels / values; thread-parallel by default.model.predict_proba(X)★Class probabilities (classifier).predict(X, prediction_type='RawFormulaVal'|'Class'|'Probability'|'Exponent')Raw score before link function, etc.model.staged_predict(X)Prediction after each tree — fast learning curves.predict(X, ntree_start=a, ntree_end=b)Apply only a tree range.model.calc_leaf_indexes(X)Leaf ids per tree — embeddings for downstream models.model.eval_metrics(pool, ['AUC','F1'])Any metric post-hoc, per iteration.model.score(X, y)Accuracy (clf) / R² (reg) shortcut.
loss_function='RMSEWithUncertainty'Predicts [mean, variance] — data (aleatoric) uncertainty.posterior_sampling=TrueSGLB preset (langevin + shrink rate + temperature) with theory guarantees.model.virtual_ensembles_predict(X, prediction_type='TotalUncertainty', virtual_ensembles_count=10)One model → N truncated sub-models → knowledge (epistemic) uncertainty.prediction_type='VirtEnsembles'Raw per-sub-model predictions instead of summary.mean ± 1.96·√varPrediction intervals from RMSEWithUncertainty output.
model.get_feature_importance()★Default PredictionValuesChange (LossFunctionChange for ranking).get_feature_importance(type='ShapValues', data=pool)★Exact per-object SHAP; plugs into the shap package.get_feature_importance(type='Interaction')Pairwise feature-interaction strengths.get_feature_importance(type='PredictionDiff', data=two_rows)Why did these 2 objects get different predictions? (symmetric trees only)model.get_object_importance(pool, train_pool)Which training rows most affected these predictions.model.calc_feature_statistics(pool)Per-bucket mean prediction vs mean target plots.model.plot_tree(tree_idx=0, pool=p)Render one tree (graphviz).model.compare(other, pool, metrics=[...])Side-by-side metric curves of two models.model.select_features(…)Built-in RFE with SHAP-based selection.
cv(pool, params, fold_count=5)★Stratified for classification by default; mean ± std per iter.cv(…, type='TimeSeries')Expanding-window CV for temporal data.model.grid_search(grid, X, y, cv=3)★Exhaustive; refits best combo; returns cv_results.model.randomized_search(dists, n_iter=10)Sampled search; accepts scipy distributions.# sklearn compatibleWorks in Pipeline, GridSearchCV, cross_val_score.# Optuna + CatBoostPruningCallbackOfficially recommended for serious tuning; prunes bad trials.# tune order: iterations+lr → depth → l2_leaf_regThen random_strength / bagging_temperature / one_hot_max_size.
task_type='GPU'★Huge speedup on large data; needs NVIDIA driver ≥ 450.80.02.devices='0:1'Multi-GPU by id range.thread_count=-1All CPU cores (train & predict).border_count=128 (GPU) / 254 (CPU)Numeric bins; 254 on GPU = max quality, slower.utils.get_gpu_device_count()Verify CatBoost sees your GPUs.used_ram_limit= · gpu_ram_part=Cap memory usage on shared machines.GPU ≠ CPU exactlynuanceSome params/metrics differ or are unsupported on GPU (e.g. rsm limited, MVS is CPU-only); results won't be bit-identical.
model.save_model('m.cbm')★Native binary — lossless, fastest.model = CatBoostClassifier(); model.load_model('m.cbm')★Instantiate first, then load.save_model('m.onnx', format='onnx')ONNX for cross-platform inference.format='json'|'coreml'|'pmml'|'cpp'|'python'Inspectable JSON, iOS, PMML, or source-code export.cat features limit exportscaveatcoreml/cpp/python exporters support only some cat-feature setups; cbm/json always work.model.get_metadata()Key-value store inside the model (guid, your tags).
get_roc_curve(model, pool)(fpr, tpr, thresholds) — plus get_fpr_curve / get_fnr_curve.select_threshold(model, data, FNR=0.01)Pick a probability cutoff for a target error rate.get_confusion_matrix(model, pool)Confusion matrix straight from a Pool.eval_metric(y, preds, 'AUC')Compute any CatBoost metric on arbitrary arrays.create_cd(…)Write a column-description file for file-based Pools.
class MyLoss: def calc_ders_range(…)Return (grad, hess) pairs → loss_function=MyLoss().class MyMetric: def evaluate(…) …is_max_optimal / get_final_error → eval_metric=MyMetric().custom Python lossslowPython callbacks disable some optimizations & GPU — prefer built-ins.
catboost-sparkDistributed training on Apache Spark (Scala/PySpark).CLI: catboost fit --learn-set …Full-featured command-line trainer.R package · Java/C++/Rust/.NET appliersTrain anywhere, serve the .cbm nearly everywhere.shap · Optuna · MLflow · ONNX RuntimeFirst-class integrations with the standard MLOps stack.model.plot_partial_dependence(pool)PDPs without leaving CatBoost.
Logloss · CrossEntropyBinary: hard 0/1 labels · probabilistic targets.MultiClass · MultiClassOneVsAllSingle-label multi-class.MultiLogloss · MultiCrossEntropyMultilabel — several 0/1 targets at once.RMSE · MAE · Quantile · MAPE · HuberRegression by error shape / robustness.Poisson · TweedieCounts & zero-inflated positive targets (insurance).MultiRMSEMulti-target regression (vector y).RMSEWithUncertaintyMean + variance per prediction.YetiRank · YetiRankPairwise · PairLogit · QueryRMSERanking — all require group_id.