Cross-validated ensemble prediction with LGBM, XGBoost, and CatBoost — with safe categorical handling, multi-seed averaging, and artifact return.
Project description
cv-score-predict
A robust utility for cross-validated ensemble prediction that performs per‑fold early stopping and uses the early‑stopped models themselves for prediction. Each fold trains LightGBM, XGBoost, or CatBoost with early stopping on its validation split; the resulting early‑stopped estimators generate both OOF predictions and averaged test predictions. The function also supports custom preprocessing pipelines, safe categorical encoding, repeated CV over multiple seeds, and optional return of trained models and the fitted encoder.
Designed for kagglers, ML engineers, and data scientists who need reliable, leakage-free CV with minimal boilerplate.
✨ Key Features
- Multi-model ensembling: Train and average predictions from LGBM, XGBoost and CatBoost in a single CV run.
- Native categorical support: Automatically encodes string/categorical columns with
OrdinalEncoderand configures models (e.g.,cat_featuresfor CatBoost,enable_categoricalfor XGBoost). - Safe preprocessing: Integrates any scikit-learn-compatible
processorpipeline (e.g.,ColumnTransformer,Pipeline) — fitted per fold to prevent data leakage. - Repeated CV: Average results over multiple random seeds for stable metrics.
- Early stopping: Enabled by default for all models using fold-wise validation.
- Full artifact return: Get OOF predictions, test predictions, trained models, and fitted
OrdinalEncoderfor later use.
📥 Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
X |
pd.DataFrame |
— | Training features. |
y |
Union[pd.Series, np.ndarray] |
— | Target values. |
X_test |
Optional[pd.DataFrame] |
None |
Test set for final prediction. If None, no test predictions are returned. |
pred_type |
str |
— | Either 'classification' or 'regression' (required). |
processor |
Optional[object] |
None |
Preprocessing pipeline with fit_transform and transform methods. Must return a pd.DataFrame (use set_output(transform='pandas')). If None, features are passed through unchanged. |
process_categorical |
bool |
True |
If True, object/category columns are encoded with OrdinalEncoder (using -1 for missing/unseen) and converted to pandas category dtype for model compatibility. |
models |
Union[List[str], str] |
('lgb', 'xgb', 'cb') |
Models to ensemble. Supported: 'lgb' (LightGBM), 'xgb' (XGBoost), 'cb' (CatBoost). |
params_dict |
Optional[Dict[str, dict]] |
None |
Model-specific hyperparameters. Keys: model names; values: param dicts. |
scoring_dict |
Optional[Dict[str, Callable]] |
None |
Metrics for evaluation. Keys: metric names; values: scoring functions (e.g., roc_auc_score). Defaults: {'roc_auc': roc_auc_score} (classification), {'rmse': rmse_fn} (regression). |
decision_threshold |
float |
0.5 |
Threshold to convert probabilities to class labels (classification only). |
n_splits |
int |
5 |
Number of cross-validation folds. |
random_state |
Union[int, List[int]] |
42 |
Seed(s) for reproducibility. If a list, CV is repeated for each seed and results are averaged. |
early_stopping_rounds |
int |
50 |
Early stopping rounds for boosting models (if not overridden in params_dict). |
verbose |
int |
2 |
Logging level: 2 = full per-fold details, 1 = final summary, 0 = silent. |
return_trained |
bool |
False |
If True, returns list of trained model instances (one per model × fold × seed). |
return_oe |
bool |
False |
If True and process_categorical=True, returns the fitted OrdinalEncoder. |
predict_proba |
bool |
True |
For classification: if True, return probabilities; if False, return binary labels (using decision_threshold). Ignored for regression. |
🚀 Installation
pip install cv-score-predict
Requirements:
- Python ≥ 3.8
- Dependencies: numpy, pandas, scikit-learn ≥1.4, lightgbm, xgboost, catboost
📌 Basic Usage
import pandas as pd
import numpy as np
from sklearn.preprocessing import StandardScaler
from sklearn.compose import make_column_transformer
from cv_score_predict import cv_score_predict
# Simulate data
X = pd.DataFrame({
"num": [1, 2, 3, 4, 5, 6, 7, 8],
"cat": ["A", "B", "A", "C", "B", "A", "C", "D"]
})
y = [0, 1, 0, 1, 1, 0, 1, 0]
X_test = pd.DataFrame({"num": [9, 10], "cat": ["B", "E"]})
# Optional processor (applied per fold!)
processor = make_column_transformer(
(StandardScaler(), ["num"]),
remainder="passthrough"
)
# Run CV with 3 seeds → results averaged over seeds & folds
oof_pred, test_pred, _, _ = cv_score_predict(
X=X,
y=y,
X_test=X_test,
pred_type="classification",
processor=processor,
models=["lgb", "xgb"],
process_categorical=True,
random_state=[42, 123, 999],
n_splits=3,
verbose=2,
)
Output will show scores per seed, then final averaged metrics.
🔧 Advanced Usage: Reuse Artifacts for New Data
# Step 1: Run CV and return artifacts
oof, _, trained_models, oe = cv_score_predict(
X,
y,
X_test=None, # we'll predict manually
pred_type="classification",
processor=processor,
models=["lgb", "cb"],
process_categorical=True,
random_state=[42, 123],
n_splits=5,
return_trained=True,
return_oe=True,
)
# Step 2: For deployment: refit processor on FULL TRAINING data
# First: encode categoricals using returned oe
cat_cols = ["cat"]
X_full = X.copy()
X_full[cat_cols] = oe.transform(X_full[cat_cols]).astype('category')
X_new = pd.DataFrame({"num": [7, 8], "cat": [None, "A"]})
# Fit processor on full encoded data
processor = make_column_transformer(
(StandardScaler(), ["num"]),
remainder="passthrough"
)
processor.fit(X_full)
# Apply to new data
X_new_proc = X_new.copy()
X_new_proc[cat_cols] = oe.transform(X_new_proc[cat_cols]).astype('category')
X_new_proc = processor.transform(X_new_proc)
# Predict with all trained models and average
preds = [model.predict_proba(X_new_proc)[:, 1] for model in trained_models]
final_pred = np.mean(preds, axis=0)
📝 Notes
Categorical columns are encoded with OrdinalEncoder(dtype=np.int32) and converted to category dtype for model compatibility. Always use set_output(transform="pandas") in sklearn pipelines to preserve dtypes. The processor used in CV is refit on each fold to prevent data leakage, so there is no single global version. For deployment, refit your preprocessing pipeline on the full training set (as shown in the advanced example).
📄 License
This project is licensed under the MIT License. See the LICENSE file for details.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file cv_score_predict-0.1.2.tar.gz.
File metadata
- Download URL: cv_score_predict-0.1.2.tar.gz
- Upload date:
- Size: 13.3 kB
- Tags: Source
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.7
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
e13a878c269b7e614ab6352fb9629087eb4720685abb538dbd19d378e2ccae42
|
|
| MD5 |
0bfd7740c1bc7fd952dd601279534177
|
|
| BLAKE2b-256 |
127b34cffbf87e922b56ae16d8d0259b57d565603e130ef14f1131604e889d1a
|
Provenance
The following attestation bundles were made for cv_score_predict-0.1.2.tar.gz:
Publisher:
publish.yml on Karabush/cv-score-predict
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
cv_score_predict-0.1.2.tar.gz -
Subject digest:
e13a878c269b7e614ab6352fb9629087eb4720685abb538dbd19d378e2ccae42 - Sigstore transparency entry: 809406660
- Sigstore integration time:
-
Permalink:
Karabush/cv-score-predict@7082acc2e3d59bccc06fbe437cffa8557f602b0a -
Branch / Tag:
refs/tags/v0.1.2 - Owner: https://github.com/Karabush
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
publish.yml@7082acc2e3d59bccc06fbe437cffa8557f602b0a -
Trigger Event:
push
-
Statement type:
File details
Details for the file cv_score_predict-0.1.2-py3-none-any.whl.
File metadata
- Download URL: cv_score_predict-0.1.2-py3-none-any.whl
- Upload date:
- Size: 10.5 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.7
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
b0c1dbcddb8ed25789078d5028ecaf3a29498d0129ecffb12c02a2617c098637
|
|
| MD5 |
a3ecbe6aaf436ead899c73faa9dec368
|
|
| BLAKE2b-256 |
fa0fb0e52bd39b0d4891ed48d0122971627f0cf6644686aff46c9928865af205
|
Provenance
The following attestation bundles were made for cv_score_predict-0.1.2-py3-none-any.whl:
Publisher:
publish.yml on Karabush/cv-score-predict
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
cv_score_predict-0.1.2-py3-none-any.whl -
Subject digest:
b0c1dbcddb8ed25789078d5028ecaf3a29498d0129ecffb12c02a2617c098637 - Sigstore transparency entry: 809406661
- Sigstore integration time:
-
Permalink:
Karabush/cv-score-predict@7082acc2e3d59bccc06fbe437cffa8557f602b0a -
Branch / Tag:
refs/tags/v0.1.2 - Owner: https://github.com/Karabush
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
publish.yml@7082acc2e3d59bccc06fbe437cffa8557f602b0a -
Trigger Event:
push
-
Statement type: