Skip to content
v0.1.3latest release121 skills4 categories6 sub-categories247 tested scripts397 reference docsContact us

catboost-model-builder

Build CatBoost models that use its strengths correctly: raw categorical columns as cat_features (ordered target statistics, no manual encoding), text_features, Pool construction with NaN-safe categories, ordered boosting and has_time for temporal data, symmetric (oblivious) trees, overfitting detector with eval_set and use_best_model, losses for classification, regression (Quantile, Poisson, Tweedie) and ranking (YetiRank), class weights, monotone constraints, feature importance (PredictionValuesChange, LossFunctionChange) and SHAP values, GPU training and model export. Plans cat/text/numeric columns from a CSV and generates a runnable training script, and checks parameter sets for the conflicts CatBoost rejects (iterations vs n_estimators, Bayesian bootstrap with subsample, multiple class-weight options, depth > 16, use_best_model without eval_set). Use when someone builds or tunes a CatBoost model, has many categorical or high-cardinality features, or hits CatBoostError messages.

AI & Machine Learning / Classical Machine Learningv1.0.0Updated OCT 25 20264 references2 scripts

CatBoost's advantage is categorical data: give it raw categorical columns and it computes target statistics in an ordered, leakage-free way (each row is encoded using only rows before it in a random permutation), builds combinations of categoricals, and trains symmetric trees that are fast at inference. Most CatBoost mistakes come from fighting that: one-hot or target encoding beforehand, NaN in categorical columns, float-typed category codes, or a random split on temporal data. scripts/catboost_plan.py sorts a CSV's columns into cat / text / numeric / dropped and generates a training script (verified with CatBoost 1.2 for binary, multiclass-with-text and Tweedie regression); scripts/catboost_params_check.py catches parameter conflicts before a long run.

Trigger Conditions

Activate this skill when the user:

  • Builds a CatBoost classifier/regressor/ranker, or asks how to pass categorical or text features
  • Has many categorical or high-cardinality columns and is unsure whether to encode them first (do not)
  • Gets CatBoostError (invalid cat feature values, NaN in categoricals, conflicting parameters, depth limit)
  • Needs CatBoost tuning, class weights, monotone constraints, SHAP values or model export
  • Compares CatBoost with LightGBM/XGBoost (name map in xgboost-lightgbm-tuner)

Workflow

text
1. PLAN      -> python scripts/catboost_plan.py data.csv --target y --drop id [--time-col ts]
2. PREPARE   -> cat columns as str (NaN -> "__nan__"), text columns as str, dates -> derived parts
3. SPLIT     -> train / validation (for the overfitting detector) / test; time order if temporal
4. CHECK     -> python scripts/catboost_params_check.py params.json --task binary --has-eval-set
5. TRAIN     -> Pool(..., cat_features, text_features); fit(eval_set=valid_pool, use_best_model=True)
6. TUNE      -> learning_rate x iterations, depth, l2_leaf_reg, random_strength, bagging_temperature
7. EXPLAIN   -> get_feature_importance (PredictionValuesChange / LossFunctionChange / ShapValues)
8. EXPORT    -> save_model("m.cbm") (or ONNX/CoreML/JSON); store the column order and cat list

Minimal Correct Model

python
from catboost import CatBoostClassifier, Pool

for c in CAT:                                         # strings or ints, never NaN or floats
    X[c] = X[c].astype("string").fillna("__nan__").astype(str)

train_pool = Pool(X_tr, y_tr, cat_features=CAT, text_features=TEXT or None)
valid_pool = Pool(X_va, y_va, cat_features=CAT, text_features=TEXT or None)

model = CatBoostClassifier(loss_function="Logloss", eval_metric="AUC", custom_metric=["PRAUC"],
                           iterations=5000, learning_rate=0.05, depth=6, l2_leaf_reg=3,
                           od_type="Iter", od_wait=200, random_seed=0, allow_writing_files=False, verbose=500)
model.fit(train_pool, eval_set=valid_pool, use_best_model=True)
proba = model.predict_proba(Pool(X_te, cat_features=CAT, text_features=TEXT or None))[:, 1]

Generated in full (split, metrics, importances, SHAP, save) by catboost_plan.py --code.

Features: What Goes Where

Column typeCatBoost handlingPrepare
Nominal categorical (any cardinality)cat_features: ordered CTRs (target statistics) + combinationsastype(str), NaN -> "__nan__"; no encoding
Numeric code with meaning only as a label (zip, store id)cat_featurescast to str; near-unique codes -> a prefix (zip3)
Low-cardinality categorical (<= one_hot_max_size, default 2; up to 255 on GPU)one-hot internallynothing
Free texttext_features: tokenised, bag-of-words + naive Bayes / BM25 estimatesastype(str), NaN -> ""
Dense embeddingsembedding_features (LDA / KNN estimators)list/array column per row
Numericas is; NaN allowed (nan_mode="Min" by default)nothing
Datesnot nativederive year, month, day of week, days since
IDsdrop-

