Skip to content

XGBoost

Train, tune, score and explain gradient-boosted tree models on your tables with plain SQL

Connector software
Free and open source
Service credentials
Not needed
Use with an agent

Install the Orchard skill in your project to help your agent find connectors, configure them, and verify SQL results.

npx skills add Query-farm/vgi-skills --skill orchard

Copy this request into your coding agent to get started.

Use https://query.farm/products/orchard/connectors/xgboost/index.md to help me query XGBoost with DuckDB or Haybarn 2.0.1 and VGI protocol 3.4. Ask only for missing details about the result I need or whether I want local execution, self-hosting or Query Farm hosting. Check the connector's actual hosting availability, credentials and input requirements. Read one format of each needed reference and the exact object declarations before writing SQL. Use a released connector, and distinguish a saved example result from anything you actually execute. If you cannot run the query, tell me what remains to verify.

Train a classifier and predict from SQL

Example output · captured
Connector release
v0.2.0
Engine
2.0.1
VGI protocol
3.4.0
SET VARIABLE iris_model = (SELECT model FROM xgboost.main.fit((SELECT * FROM xgboost.main.iris), estimator := 'xgb_classifier', target := 'target', id := 'sample_id'));
SELECT sample_id, prediction FROM xgboost.main.predict((SELECT * FROM xgboost.main.iris), model := getvariable('iris_model'), id := 'sample_id') LIMIT 5;
Result
sample_id prediction
0 0
1 0
2 0
3 0
4 0

Quick start

Choose where to run XGBoost, then follow the steps below.

The connector runs alongside DuckDB or Haybarn. No Query Farm account is needed.

1. Install the vgi extension

Run this in your SQL client. On DuckDB, keep FROM query_farm on LOAD in later sessions.

setup.sql
SET allow_extension_repositories = 'allowed';

CREATE EXTENSION REPOSITORY IF NOT EXISTS query_farm
    WITH PREFIX 'https://duckdb-extensions.query.farm';

INSTALL vgi FROM query_farm;
LOAD vgi FROM query_farm;

2. Attach the connector

Attach with uv

Needs uv. uv fetches the worker script and its package at the release tag on first attach and reuses the cached environment after that.

ATTACH 'xgboost' AS xgboost (
  TYPE vgi,
  LOCATION 'uv run --with git+https://github.com/Query-farm/[email protected] https://raw.githubusercontent.com/Query-farm/vgi-xgboost/v0.2.0/xgboost_worker.py'
);

3. Run a query

query.sql
SET VARIABLE iris_model = (SELECT model FROM xgboost.main.fit((SELECT * FROM xgboost.main.iris), estimator := 'xgb_classifier', target := 'target', id := 'sample_id'));
SELECT sample_id, prediction FROM xgboost.main.predict((SELECT * FROM xgboost.main.iris), model := getvariable('iris_model'), id := 'sample_id') LIMIT 5;
More example queries →
Technical details
Verified connector release
v0.2.0
Engine
2.0.1
VGI protocol
3.4.0
Verified on
December 1, 2026
Release notes on GitHub
Pin a version for production

When running the connector yourself, keep a specific release until you’re ready to upgrade. Replace the ATTACH statement above with this one and follow the same extension and credential setup.

Attach with uv

Needs uv. uv fetches the worker script and its package at the release tag on first attach and reuses the cached environment after that.

ATTACH 'xgboost' AS xgboost (
  TYPE vgi,
  LOCATION 'uv run --with git+https://github.com/Query-farm/[email protected] https://raw.githubusercontent.com/Query-farm/vgi-xgboost/v0.2.0/xgboost_worker.py'
);

Overview

XGBoost train/predict model registry, datasets, and interpretation for DuckDB/SQL

Catalog

Everything xgboost exposes once attached — read straight from the worker's released build.

xgboost 1 schema
main 6 tables · 18 functions

XGBoost train/predict model registry, datasets, and interpretation for SQL

Schema examples (3)
Examples (3)

Fit an XGBoost classifier on iris and return the training summary

SELECT estimator, task, n_samples, n_features, train_score
FROM xgboost.main.fit((SELECT * FROM xgboost.main.iris), estimator := 'xgb_classifier', target := 'target', id := 'sample_id');

Out-of-fold confusion matrix for an XGBoost iris classifier: 5-fold cross_val_predict on the species name, joined back to the iris table by sample_id and counted per (actual, predicted) species pair. Only non-empty cells are returned; the off-diagonal rows are the held-out misclassifications, almost all of them versicolor/virginica mix-ups.

SELECT i.target_name AS actual_species, cv.prediction AS predicted_species,
  count(*) AS n_flowers
FROM xgboost.main.cross_val_predict((SELECT sample_id, sepal_length_cm, sepal_width_cm, petal_length_cm, petal_width_cm, target_name FROM xgboost.main.iris), estimator := 'xgb_classifier', target := 'target_name', id := 'sample_id', cv := 5) AS cv
JOIN xgboost.main.iris AS i USING (sample_id)
GROUP BY ALL
ORDER BY actual_species, predicted_species;

Where does an XGBoost regressor miss? 5-fold out-of-fold predictions on diabetes joined back to the patients, with the held-out mean absolute error and mean progression score per BMI quartile (1 = lowest BMI).

SELECT d.bmi_quartile, count(*) AS patients,
  round(avg(abs(cv.prediction - d.target)), 1) AS oof_mae,
  round(avg(d.target), 1) AS mean_progression
FROM xgboost.main.cross_val_predict((SELECT * FROM xgboost.main.diabetes), estimator := 'xgb_regressor', target := 'target', id := 'sample_id', cv := 5) AS cv
JOIN (SELECT sample_id, target, ntile(4) OVER (ORDER BY bmi, sample_id) AS bmi_quartile FROM xgboost.main.diabetes) AS d USING (sample_id)
GROUP BY d.bmi_quartile
ORDER BY d.bmi_quartile;
Tables
breast_cancer 2 examples33 cols

569 tumour samples with 30 cell-nucleus measurements and a benign/malignant label.

Columns
sample_idnot null INTEGER
Row index within the dataset (0-based).
mean_radius DOUBLE
Feature: mean radius.
mean_texture DOUBLE
Feature: mean texture.
mean_perimeter DOUBLE
Feature: mean perimeter.
mean_area DOUBLE
Feature: mean area.
mean_smoothness DOUBLE
Feature: mean smoothness.
mean_compactness DOUBLE
Feature: mean compactness.
mean_concavity DOUBLE
Feature: mean concavity.
mean_concave_points DOUBLE
Feature: mean concave points.
mean_symmetry DOUBLE
Feature: mean symmetry.
mean_fractal_dimension DOUBLE
Feature: mean fractal dimension.
radius_error DOUBLE
Feature: radius error.
texture_error DOUBLE
Feature: texture error.
perimeter_error DOUBLE
Feature: perimeter error.
area_error DOUBLE
Feature: area error.
smoothness_error DOUBLE
Feature: smoothness error.
compactness_error DOUBLE
Feature: compactness error.
concavity_error DOUBLE
Feature: concavity error.
concave_points_error DOUBLE
Feature: concave points error.
symmetry_error DOUBLE
Feature: symmetry error.
fractal_dimension_error DOUBLE
Feature: fractal dimension error.
worst_radius DOUBLE
Feature: worst radius.
worst_texture DOUBLE
Feature: worst texture.
worst_perimeter DOUBLE
Feature: worst perimeter.
worst_area DOUBLE
Feature: worst area.
worst_smoothness DOUBLE
Feature: worst smoothness.
worst_compactness DOUBLE
Feature: worst compactness.
worst_concavity DOUBLE
Feature: worst concavity.
worst_concave_points DOUBLE
Feature: worst concave points.
worst_symmetry DOUBLE
Feature: worst symmetry.
worst_fractal_dimension DOUBLE
Feature: worst fractal dimension.
target INTEGER
Integer class label (0-based).
target_name VARCHAR
Human-readable class name (one of: malignant, benign).
ConstraintsPRIMARY KEY (sample_id)
Examples (2)

Class balance

SELECT target_name, count(*)
FROM xgboost.main.breast_cancer
GROUP BY target_name;
SELECT target_name, count(*) AS n,
  round(avg(mean_radius), 2) AS avg_mean_radius
FROM xgboost.main.breast_cancer()
GROUP BY target_name
ORDER BY target_name;
Link
california_housing 2 examples10 cols

20640 census block groups with 8 features and the median house value (regression).

Columns
sample_idnot null INTEGER
Row index within the dataset (0-based).
medinc DOUBLE
Feature: MedInc.
houseage DOUBLE
Feature: HouseAge.
averooms DOUBLE
Feature: AveRooms.
avebedrms DOUBLE
Feature: AveBedrms.
population DOUBLE
Feature: Population.
aveoccup DOUBLE
Feature: AveOccup.
latitude DOUBLE
Feature: Latitude.
longitude DOUBLE
Feature: Longitude.
target DOUBLE
Continuous regression target.
ConstraintsPRIMARY KEY (sample_id)
Examples (2)

Average value by latitude band

SELECT round(latitude) AS lat, round(avg(target), 2)
FROM xgboost.main.california_housing
GROUP BY lat
ORDER BY lat;
SELECT count(*) AS n_districts, round(avg(target), 3) AS mean_value_100k
FROM xgboost.main.california_housing();
Link
diabetes 2 examples12 cols

442 patients with 10 baseline measurements and a one-year disease-progression score.

Columns
sample_idnot null INTEGER
Row index within the dataset (0-based).
age DOUBLE
Feature: age.
sex DOUBLE
Feature: sex.
bmi DOUBLE
Feature: bmi.
bp DOUBLE
Feature: bp.
s1 DOUBLE
Feature: s1.
s2 DOUBLE
Feature: s2.
s3 DOUBLE
Feature: s3.
s4 DOUBLE
Feature: s4.
s5 DOUBLE
Feature: s5.
s6 DOUBLE
Feature: s6.
target DOUBLE
Continuous regression target.
ConstraintsPRIMARY KEY (sample_id)
Examples (2)

Target range

SELECT min(target), max(target), round(avg(target), 1)
FROM xgboost.main.diabetes;
SELECT count(*) AS n, round(avg(target), 1) AS mean_progression
FROM xgboost.main.diabetes();
Link
iris 3 examples7 cols

150 iris flowers with four sepal/petal measurements (cm) and their species.

Columns
sample_idnot null INTEGER
Row index within the dataset (0-based).
sepal_length_cm DOUBLE
Feature: sepal length (cm).
sepal_width_cm DOUBLE
Feature: sepal width (cm).
petal_length_cm DOUBLE
Feature: petal length (cm).
petal_width_cm DOUBLE
Feature: petal width (cm).
target INTEGER
Integer class label (0-based).
target_name VARCHAR
Human-readable class name (one of: setosa, versicolor, virginica).
ConstraintsPRIMARY KEY (sample_id)
Examples (3)

Row count per species

SELECT target_name, count(*) FROM xgboost.main.iris GROUP BY target_name;
SELECT target_name, count(*) AS n
FROM xgboost.main.iris()
GROUP BY ALL
ORDER BY target_name;
SELECT target_name, avg(petal_length_cm)
FROM xgboost.main.iris()
GROUP BY target_name;
Link
list_models 2 examples11 cols

One row per model persisted in the registry, with its estimator, task, shape, and score.

Columns
model_namenot null VARCHAR
Stored model name.
estimator VARCHAR
Estimator type.
task VARCHAR
classification or regression.
target VARCHAR
Target column the model was trained on.
n_features BIGINT
Number of features.
n_samples BIGINT
Number of training rows.
n_classes BIGINT
Number of classes (NULL for regression).
train_score DOUBLE
In-sample training score.
xgboost_version VARCHAR
xgboost version used to fit.
created_at VARCHAR
UTC timestamp the model was stored.
features VARCHAR[]
Ordered feature column names.
ConstraintsPRIMARY KEY (model_name)
Examples (2)

How many models are saved

SELECT count(*) AS model_count FROM xgboost.main.list_models;
SELECT model_name, estimator, train_score
FROM xgboost.main.list_models()
ORDER BY model_name;
Link
wine 2 examples16 cols

178 wines with 13 chemical measurements and their cultivar of origin.

Columns
sample_idnot null INTEGER
Row index within the dataset (0-based).
alcohol DOUBLE
Feature: alcohol.
malic_acid DOUBLE
Feature: malic_acid.
ash DOUBLE
Feature: ash.
alcalinity_of_ash DOUBLE
Feature: alcalinity_of_ash.
magnesium DOUBLE
Feature: magnesium.
total_phenols DOUBLE
Feature: total_phenols.
flavanoids DOUBLE
Feature: flavanoids.
nonflavanoid_phenols DOUBLE
Feature: nonflavanoid_phenols.
proanthocyanins DOUBLE
Feature: proanthocyanins.
color_intensity DOUBLE
Feature: color_intensity.
hue DOUBLE
Feature: hue.
od280_od315_of_diluted_wines DOUBLE
Feature: od280/od315_of_diluted_wines.
proline DOUBLE
Feature: proline.
target INTEGER
Integer class label (0-based).
target_name VARCHAR
Human-readable class name (one of: class_0, class_1, class_2).
ConstraintsPRIMARY KEY (sample_id)
Examples (2)

Average alcohol per cultivar

SELECT target_name, round(avg(alcohol), 2)
FROM xgboost.main.wine
GROUP BY target_name;
SELECT target_name, round(avg(alcohol), 2) AS mean_alcohol
FROM xgboost.main.wine()
GROUP BY target_name
ORDER BY target_name;
Link
Table functions
drop_model (model_name VARCHAR) 1 example

Delete a model from the registry

Arguments
model_name VARCHAR
Name of the model to delete.
Returns columns
model_name VARCHAR
Name of the model.
dropped BOOLEAN
True if a model was deleted, False if it did not exist.
Example

Delete a stored model and report whether it existed

SELECT model_name, dropped FROM xgboost.main.drop_model('iris_clf');
Link
feature_importance (model_name VARCHAR, importance_type := VARCHAR, model := BLOB) 1 example

Per-feature importance (weight/gain/cover) for a stored model, ranked

Positional arguments
model_name VARCHAR
Name of a stored model (pass '' to use model:= instead).
Named arguments
importance_type := VARCHAR
weight, gain, cover, total_gain, or total_cover. · default "gain"
model := BLOB
A fitted model (as returned by fit). Provide this OR model_name. · default "b''"
Returns columns
feature VARCHAR
Feature column name.
importance DOUBLE
Importance score for the chosen importance_type.
rank INTEGER
1-based rank by importance (1 = most important).
Example

Top three features by gain for a stored model

SELECT feature, importance, rank
FROM xgboost.main.feature_importance('iris_clf', importance_type => 'gain')
WHERE rank <= 3;
Link
make_classification (n_classes := BIGINT, n_features := BIGINT, n_informative := BIGINT, n_samples := BIGINT, random_state := BIGINT) 1 example

Generate a synthetic classification dataset

Named arguments
n_classes := BIGINT
Number of target classes. · default 2
n_features := BIGINT
Total number of features. · default 20
n_informative := BIGINT
Number of informative features. · default 2
n_samples := BIGINT
Number of samples to generate. · default 100
random_state := BIGINT
Random seed for reproducibility. · default 0
Returns columns
sample_id INTEGER
Row index within the generated sample (0-based).
feature_0 DOUBLE
Generated feature 0.
feature_1 DOUBLE
Generated feature 1.
feature_2 DOUBLE
Generated feature 2.
feature_3 DOUBLE
Generated feature 3.
feature_4 DOUBLE
Generated feature 4.
target INTEGER
Integer class label (0-based).
Returns columns · depends on the arguments
With n_features := 5 (one feature_<i> column per feature in general)
sample_id INTEGER
Row index within the generated sample (0-based).
feature_0 DOUBLE
Generated feature 0.
feature_1 DOUBLE
Generated feature 1.
feature_2 DOUBLE
Generated feature 2.
feature_3 DOUBLE
Generated feature 3.
feature_4 DOUBLE
Generated feature 4.
target INTEGER
Integer class label (0-based).
Example

Class balance of 500 generated rows with 5 features and 3 classes

SELECT target, count(*) AS n
FROM xgboost.main.make_classification(n_samples => 500, n_features => 5, n_classes => 3)
GROUP BY target
ORDER BY target;
Link
make_regression (n_features := BIGINT, n_informative := BIGINT, n_samples := BIGINT, noise := DOUBLE, random_state := BIGINT) 1 example

Generate a synthetic regression dataset