Mechanics of ordered target statistics, CTR types, feature combinations and text/embedding processing: catboost-essentials.md.

Temporal Data

  • Split by time (train on the past, validate and test on later periods).
  • has_time=True makes CatBoost use the given row order instead of random permutations for ordered boosting and target statistics: sort rows by time first.
  • The overfitting detector's eval_set should be the most recent training period, not a random sample.

Key Parameters

ParameterDefaultTuneNotes
iterations + learning_rate1000, autolr 0.03-0.1 with early stoppingCatBoost picks lr automatically if unset
depth64-10symmetric trees: 2^depth leaves; > 16 is rejected
l2_leaf_reg31-10 (log)main regulariser
random_strength10.5-10noise on split scores
bagging_temperature10-1+Bayesian bootstrap only
bootstrap_typeMVS / BayesianBernoulli + subsample 0.6-0.9subsample is invalid with Bayesian
border_count254 (CPU)32-254numeric binning
one_hot_max_size22-10one-hot threshold for categoricals
max_ctr_complexity41-4categorical combinations (lower = faster)
grow_policySymmetricTreeDepthwise / Lossguide (+ max_leaves)non-symmetric trees: slower inference
auto_class_weightsNoneBalanced / SqrtBalancedonly one of this, class_weights, scale_pos_weight
od_type, od_wait-Iter, 100-300overfitting detector

Tuning order, Optuna space and GPU notes: parameters-and-tuning.md.

Conflicts CatBoost Rejects

catboost_params_check.py mirrors the errors CatBoost 1.2 raises (checked against the library):

CodeConflict
CB001iterations and n_estimators / num_boost_round / num_trees together
CB002learning_rate and eta together
CB003more than one of scale_pos_weight, class_weights, auto_class_weights
CB004bootstrap_type="Bayesian" with subsample; bagging_temperature without Bayesian
CB005depth > 16
CB006use_best_model=True without eval_set

Plus warnings for silently ignored settings (max_leaves without grow_policy="Lossguide"), no overfitting detector, task/loss mismatches, extreme learning rates, deep trees and zero L2.

Explaining and Exporting

python
imp = model.get_feature_importance(train_pool, prettified=True)              # PredictionValuesChange
loss_imp = model.get_feature_importance(valid_pool, type="LossFunctionChange")  # needs labels, honest
shap = model.get_feature_importance(test_pool, type="ShapValues")          # (n, features + 1); last col = expected value
inter = model.get_feature_importance(train_pool, type="Interaction")       # strongest feature pairs
model.save_model("model.cbm")              # also "json", "cpp", "python"; ONNX only without cat_features

For multiclass, ShapValues has shape (n, classes, features + 1). Pitfalls (category order at inference, predict vs predict_proba, prediction_type, thread settings, determinism): catboost-pitfalls.md.

Output Format

When building a CatBoost model, deliver:

  1. Column plan - cat / text / numeric / dropped with reasons (catboost_plan.py).
  2. Split - train / validation (detector) / test, time order and has_time if temporal.
  3. Parameters - with the catboost_params_check.py result.
  4. Training code - Pool construction and fit with eval_set and use_best_model.
  5. Results - best iteration, validation and test metrics, importances (LossFunctionChange preferred).
  6. Export - saved model format, column order, cat feature list, version pin.

Scripts

bash
python scripts/catboost_plan.py data.csv --target churned --drop customer_id
python scripts/catboost_plan.py data.csv --target churned --time-col signup_date --code -o train_catboost.py
python scripts/catboost_plan.py tickets.csv --target queue --drop ticket_id --code
python scripts/catboost_plan.py claims.csv --target claim_amount --loss "Tweedie:variance_power=1.5" --code

Classifies columns into cat_features (non-numeric, plus code-like numerics), text_features (mean length >= 30 and

= 4 words), numeric, and dropped (constant, near-unique IDs, dates, the time column); picks CatBoostClassifier (Logloss / AUC + PRAUC, or MultiClass / TotalF1) or CatBoostRegressor (RMSE, or the --loss you give); --code emits a script with NaN-safe category casting, time or stratified train/valid/test split, overfitting detector, has_time for temporal data, test metric, importances, SHAP and save_model. Exit codes: 0 printed/written, 2 usage or read error.

bash
python scripts/catboost_params_check.py params.json --task binary --has-eval-set
echo '{"iterations": 5000, "n_estimators": 100}' | python scripts/catboost_params_check.py -

Rules CB001-CB014 (errors CB001-CB006 confirmed against CatBoost 1.2). Exit codes: 0 no errors, 1 errors, 2 read error.