Named arguments
n_features := BIGINT
Total number of features. · default 20
n_informative := BIGINT
Number of informative features. · default 10
n_samples := BIGINT
Number of samples to generate. · default 100
noise := DOUBLE
Std-dev of gaussian noise on the output. · default 0.0
random_state := BIGINT
Random seed for reproducibility. · default 0
Returns columns
sample_id INTEGER
Row index within the generated sample (0-based).
feature_0 DOUBLE
Generated feature 0.
feature_1 DOUBLE
Generated feature 1.
feature_2 DOUBLE
Generated feature 2.
feature_3 DOUBLE
Generated feature 3.
target DOUBLE
Continuous regression target.
Returns columns · depends on the arguments
With n_features := 4 (one feature_<i> column per feature in general)
sample_id INTEGER
Row index within the generated sample (0-based).
feature_0 DOUBLE
Generated feature 0.
feature_1 DOUBLE
Generated feature 1.
feature_2 DOUBLE
Generated feature 2.
feature_3 DOUBLE
Generated feature 3.
target DOUBLE
Continuous regression target.
Example

Size and target spread of 500 generated rows with 4 features

SELECT count(*) AS n, round(stddev(target), 2) AS target_sd
FROM xgboost.main.make_regression(n_samples => 500, n_features => 4, noise => 5.0);
Link
model_info (model_name VARCHAR) 1 example

Describe a single stored model (one row, empty if absent)

Arguments
model_name VARCHAR
Name of a stored model.
Returns columns
model_name VARCHAR
Stored model name.
estimator VARCHAR
Estimator type.
task VARCHAR
classification or regression.
target VARCHAR
Target column the model was trained on.
n_features BIGINT
Number of features.
n_samples BIGINT
Number of training rows.
n_classes BIGINT
Number of classes (NULL for regression).
train_score DOUBLE
In-sample training score.
xgboost_version VARCHAR
xgboost version used to fit.
created_at VARCHAR
UTC timestamp the model was stored.
features VARCHAR[]
Ordered feature column names.
Example

Show one stored model's training metadata

SELECT estimator, task, target, n_features, train_score
FROM xgboost.main.model_info('iris_clf');
Link
Table in-out functions
cross_val_predict (data TABLE, cv := BIGINT, estimator := VARCHAR, id := VARCHAR, params := VARCHAR, target := VARCHAR) 3 examples

Out-of-fold cross-validated predictions (no model is stored)

Positional arguments
data TABLE
Training rows: features + target [+ id].
Named arguments
cv := BIGINT
Number of cross-validation folds. · default 5
estimator := VARCHAR
Estimator name. · default "xgb_classifier"
id := VARCHAR
Optional id column to carry through. · default ""
params := VARCHAR
JSON object of hyperparameters. · default ""
target := VARCHAR
Name of the target/label column (required). · default ""
Returns columns
sample_id BIGINT
Column named by `id :=` (here `sample_id`), carried through first as-is.
prediction BIGINT
Out-of-fold class label (`VARCHAR` for string labels).
sample_id BIGINT
Column named by `id :=` (here `sample_id`), carried through first as-is.
prediction DOUBLE
Out-of-fold predicted value.
Returns columns · depends on the arguments
Classifier
sample_id BIGINT
Column named by `id :=` (here `sample_id`), carried through first as-is.
prediction BIGINT
Out-of-fold class label (`VARCHAR` for string labels).
Regressor
sample_id BIGINT
Column named by `id :=` (here `sample_id`), carried through first as-is.
prediction DOUBLE
Out-of-fold predicted value.
Examples (3)

Out-of-fold confusion matrix for an XGBoost iris classifier: 5-fold cross_val_predict on the species name, joined back to the iris table by sample_id and counted per (actual, predicted) species pair. Only non-empty cells are returned; the off-diagonal rows are the held-out misclassifications, almost all of them versicolor/virginica mix-ups.

SELECT i.target_name AS actual_species, cv.prediction AS predicted_species,
  count(*) AS n_flowers
FROM xgboost.main.cross_val_predict((SELECT sample_id, sepal_length_cm, sepal_width_cm, petal_length_cm, petal_width_cm, target_name FROM xgboost.main.iris), estimator := 'xgb_classifier', target := 'target_name', id := 'sample_id', cv := 5) AS cv
JOIN xgboost.main.iris AS i USING (sample_id)
GROUP BY ALL
ORDER BY actual_species, predicted_species;

Where does an XGBoost regressor miss? 5-fold out-of-fold predictions on diabetes joined back to the patients, with the held-out mean absolute error and mean progression score per BMI quartile (1 = lowest BMI).

SELECT d.bmi_quartile, count(*) AS patients,
  round(avg(abs(cv.prediction - d.target)), 1) AS oof_mae,
  round(avg(d.target), 1) AS mean_progression
FROM xgboost.main.cross_val_predict((SELECT * FROM xgboost.main.diabetes), estimator := 'xgb_regressor', target := 'target', id := 'sample_id', cv := 5) AS cv
JOIN (SELECT sample_id, target, ntile(4) OVER (ORDER BY bmi, sample_id) AS bmi_quartile FROM xgboost.main.diabetes) AS d USING (sample_id)
GROUP BY d.bmi_quartile
ORDER BY d.bmi_quartile;

5-fold out-of-fold predictions on iris

SELECT sample_id, prediction
FROM xgboost.main.cross_val_predict((SELECT sample_id, sepal_length_cm, sepal_width_cm, petal_length_cm, petal_width_cm, target FROM xgboost.main.iris()), estimator => 'xgb_classifier', target => 'target', id => 'sample_id');
Link
cross_val_score (data TABLE, cv := BIGINT, estimator := VARCHAR, id := VARCHAR, params := VARCHAR, scoring := VARCHAR, target := VARCHAR) 1 example

Cross-validated held-out scores, one row per fold (no model is stored)

Positional arguments
data TABLE
Training rows: features + target [+ id].
Named arguments
cv := BIGINT
Number of cross-validation folds. · default 5
estimator := VARCHAR
Estimator name. · default "xgb_classifier"
id := VARCHAR
Optional id column to exclude from features. · default ""
params := VARCHAR
JSON object of hyperparameters. · default ""
scoring := VARCHAR
Scorer name (default: the estimator's own scorer). · default ""
target := VARCHAR
Name of the target/label column (required). · default ""
Returns columns
fold BIGINT
Cross-validation fold index (0-based).
score DOUBLE
Held-out score for this fold.
Example

5-fold accuracy of an XGBoost classifier on iris

SELECT fold, score
FROM xgboost.main.cross_val_score((SELECT sepal_length_cm, sepal_width_cm, petal_length_cm, petal_width_cm, target FROM xgboost.main.iris()), estimator => 'xgb_classifier', target => 'target');
Link
explain (data TABLE, id := VARCHAR, model := BLOB, model_name := VARCHAR) 1 example

Per-row SHAP feature contributions, long format (row, [class], feature, shap_value, base_value)

Positional arguments
data TABLE
Rows to explain (must contain the model's feature columns).
Named arguments
id := VARCHAR
Optional id column to carry through onto every emitted row. · default ""
model := BLOB
A fitted model (as returned by fit). Provide this OR model_name. · default "b''"
model_name := VARCHAR
Name of a model in the registry. Provide this OR model. · default ""
Returns columns
sample_id BIGINT
Column named by `id :=` (here `sample_id`), carried through first as-is.
feature VARCHAR
Feature column name.
shap_value DOUBLE
Contribution of the feature to the raw margin.
base_value DOUBLE
Model base (expected) raw-margin value.
sample_id BIGINT
Column named by `id :=` (here `sample_id`), carried through first as-is.
class BIGINT
Class index the contribution is for.
feature VARCHAR
Feature column name.
shap_value DOUBLE
Contribution of the feature to the raw margin for this class.
base_value DOUBLE
Model base (expected) raw-margin value for this class.
Returns columns · depends on the arguments
Binary classification or regression
sample_id BIGINT
Column named by `id :=` (here `sample_id`), carried through first as-is.
feature VARCHAR
Feature column name.
shap_value DOUBLE
Contribution of the feature to the raw margin.
base_value DOUBLE
Model base (expected) raw-margin value.
Multiclass classification
sample_id BIGINT
Column named by `id :=` (here `sample_id`), carried through first as-is.
class BIGINT
Class index the contribution is for.
feature VARCHAR
Feature column name.
shap_value DOUBLE
Contribution of the feature to the raw margin for this class.
base_value DOUBLE
Model base (expected) raw-margin value for this class.
Example

Explain each row's prediction with per-feature contributions

SELECT feature, round(avg(abs(shap_value)), 3) AS mean_abs_shap
FROM xgboost.main.explain((SELECT * FROM xgboost.main.diabetes()), model_name => 'diab_reg', id => 'sample_id')
GROUP BY feature
ORDER BY mean_abs_shap DESC;
Link
fit (data TABLE, estimator := VARCHAR, id := VARCHAR, model_name := VARCHAR, params := VARCHAR, target := VARCHAR) 1 example

Fit an XGBoost estimator and store it in the model registry

Positional arguments
data TABLE
Training rows: features + target [+ id].
Named arguments
estimator := VARCHAR
Estimator name. · default "xgb_classifier"
id := VARCHAR
Optional id column to exclude from features. · default ""
model_name := VARCHAR
Optional registry name; the model is always returned as a BLOB. · default ""
params := VARCHAR
JSON object of hyperparameters. · default ""
target := VARCHAR
Name of the target/label column (required). · default ""
Returns columns
model_name VARCHAR
Name the model was stored under ('' if not persisted).
estimator VARCHAR
Estimator type used.
task VARCHAR
classification or regression.
n_samples BIGINT
Number of training rows.
n_features BIGINT
Number of features.
n_classes BIGINT
Number of classes (NULL for regression).
train_score DOUBLE
In-sample score (accuracy or R^2).
features VARCHAR[]
Ordered feature column names.
model BLOB
The fitted model as a self-contained `BLOB` (estimator + metadata).
Example

Train an XGBoost classifier on iris and store it as 'iris_clf'

SELECT model_name, task, n_samples, n_features, train_score
FROM xgboost.main.fit((SELECT sample_id, sepal_length_cm, sepal_width_cm, petal_length_cm, petal_width_cm, target FROM xgboost.main.iris()), model_name => 'iris_clf', estimator => 'xgb_classifier', target => 'target', id => 'sample_id');
Link
fit_xgb_classifier (data TABLE, booster := VARCHAR, colsample_bytree := DOUBLE, gamma := DOUBLE, id := VARCHAR, learning_rate := DOUBLE, max_depth := BIGINT, min_child_weight := DOUBLE, model_name := VARCHAR, n_estimators := BIGINT, objective := VARCHAR, random_state := BIGINT, reg_alpha := DOUBLE, reg_lambda := DOUBLE, subsample := DOUBLE, target := VARCHAR, tree_method := VARCHAR) 1 example

Fit a xgb_classifier with typed hyperparameters; returns/stores the model

Positional arguments
data TABLE
Training rows: features + target [+ id].
Named arguments
booster := VARCHAR
Booster: 'gbtree', 'gblinear', or 'dart' ('' = default). · default ""
colsample_bytree := DOUBLE
Column subsample ratio per tree. · default 1.0
gamma := DOUBLE
Min loss reduction to split. · default 0.0
id := VARCHAR
Optional id passthrough column. · default ""
learning_rate := DOUBLE
Boosting learning rate / eta. · default 0.3
max_depth := BIGINT
Max tree depth. · default 6
min_child_weight := DOUBLE
Min sum of instance weight in a child. · default 1.0
model_name := VARCHAR
Optional registry name; the model is always returned as a BLOB. · default ""
n_estimators := BIGINT
Number of boosting rounds. · default 100
objective := VARCHAR
Learning objective (e.g. 'binary:logistic'); '' = task default. · default ""
random_state := BIGINT
Random seed. · default 0
reg_alpha := DOUBLE
L1 regularization on weights. · default 0.0
reg_lambda := DOUBLE
L2 regularization on weights. · default 1.0
subsample := DOUBLE
Row subsample ratio per tree. · default 1.0
target := VARCHAR
Label column name (required). · default ""
tree_method := VARCHAR
Tree construction algorithm ('hist', 'approx', 'exact'). · default "hist"
Returns columns
model_name VARCHAR
Name the model was stored under ('' if not persisted).
estimator VARCHAR
Estimator type used.
task VARCHAR
classification or regression.
n_samples BIGINT
Number of training rows.
n_features BIGINT
Number of features.
n_classes BIGINT
Number of classes (NULL for regression).
train_score DOUBLE
In-sample score (accuracy or R^2).
features VARCHAR[]
Ordered feature column names.
model BLOB
The fitted model as a self-contained `BLOB` (estimator + metadata).
Example

Train a xgb_classifier with named hyperparameters

SELECT n_samples, n_features, train_score
FROM xgboost.main.fit_xgb_classifier((SELECT * FROM xgboost.main.iris()), target := 'target', id := 'sample_id', n_estimators := 200, max_depth := 6);
Link
fit_xgb_regressor (data TABLE, booster := VARCHAR, colsample_bytree := DOUBLE, gamma := DOUBLE, id := VARCHAR, learning_rate := DOUBLE, max_depth := BIGINT, min_child_weight := DOUBLE, model_name := VARCHAR, n_estimators := BIGINT, objective := VARCHAR, random_state := BIGINT, reg_alpha := DOUBLE, reg_lambda := DOUBLE, subsample := DOUBLE, target := VARCHAR, tree_method := VARCHAR) 1 example

Fit a xgb_regressor with typed hyperparameters; returns/stores the model

Positional arguments
data TABLE
Training rows: features + target [+ id].
Named arguments
booster := VARCHAR
Booster: 'gbtree', 'gblinear', or 'dart' ('' = default). · default ""
colsample_bytree := DOUBLE
Column subsample ratio per tree. · default 1.0
gamma := DOUBLE
Min loss reduction to split. · default 0.0
id := VARCHAR
Optional id passthrough column. · default ""
learning_rate := DOUBLE
Boosting learning rate / eta. · default 0.3
max_depth := BIGINT
Max tree depth. · default 6
min_child_weight := DOUBLE
Min sum of instance weight in a child. · default 1.0
model_name := VARCHAR
Optional registry name; the model is always returned as a BLOB. · default ""
n_estimators := BIGINT
Number of boosting rounds. · default 100
objective := VARCHAR
Learning objective (e.g. 'binary:logistic'); '' = task default. · default ""
random_state := BIGINT
Random seed. · default 0
reg_alpha := DOUBLE
L1 regularization on weights. · default 0.0
reg_lambda := DOUBLE
L2 regularization on weights. · default 1.0
subsample := DOUBLE
Row subsample ratio per tree. · default 1.0
target := VARCHAR
Label column name (required). · default ""
tree_method := VARCHAR
Tree construction algorithm ('hist', 'approx', 'exact'). · default "hist"
Returns columns
model_name VARCHAR
Name the model was stored under ('' if not persisted).
estimator VARCHAR
Estimator type used.
task VARCHAR
classification or regression.
n_samples BIGINT
Number of training rows.
n_features BIGINT
Number of features.
n_classes BIGINT
Number of classes (NULL for regression).
train_score DOUBLE
In-sample score (accuracy or R^2).
features VARCHAR[]
Ordered feature column names.
model BLOB
The fitted model as a self-contained `BLOB` (estimator + metadata).
Example

Train a xgb_regressor with named hyperparameters

SELECT n_samples, n_features, train_score
FROM xgboost.main.fit_xgb_regressor((SELECT * FROM xgboost.main.iris()), target := 'target', id := 'sample_id', n_estimators := 200, max_depth := 6);
Link
fit_xgb_rf_classifier (data TABLE, booster := VARCHAR, colsample_bytree := DOUBLE, gamma := DOUBLE, id := VARCHAR, learning_rate := DOUBLE, max_depth := BIGINT, min_child_weight := DOUBLE, model_name := VARCHAR, n_estimators := BIGINT, objective := VARCHAR, random_state := BIGINT, reg_alpha := DOUBLE, reg_lambda := DOUBLE, subsample := DOUBLE, target := VARCHAR, tree_method := VARCHAR) 1 example

Fit a xgb_rf_classifier with typed hyperparameters; returns/stores the model

Positional arguments
data TABLE
Training rows: features + target [+ id].
Named arguments
booster := VARCHAR
Booster: 'gbtree', 'gblinear', or 'dart' ('' = default). · default ""
colsample_bytree := DOUBLE
Column subsample ratio per tree. · default 1.0
gamma := DOUBLE
Min loss reduction to split. · default 0.0
id := VARCHAR
Optional id passthrough column. · default ""
learning_rate := DOUBLE
Boosting learning rate / eta. · default 0.3
max_depth := BIGINT
Max tree depth. · default 6
min_child_weight := DOUBLE
Min sum of instance weight in a child. · default 1.0
model_name := VARCHAR
Optional registry name; the model is always returned as a BLOB. · default ""
n_estimators := BIGINT
Number of boosting rounds. · default 100
objective := VARCHAR
Learning objective (e.g. 'binary:logistic'); '' = task default. · default ""
random_state := BIGINT
Random seed. · default 0
reg_alpha := DOUBLE
L1 regularization on weights. · default 0.0
reg_lambda := DOUBLE
L2 regularization on weights. · default 1.0
subsample := DOUBLE
Row subsample ratio per tree. · default 1.0
target := VARCHAR
Label column name (required). · default ""
tree_method := VARCHAR
Tree construction algorithm ('hist', 'approx', 'exact'). · default "hist"
Returns columns
model_name VARCHAR
Name the model was stored under ('' if not persisted).
estimator VARCHAR
Estimator type used.
task VARCHAR
classification or regression.
n_samples BIGINT
Number of training rows.
n_features BIGINT
Number of features.
n_classes BIGINT
Number of classes (NULL for regression).
train_score DOUBLE
In-sample score (accuracy or R^2).
features VARCHAR[]
Ordered feature column names.
model BLOB
The fitted model as a self-contained `BLOB` (estimator + metadata).
Example

Train a xgb_rf_classifier with named hyperparameters

SELECT n_samples, n_features, train_score
FROM xgboost.main.fit_xgb_rf_classifier((SELECT * FROM xgboost.main.iris()), target := 'target', id := 'sample_id', n_estimators := 200, max_depth := 6);
Link
fit_xgb_rf_regressor (data TABLE, booster := VARCHAR, colsample_bytree := DOUBLE, gamma := DOUBLE, id := VARCHAR, learning_rate := DOUBLE, max_depth := BIGINT, min_child_weight := DOUBLE, model_name := VARCHAR, n_estimators := BIGINT, objective := VARCHAR, random_state := BIGINT, reg_alpha := DOUBLE, reg_lambda := DOUBLE, subsample := DOUBLE, target := VARCHAR, tree_method := VARCHAR) 1 example

Fit a xgb_rf_regressor with typed hyperparameters; returns/stores the model

Positional arguments
data TABLE
Training rows: features + target [+ id].
Named arguments
booster := VARCHAR
Booster: 'gbtree', 'gblinear', or 'dart' ('' = default). · default ""
colsample_bytree := DOUBLE
Column subsample ratio per tree. · default 1.0
gamma := DOUBLE
Min loss reduction to split. · default 0.0
id := VARCHAR
Optional id passthrough column. · default ""
learning_rate := DOUBLE
Boosting learning rate / eta. · default 0.3
max_depth := BIGINT
Max tree depth. · default 6
min_child_weight := DOUBLE
Min sum of instance weight in a child. · default 1.0
model_name := VARCHAR
Optional registry name; the model is always returned as a BLOB. · default ""
n_estimators := BIGINT
Number of boosting rounds. · default 100
objective := VARCHAR
Learning objective (e.g. 'binary:logistic'); '' = task default. · default ""
random_state := BIGINT
Random seed. · default 0
reg_alpha := DOUBLE
L1 regularization on weights. · default 0.0
reg_lambda := DOUBLE
L2 regularization on weights. · default 1.0
subsample := DOUBLE
Row subsample ratio per tree. · default 1.0
target := VARCHAR
Label column name (required). · default ""
tree_method := VARCHAR
Tree construction algorithm ('hist', 'approx', 'exact'). · default "hist"
Returns columns
model_name VARCHAR
Name the model was stored under ('' if not persisted).
estimator VARCHAR
Estimator type used.
task VARCHAR
classification or regression.
n_samples BIGINT
Number of training rows.
n_features BIGINT
Number of features.
n_classes BIGINT
Number of classes (NULL for regression).
train_score DOUBLE
In-sample score (accuracy or R^2).
features VARCHAR[]
Ordered feature column names.
model BLOB
The fitted model as a self-contained `BLOB` (estimator + metadata).
Example

Train a xgb_rf_regressor with named hyperparameters

SELECT n_samples, n_features, train_score
FROM xgboost.main.fit_xgb_rf_regressor((SELECT * FROM xgboost.main.iris()), target := 'target', id := 'sample_id', n_estimators := 200, max_depth := 6);
Link
partial_dependence (data TABLE, feature := VARCHAR, grid_resolution := BIGINT, model := BLOB, model_name := VARCHAR) 1 example

How a stored model's average prediction changes as one feature varies over a grid

Positional arguments
data TABLE
Background rows over the model's feature columns.
Named arguments
feature := VARCHAR
Feature column to vary (required). · default ""
grid_resolution := BIGINT
Number of grid points along the feature. · default 100
model := BLOB
A fitted model. Provide this OR model_name. · default "b''"
model_name := VARCHAR
Name of a model in the registry. Provide this OR model. · default ""
Returns columns
feature_value DOUBLE
Value the feature was set to.
class BIGINT
Class index (NULL for regression / the single binary curve).
partial_dependence DOUBLE
Average model output at this feature value.
Example

Partial dependence of 'iris_clf' on petal length

SELECT class, feature_value, partial_dependence
FROM xgboost.main.partial_dependence((SELECT * FROM xgboost.main.iris()), model_name := 'iris_clf', feature := 'petal_length_cm')
ORDER BY feature_value;
Link
permutation_importance (data TABLE, model := BLOB, model_name := VARCHAR, n_repeats := BIGINT, random_state := BIGINT, scoring := VARCHAR, target := VARCHAR) 1 example

Model-agnostic feature importance: the drop in score when each feature is shuffled

Positional arguments
data TABLE
Evaluation rows: the model's features + the target column.
Named arguments
model := BLOB
A fitted model. Provide this OR model_name. · default "b''"
model_name := VARCHAR
Name of a model in the registry. Provide this OR model. · default ""
n_repeats := BIGINT
Number of times each feature is shuffled. · default 5
random_state := BIGINT
Random seed. · default 0
scoring := VARCHAR
Scorer name (default: the estimator's own scorer). · default ""
target := VARCHAR
Name of the target/label column (required). · default ""
Returns columns
feature VARCHAR
Feature column name.
importance_mean DOUBLE
Mean drop in score when the feature is shuffled.
importance_std DOUBLE
Std-dev of the importance across repeats.
rank INTEGER
1-based rank by importance_mean (1 = most important).
Example

Rank iris features by permutation importance for a stored model

SELECT feature, importance_mean, rank
FROM xgboost.main.permutation_importance((SELECT * EXCLUDE (target_name) FROM xgboost.main.iris()), model_name := 'iris_clf', target := 'target')
ORDER BY importance_mean DESC;
Link
predict (data TABLE, id := VARCHAR, model := BLOB, model_name := VARCHAR, output_margin := BOOLEAN, pred_leaf := BOOLEAN, with_proba := BOOLEAN) 1 example

Score a table through a stored model, emitting predictions

Positional arguments
data TABLE
Rows to score (must contain the model's feature columns).
Named arguments
id := VARCHAR
Optional id column to carry through. · default ""
model := BLOB
A fitted model (as returned by fit). Provide this OR model_name. · default "b''"
model_name := VARCHAR
Name of a model in the registry. Provide this OR model. · default ""
output_margin := BOOLEAN
Emit the raw (untransformed) margin score instead of the label. · default false
pred_leaf := BOOLEAN
Emit the leaf index each tree assigns the row (a list per row). · default false
with_proba := BOOLEAN
Also emit per-class probabilities (classifiers). · default false
Returns columns
sample_id BIGINT
Column named by `id :=` (here `sample_id`), carried through first as-is.
prediction BIGINT
Predicted class label (`VARCHAR` for string labels).
sample_id BIGINT
Column named by `id :=` (here `sample_id`), carried through first as-is.
prediction DOUBLE
Predicted value.
sample_id BIGINT
Column named by `id :=` (here `sample_id`), carried through first as-is.
margin DOUBLE
Raw (untransformed) margin score.
sample_id BIGINT
Column named by `id :=` (here `sample_id`), carried through first as-is.
leaf INTEGER[]
Leaf index reached in each tree, one element per tree.
Returns columns · depends on the arguments
Classifier (default)
sample_id BIGINT
Column named by `id :=` (here `sample_id`), carried through first as-is.
prediction BIGINT
Predicted class label (`VARCHAR` for string labels).
Regressor (default)
sample_id BIGINT
Column named by `id :=` (here `sample_id`), carried through first as-is.
prediction DOUBLE
Predicted value.
output_margin := true
sample_id BIGINT
Column named by `id :=` (here `sample_id`), carried through first as-is.
margin DOUBLE
Raw (untransformed) margin score.
pred_leaf := true
sample_id BIGINT
Column named by `id :=` (here `sample_id`), carried through first as-is.
leaf INTEGER[]
Leaf index reached in each tree, one element per tree.
Example

Predict with the stored 'iris_clf' model

SELECT sample_id, prediction
FROM xgboost.main.predict((SELECT * FROM xgboost.main.iris()), model_name => 'iris_clf', id => 'sample_id');
Link

Try these queries

Load the built-in iris dataset.

SELECT * FROM xgboost.main.iris LIMIT 5;

Uses iris

Three-fold cross-validated accuracy of an XGBoost classifier on iris.

SELECT fold, score
FROM xgboost.main.cross_val_score((SELECT * EXCLUDE (target_name) FROM xgboost.main.iris), estimator := 'xgb_classifier', target := 'target', cv := 3);

Uses cross_val_scoreiris

Grid-search an XGBoost classifier on iris over a tiny grid (3-fold).

SELECT params, mean_test_score, rank
FROM xgboost.main.grid_search((SELECT * EXCLUDE (target_name) FROM xgboost.main.iris), target := 'target', cv := 3, estimator := union_value(xgb_classifier := {'n_estimators': [25, 50], 'max_depth': [3]}))
ORDER BY rank;

Uses grid_searchiris

Out-of-fold confusion matrix for an XGBoost iris classifier: 5-fold cross_val_predict on the species name, joined back to the iris table by sample_id and counted per (actual, predicted) species pair. Only non-empty cells are returned; the off-diagonal rows are the held-out misclassifications, almost all of them versicolor/virginica mix-ups.

SELECT i.target_name AS actual_species, cv.prediction AS predicted_species,
  count(*) AS n_flowers
FROM xgboost.main.cross_val_predict((SELECT sample_id, sepal_length_cm, sepal_width_cm, petal_length_cm, petal_width_cm, target_name FROM xgboost.main.iris), estimator := 'xgb_classifier', target := 'target_name', id := 'sample_id', cv := 5) AS cv
JOIN xgboost.main.iris AS i USING (sample_id)
GROUP BY ALL
ORDER BY actual_species, predicted_species;

Uses cross_val_predictiris

Fit an XGBoost classifier on iris and return the training summary

SELECT estimator, task, n_samples, n_features, train_score
FROM xgboost.main.fit((SELECT * FROM xgboost.main.iris), estimator := 'xgb_classifier', target := 'target', id := 'sample_id')

Uses fitiris

How many models are saved

SELECT count(*) AS model_count FROM xgboost.main.list_models

Uses list_models

31 more examples in the Catalog, each listed under the table or function it uses.

XGBoost is an independent open-source connector from Query.Farm. It is not affiliated with, endorsed by or sponsored by the services, projects or organisations it works with. Product names, logos and trademarks belong to their respective owners.