Additional Resources

FileContent
catboost-essentials.mdOrdered boosting, ordered target statistics and CTR types, feature combinations, symmetric trees, text and embedding features, Pool API
parameters-and-tuning.mdParameter reference, tuning order and Optuna space, imbalance, monotone constraints, GPU training, speed tips
catboost-pitfalls.mdNaN and float categories, category consistency at inference, importance types, SHAP shapes, prediction types, determinism, common CatBoostError messages
deployment.mdsave/load formats (cbm, ONNX, CoreML, JSON, C++), fast inference, versioning, applying models in other languages
More in Classical Machine Learning

anomaly-detection-model-builder

Build and evaluate anomaly detection for tabular, sensor and transaction data with few or no labels: define the anomaly type (point, contextual, collective), choose detectors (robust z-score/MAD and IQR rules, Mahalanobis with robust covariance, k-NN distance, LOF, Isolation Forest, one-class SVM, PCA reconstruction / autoencoders, forecasting residuals for time series), combine them by rank, explain each alert by its deviating features, set thresholds from an alert budget or the score distribution, and evaluate with precision@k, PR-AUC and recall on known incidents, or detector agreement when no labels exist. Includes pure-Python detectors (robust z, Mahalanobis, kNN, Isolation Forest, ensemble) and an evaluation script.

categorical-encoding-selector

Choose and implement the right encoding for every categorical column given the model family and the data: one-hot (with infrequent-level grouping and handle_unknown), ordinal with an explicit order, cross-fitted target encoding (scikit-learn TargetEncoder, CatBoost ordered statistics, category_encoders inside CV), frequency/count encoding, feature hashing, native categorical support in LightGBM, HistGradientBoosting, XGBoost and CatBoost, prefix levels for codes (zip3, NAICS-2), and embeddings. Measures cardinality, rare-level share, unseen-level rate on a time-ordered holdout and target signal per column, emits the ColumnTransformer, and quantifies target-encoding leakage (in-sample vs out-of-fold vs holdout AUC).

classification-model-selector

Choose the right classification algorithm for tabular, text or mixed data and prove the choice with a fair bake-off: logistic regression (L2, L1, elastic net), linear SVM, naive Bayes, k-NN, RBF SVM, decision trees, random forest, extra trees, HistGradientBoosting, LightGBM, XGBoost, CatBoost, explainable boosting machines (EBM/GAM), points scorecards and MLPs, matched to data size, width, categorical and high-cardinality share, missingness, class imbalance, text, and constraints such as interpretability, monotonic constraints, calibrated probabilities, latency budgets and tiny deployable models. Ranks candidates with starting hyperparameters and cautions, then generates a bake-off script running every candidate on identical CV folds with per-fold metrics, fit time and prediction latency.

clustering-algorithm-selector

Choose the right clustering algorithm and check that clustering makes sense at all: cluster tendency (Hopkins statistic with a correlated-features caveat, nearest-neighbour isolation), then k-means / MiniBatchKMeans, Gaussian mixtures with BIC, agglomerative (Ward, average, complete, single) with dendrograms, DBSCAN, HDBSCAN, OPTICS, spectral clustering, BIRCH, mean shift, k-prototypes and k-modes for mixed or categorical data, and Gower distance, matched to data size, expected shapes, noise, varying density, known k, soft memberships, hierarchy and streaming. Covers preprocessing (scaling, encoding, dimensionality, distance metrics), validation (internal indices, bootstrap stability, external labels, business profiling) and assigning new points.

collaborative-filtering-implementer

Implement collaborative filtering recommenders that beat popularity: item-based kNN with cosine, Jaccard or asymmetric similarity, shrinkage, neighbourhood size, positive-only or mean-centred rating signals and 'because you liked X' explanations; implicit ALS with confidence weighting, BPR pairwise ranking and the closed-form EASE model in plain NumPy, tuned on a temporal validation split by recall@k and NDCG@k and refit on all data; plus user-kNN, explicit matrix factorisation, the implicit/LightFM libraries, hyperparameter ranges, cold-start fallbacks, scaling with sparse matrices and approximate nearest neighbours. Produces top-k lists in the format of the recommendation evaluator.

counterfactual-explanation-generator

Generate counterfactual explanations and algorithmic recourse: the smallest realistic change to a row's features that changes the model's decision. Solves exact minimal-cost recourse for linear and logistic models (MAD-scaled L1 cost, immutable features, increase/decrease directions, bounds, integer and binary features, diverse alternatives, features every counterfactual must change, and a no-recourse finding when immutable features decide), generates DiCE counterfactuals for any scikit-learn model with constraints turned into permitted ranges and every result re-predicted, and validates counterfactuals from any method for constraint violations, implausible values, off-manifold rows, broken derived-feature relations and failure to flip the prediction.