Skip to content

LightGBM

Train, tune, evaluate, and explain gradient-boosted classifiers and regressors, with a saved-model registry

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/lightgbm/index.md to help me query LightGBM 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.

See where a classifier gets its predictions right

Example output · captured
Connector release
v0.2.0
Engine
2.0.1
VGI protocol
3.4.0
SELECT a.target_name AS actual, l.target_name AS predicted, count(*) AS n
FROM lightgbm.main.cross_val_predict((SELECT * EXCLUDE (target_name) FROM lightgbm.main.iris()), estimator := 'lgbm_classifier', target := 'target', id := 'sample_id', cv := 5) p
JOIN lightgbm.main.iris() a USING (sample_id)
JOIN (SELECT DISTINCT target, target_name FROM lightgbm.main.iris()) l ON l.target = p.prediction
GROUP BY actual, predicted
ORDER BY actual, predicted;
Result
actual predicted n
setosa setosa 50
versicolor versicolor 46
versicolor virginica 4
virginica versicolor 6
virginica virginica 44

Quick start

Choose where to run LightGBM, 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 'lightgbm' AS lightgbm (
  TYPE vgi,
  LOCATION 'uv run --with git+https://github.com/Query-farm/[email protected] https://raw.githubusercontent.com/Query-farm/vgi-lightgbm/v0.2.0/lightgbm_worker.py'
);

3. Run a query

query.sql
SELECT a.target_name AS actual, l.target_name AS predicted, count(*) AS n
FROM lightgbm.main.cross_val_predict((SELECT * EXCLUDE (target_name) FROM lightgbm.main.iris()), estimator := 'lgbm_classifier', target := 'target', id := 'sample_id', cv := 5) p
JOIN lightgbm.main.iris() a USING (sample_id)
JOIN (SELECT DISTINCT target, target_name FROM lightgbm.main.iris()) l ON l.target = p.prediction
GROUP BY actual, predicted
ORDER BY actual, predicted;
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 'lightgbm' AS lightgbm (
  TYPE vgi,
  LOCATION 'uv run --with git+https://github.com/Query-farm/[email protected] https://raw.githubusercontent.com/Query-farm/vgi-lightgbm/v0.2.0/lightgbm_worker.py'
);

Overview

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

Catalog

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

lightgbm 1 schema
main 6 tables · 16 functions

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

Schema examples (4)
Examples (4)

Fit a LightGBM classifier on iris and return the training summary

SELECT estimator, task, n_samples, n_features, train_score
FROM lightgbm.main.fit((SELECT * EXCLUDE (target_name) FROM lightgbm.main.iris), estimator := 'lgbm_classifier', target := 'target', id := 'sample_id');

Out-of-fold confusion matrix on iris with species names: 5-fold cross_val_predict joined back to iris for the true and the predicted species (setosa is never confused; versicolor and virginica are mixed up a handful of times)

SELECT a.target_name AS actual, l.target_name AS predicted, count(*) AS n
FROM lightgbm.main.cross_val_predict((SELECT * EXCLUDE (target_name) FROM lightgbm.main.iris()), estimator := 'lgbm_classifier', target := 'target', id := 'sample_id', cv := 5) p
JOIN lightgbm.main.iris() a USING (sample_id)
JOIN (SELECT DISTINCT target, target_name FROM lightgbm.main.iris()) l ON l.target = p.prediction
GROUP BY actual, predicted
ORDER BY actual, predicted;
Result
actual predicted n
setosa setosa 50
versicolor versicolor 46
versicolor virginica 4
virginica versicolor 6
virginica virginica 44

Do split-gain and permutation importance agree? Join the stored 'iris_clf' model's gain ranking to its permutation (accuracy-drop) ranking per feature; both put the two petal measurements first

SELECT f.feature, f.rank AS gain_rank, p.rank AS permutation_rank,
  round(f.importance, 1) AS gain,
  round(p.importance_mean, 4) AS accuracy_drop
FROM lightgbm.main.feature_importance('iris_clf', importance_type := 'gain') f
JOIN lightgbm.main.permutation_importance((SELECT * EXCLUDE (target_name) FROM lightgbm.main.iris()), model_name := 'iris_clf', target := 'target', random_state := 42) p USING (feature)
ORDER BY f.rank;

Which features push each flower toward its own species? Join SHAP contributions from the stored 'iris_clf' to iris on sample and true class, then average |SHAP| per species and feature (petal length leads for all three species)

SELECT i.target_name, e.feature,
  round(avg(abs(e.shap_value)), 3) AS mean_abs_shap
FROM lightgbm.main.explain((SELECT * EXCLUDE (target_name) FROM lightgbm.main.iris()), model_name := 'iris_clf', id := 'sample_id') e
JOIN lightgbm.main.iris() i ON i.sample_id = e.sample_id AND i.target = e.class
GROUP BY i.target_name, e.feature
ORDER BY i.target_name, mean_abs_shap DESC;
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
Mean over the image's nuclei of the nucleus radius (mean distance from the centre to the perimeter), in image pixels.
mean_texture DOUBLE
Mean over the image's nuclei of the nucleus texture, the standard deviation of the grey-scale pixel values.
mean_perimeter DOUBLE
Mean over the image's nuclei of the nucleus perimeter length, in image pixels.
mean_area DOUBLE
Mean over the image's nuclei of the nucleus area, in square image pixels.
mean_smoothness DOUBLE
Mean over the image's nuclei of the nucleus smoothness, the local variation in radius lengths (a ratio).
mean_compactness DOUBLE
Mean over the image's nuclei of the nucleus compactness, perimeter squared over area minus one (a ratio).
mean_concavity DOUBLE
Mean over the image's nuclei of the severity of the concave portions of the nucleus contour (a ratio).
mean_concave_points DOUBLE
Mean over the image's nuclei of the count of concave portions of the nucleus contour.
mean_symmetry DOUBLE
Mean over the image's nuclei of the nucleus symmetry, as a ratio.
mean_fractal_dimension DOUBLE
Mean over the image's nuclei of the nucleus fractal dimension ('coastline approximation' minus one, a ratio).
radius_error DOUBLE
Standard error over the image's nuclei of the nucleus radius (mean distance from the centre to the perimeter), in image pixels.
texture_error DOUBLE
Standard error over the image's nuclei of the nucleus texture, the standard deviation of the grey-scale pixel values.
perimeter_error DOUBLE
Standard error over the image's nuclei of the nucleus perimeter length, in image pixels.
area_error DOUBLE
Standard error over the image's nuclei of the nucleus area, in square image pixels.
smoothness_error DOUBLE
Standard error over the image's nuclei of the nucleus smoothness, the local variation in radius lengths (a ratio).
compactness_error DOUBLE
Standard error over the image's nuclei of the nucleus compactness, perimeter squared over area minus one (a ratio).
concavity_error DOUBLE
Standard error over the image's nuclei of the severity of the concave portions of the nucleus contour (a ratio).
concave_points_error DOUBLE
Standard error over the image's nuclei of the count of concave portions of the nucleus contour.
symmetry_error DOUBLE
Standard error over the image's nuclei of the nucleus symmetry, as a ratio.
fractal_dimension_error DOUBLE
Standard error over the image's nuclei of the nucleus fractal dimension ('coastline approximation' minus one, a ratio).
worst_radius DOUBLE
Largest ('worst') value over the image's nuclei of the nucleus radius (mean distance from the centre to the perimeter), in image pixels.
worst_texture DOUBLE
Largest ('worst') value over the image's nuclei of the nucleus texture, the standard deviation of the grey-scale pixel values.
worst_perimeter DOUBLE
Largest ('worst') value over the image's nuclei of the nucleus perimeter length, in image pixels.
worst_area DOUBLE
Largest ('worst') value over the image's nuclei of the nucleus area, in square image pixels.
worst_smoothness DOUBLE
Largest ('worst') value over the image's nuclei of the nucleus smoothness, the local variation in radius lengths (a ratio).
worst_compactness DOUBLE
Largest ('worst') value over the image's nuclei of the nucleus compactness, perimeter squared over area minus one (a ratio).
worst_concavity DOUBLE
Largest ('worst') value over the image's nuclei of the severity of the concave portions of the nucleus contour (a ratio).
worst_concave_points DOUBLE
Largest ('worst') value over the image's nuclei of the count of concave portions of the nucleus contour.
worst_symmetry DOUBLE
Largest ('worst') value over the image's nuclei of the nucleus symmetry, as a ratio.
worst_fractal_dimension DOUBLE
Largest ('worst') value over the image's nuclei of the nucleus fractal dimension ('coastline approximation' minus one, a ratio).
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 lightgbm.main.breast_cancer
GROUP BY target_name;
SELECT target_name, count(*) AS n,
  round(avg(mean_radius), 2) AS avg_mean_radius
FROM lightgbm.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
Median income of the block group's households, in tens of thousands of US dollars.
houseage DOUBLE
Median age of the houses in the block group, in years.
averooms DOUBLE
Average number of rooms per household in the block group (a count per household).
avebedrms DOUBLE
Average number of bedrooms per household in the block group (a count per household).
population DOUBLE
Total count of people resident in the block group.
aveoccup DOUBLE
Average household size, in people per household.
latitude DOUBLE
Latitude of the block group's centroid, in decimal degrees north.
longitude DOUBLE
Longitude of the block group's centroid, in decimal degrees east (negative west).
median_house_value DOUBLE
Median house value for the block group, in units of $100,000.
ConstraintsPRIMARY KEY (sample_id)
Examples (2)

Average median house value by latitude band

SELECT round(latitude) AS lat,
  round(avg(median_house_value), 2) AS avg_value
FROM lightgbm.main.california_housing
GROUP BY lat
ORDER BY lat;
SELECT round(latitude) AS lat, count(*) AS block_groups,
  round(avg(median_house_value), 3) AS avg_value
FROM lightgbm.main.california_housing()
GROUP BY lat
ORDER BY lat;
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
Patient age at baseline, mean-centred and scaled to unit L2 norm across the 442 patients (dimensionless).
sex DOUBLE
Patient sex, encoded numerically, mean-centred and scaled to unit L2 norm across the 442 patients (dimensionless).
bmi DOUBLE
Body mass index at baseline, mean-centred and scaled to unit L2 norm across the 442 patients (dimensionless).
bp DOUBLE
Average blood pressure at baseline, mean-centred and scaled to unit L2 norm across the 442 patients (dimensionless).
s1 DOUBLE
Serum measurement 1: total serum cholesterol (tc), mean-centred and scaled to unit L2 norm across the 442 patients (dimensionless).
s2 DOUBLE
Serum measurement 2: low-density lipoproteins (ldl), mean-centred and scaled to unit L2 norm across the 442 patients (dimensionless).
s3 DOUBLE
Serum measurement 3: high-density lipoproteins (hdl), mean-centred and scaled to unit L2 norm across the 442 patients (dimensionless).
s4 DOUBLE
Serum measurement 4: total cholesterol over HDL (tch), mean-centred and scaled to unit L2 norm across the 442 patients (dimensionless).
s5 DOUBLE
Serum measurement 5: log of serum triglycerides (ltg), mean-centred and scaled to unit L2 norm across the 442 patients (dimensionless).
s6 DOUBLE
Serum measurement 6: blood sugar level (glu), mean-centred and scaled to unit L2 norm across the 442 patients (dimensionless).
progression DOUBLE
Quantitative measure of disease progression one year after baseline (unitless index, ~25-346).
ConstraintsPRIMARY KEY (sample_id)
Examples (2)

Range and mean of the one-year progression score

SELECT min(progression) AS lo, max(progression) AS hi,
  round(avg(progression), 1) AS mean
FROM lightgbm.main.diabetes;
SELECT round(min(progression), 1) AS lo, round(max(progression), 1) AS hi,
  round(avg(progression), 1) AS mean
FROM lightgbm.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 lightgbm.main.iris GROUP BY target_name;
SELECT target_name, count(*) AS n,
  round(avg(petal_length_cm), 2) AS avg_petal_length_cm
FROM lightgbm.main.iris()
GROUP BY target_name
ORDER BY target_name;
SELECT target_name, avg(petal_length_cm)
FROM lightgbm.main.iris()
GROUP BY target_name;
Link
models 2 examples12 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_column VARCHAR
Name of the column the model was trained to predict.
n_features BIGINT
Number of features.
n_categorical BIGINT
Number of categorical features.
n_samples BIGINT
Number of training rows.
n_classes BIGINT
Number of classes (NULL for regression).
train_score DOUBLE
In-sample training score.
lightgbm_version VARCHAR
lightgbm 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 lightgbm.main.models;
SELECT count(*) AS n_models, count(DISTINCT estimator) AS n_estimators
FROM lightgbm.main.models();
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
Alcohol content, in percent by volume.
malic_acid DOUBLE
Malic acid concentration, in grams per litre.
ash DOUBLE
Total ash (mineral residue after incineration), in grams per litre.
alcalinity_of_ash DOUBLE
Alkalinity of the ash, in milliequivalents per litre.
magnesium DOUBLE
Magnesium concentration, in milligrams per litre.
total_phenols DOUBLE
Total phenol content, as a concentration index.
flavanoids DOUBLE
Flavanoid phenol content, as a concentration index.
nonflavanoid_phenols DOUBLE
Non-flavanoid phenol content, as a concentration index.
proanthocyanins DOUBLE
Proanthocyanin content, as a concentration index.
color_intensity DOUBLE
Colour intensity of the wine, as an absorbance index.
hue DOUBLE
Colour hue, a ratio derived from the absorbance spectrum.
od280_od315_of_diluted_wines DOUBLE
Ratio of absorbance at 280 nm to absorbance at 315 nm for the diluted wine (a protein-content index).
proline DOUBLE
Proline (an amino acid) concentration, in milligrams per litre.
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 lightgbm.main.wine
GROUP BY target_name;
SELECT sample_id, alcohol, flavanoids, target_name
FROM lightgbm.main.wine()
WHERE alcohol > 13.5
ORDER BY alcohol DESC
LIMIT 10;
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 model by name; `dropped` is false when the name did not exist

SELECT model_name, dropped FROM lightgbm.main.drop_model('no_such_model');
Link
feature_importance (model_name VARCHAR, importance_type := VARCHAR, model := BLOB) 2 examples

Per-feature importance (split or gain) for a model, ranked

Positional arguments
model_name VARCHAR
Name of a stored model (pass '' to use model:= instead).
Named arguments
importance_type := VARCHAR
How importance is measured: split counts a feature's splits, gain totals their gain. · default "gain"
model := BLOB
A fitted model (alternative to 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).
Examples (2)

Gain-based feature importance for a stored model

SELECT feature, round(importance, 3) AS importance
FROM lightgbm.main.feature_importance('iris_clf', importance_type := 'gain')
WHERE rank <= 5
ORDER BY rank;

Do split-gain and permutation importance agree? Join the stored 'iris_clf' model's gain ranking to its permutation (accuracy-drop) ranking per feature; both put the two petal measurements first

SELECT f.feature, f.rank AS gain_rank, p.rank AS permutation_rank,
  round(f.importance, 1) AS gain,
  round(p.importance_mean, 4) AS accuracy_drop
FROM lightgbm.main.feature_importance('iris_clf', importance_type := 'gain') f
JOIN lightgbm.main.permutation_importance((SELECT * EXCLUDE (target_name) FROM lightgbm.main.iris()), model_name := 'iris_clf', target := 'target', random_state := 42) p USING (feature)
ORDER BY f.rank;
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).
target INTEGER
Integer class label (0-based).
feature_0 DOUBLE
First generated feature value.
feature_1 DOUBLE
Second generated feature value.
feature_2 DOUBLE
Third generated feature value.
Returns columns · depends on the arguments
Always present
sample_id INTEGER
Row index within the generated sample (0-based).
target INTEGER
Integer class label (0-based).
Generated features — the shape for `n_features := 3`
feature_0 DOUBLE
First generated feature value.
feature_1 DOUBLE
Second generated feature value.
feature_2 DOUBLE
Third generated feature value.
Example

Class balance and mean first feature of a 500-row, 3-feature, 3-class sample

SELECT target, count(*) AS n, round(avg(feature_0), 3) AS avg_feature_0
FROM lightgbm.main.make_classification(n_samples := 500, n_features := 3, 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).
target DOUBLE
Continuous regression target.
feature_0 DOUBLE
First generated feature value.
feature_1 DOUBLE
Second generated feature value.
feature_2 DOUBLE
Third generated feature value.
Returns columns · depends on the arguments
Always present
sample_id INTEGER
Row index within the generated sample (0-based).
target DOUBLE
Continuous regression target.
Generated features — the shape for `n_features := 3`
feature_0 DOUBLE
First generated feature value.
feature_1 DOUBLE
Second generated feature value.
feature_2 DOUBLE
Third generated feature value.
Example

Mean and spread of a noisy 500-row, 3-feature regression target

SELECT round(avg(target), 3) AS mean_target,
  round(stddev(target), 3) AS sd_target
FROM lightgbm.main.make_regression(n_samples := 500, n_features := 3, 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_column VARCHAR
Name of the column the model was trained to predict.
n_features BIGINT
Number of features.
n_categorical BIGINT
Number of categorical features.
n_samples BIGINT
Number of training rows.
n_classes BIGINT
Number of classes (NULL for regression).
train_score DOUBLE
In-sample training score.
lightgbm_version VARCHAR
lightgbm version used to fit.
created_at VARCHAR
UTC timestamp the model was stored.
features VARCHAR[]
Ordered feature column names.
Example

Check whether a model named 'iris_clf' is in the registry

SELECT count(*) AS found FROM lightgbm.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) 2 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 "lgbm_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
prediction BIGINT
Out-of-fold predicted class label, decoded to the original label value.
prediction VARCHAR
Out-of-fold predicted class label, decoded to the original label value.
prediction DOUBLE
Out-of-fold predicted value.
sample_id INTEGER
The named id column, carried through as the first column.
Returns columns · depends on the arguments
Classification with integer or boolean labels
prediction BIGINT
Out-of-fold predicted class label, decoded to the original label value.
Classification with string labels
prediction VARCHAR
Out-of-fold predicted class label, decoded to the original label value.
Regression
prediction DOUBLE
Out-of-fold predicted value.
`id := '<column>'` passthrough
sample_id INTEGER
The named id column, carried through as the first column.
Examples (2)

Out-of-fold confusion matrix on iris with species names: 5-fold cross_val_predict joined back to iris for the true and the predicted species (setosa is never confused; versicolor and virginica are mixed up a handful of times)

SELECT a.target_name AS actual, l.target_name AS predicted, count(*) AS n
FROM lightgbm.main.cross_val_predict((SELECT * EXCLUDE (target_name) FROM lightgbm.main.iris()), estimator := 'lgbm_classifier', target := 'target', id := 'sample_id', cv := 5) p
JOIN lightgbm.main.iris() a USING (sample_id)
JOIN (SELECT DISTINCT target, target_name FROM lightgbm.main.iris()) l ON l.target = p.prediction
GROUP BY actual, predicted
ORDER BY actual, predicted;
Result
actual predicted n
setosa setosa 50
versicolor versicolor 46
versicolor virginica 4
virginica versicolor 6
virginica virginica 44

Distribution of the 5-fold out-of-fold predictions on iris

SELECT prediction, count(*) AS n
FROM lightgbm.main.cross_val_predict((SELECT sample_id, sepal_length_cm, sepal_width_cm, petal_length_cm, petal_width_cm, target FROM lightgbm.main.iris()), estimator := 'lgbm_classifier', target := 'target')
GROUP BY prediction
ORDER BY prediction;
Link
cross_val_score (data TABLE, cv := BIGINT, estimator := VARCHAR, id := VARCHAR, params := VARCHAR, target := VARCHAR) 1 example

Per-fold cross-validation scores (accuracy or R^2); 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 "lgbm_classifier"
id := VARCHAR
Optional id column to exclude from features. · default ""
params := VARCHAR
JSON object of hyperparameters. · default ""
target := VARCHAR
Name of the target/label column (required). · default ""
Returns columns
fold INTEGER
0-based fold index.
score DOUBLE
Held-out score for the fold (accuracy or R^2).
metric VARCHAR
accuracy (classification) or r2 (regression).
Example

5-fold accuracy scores on iris

SELECT fold, score
FROM lightgbm.main.cross_val_score((SELECT sample_id, sepal_length_cm, sepal_width_cm, petal_length_cm, petal_width_cm, target FROM lightgbm.main.iris()), estimator := 'lgbm_classifier', target := 'target', cv := 5);
Link
explain (data TABLE, id := VARCHAR, model := BLOB, model_name := VARCHAR) 2 examples

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. · default ""
model := BLOB
A fitted model (alternative to model_name). · default "b''"
model_name := VARCHAR
Name of a stored model (or pass model:=). · default ""
Returns columns
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.
class BIGINT
Class index the contribution belongs to (0-based).
sample_id INTEGER
The named id column, carried through as the first column.
Returns columns · depends on the arguments
Always present
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 models only
class BIGINT
Class index the contribution belongs to (0-based).
`id := '<column>'` passthrough
sample_id INTEGER
The named id column, carried through as the first column.
Examples (2)

Rank features by mean absolute SHAP contribution for a stored regressor 'diab_reg'

SELECT feature, round(avg(abs(shap_value)), 4) AS mean_abs_shap
FROM lightgbm.main.explain((SELECT * FROM lightgbm.main.diabetes()), model_name := 'diab_reg', id := 'sample_id')
GROUP BY feature
ORDER BY mean_abs_shap DESC;

Which features push each flower toward its own species? Join SHAP contributions from the stored 'iris_clf' to iris on sample and true class, then average |SHAP| per species and feature (petal length leads for all three species)

SELECT i.target_name, e.feature,
  round(avg(abs(e.shap_value)), 3) AS mean_abs_shap
FROM lightgbm.main.explain((SELECT * EXCLUDE (target_name) FROM lightgbm.main.iris()), model_name := 'iris_clf', id := 'sample_id') e
JOIN lightgbm.main.iris() i ON i.sample_id = e.sample_id AND i.target = e.class
GROUP BY i.target_name, e.feature
ORDER BY i.target_name, mean_abs_shap DESC;
Link
fit (data TABLE, estimator := VARCHAR, id := VARCHAR, model_name := VARCHAR, params := VARCHAR, target := VARCHAR) 1 example

Fit a LightGBM estimator; returns the model as a BLOB and stores it when model_name is given

Positional arguments
data TABLE
Training rows: features + target [+ id].
Named arguments
estimator := VARCHAR
Estimator name. · default "lgbm_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 (NULL 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).
n_categorical BIGINT
Number of categorical (string) features.
train_score DOUBLE
In-sample score (accuracy or R^2).
features VARCHAR[]
Ordered feature column names.
model BLOB
The fitted model as a portable `BLOB`.
Example

Train a LightGBM classifier on iris and store it as 'iris_clf'

SELECT model_name, task, n_samples
FROM lightgbm.main.fit((SELECT sample_id, sepal_length_cm, sepal_width_cm, petal_length_cm, petal_width_cm, target FROM lightgbm.main.iris()), model_name := 'iris_clf', estimator := 'lgbm_classifier', target := 'target', id := 'sample_id');
Link
fit_lgbm_classifier (data TABLE, boosting_type := VARCHAR, colsample_bytree := DOUBLE, id := VARCHAR, learning_rate := DOUBLE, max_depth := BIGINT, min_child_samples := BIGINT, model_name := VARCHAR, n_estimators := BIGINT, num_leaves := BIGINT, objective := VARCHAR, random_state := BIGINT, reg_alpha := DOUBLE, reg_lambda := DOUBLE, subsample := DOUBLE, target := VARCHAR) 1 example

Fit a lgbm_classifier with typed LightGBM hyperparameters; returns/stores the model

Positional arguments
data TABLE
Training rows: features + target [+ id].
Named arguments
boosting_type := VARCHAR
Boosting algorithm. · default "gbdt"
colsample_bytree := DOUBLE
Column subsampling fraction per tree. · default 1.0
id := VARCHAR
Optional id passthrough column. · default ""
learning_rate := DOUBLE
Shrinkage applied to each tree. · default 0.1
max_depth := BIGINT
Max tree depth; 0 = unlimited. · default 0
min_child_samples := BIGINT
Min data in a leaf (regularization). · default 20
model_name := VARCHAR
Optional registry name; the model is always returned as a `BLOB`. · default ""
n_estimators := BIGINT
Number of boosting iterations (trees). · default 100
num_leaves := BIGINT
Max leaves per tree (the main capacity knob). · default 31
objective := VARCHAR
LightGBM objective; '' keeps the task default. · default ""
random_state := BIGINT
Random seed. · default 0
reg_alpha := DOUBLE
L1 regularization. · default 0.0
reg_lambda := DOUBLE
L2 regularization. · default 0.0
subsample := DOUBLE
Row subsampling fraction (bagging_fraction). · default 1.0
target := VARCHAR
Label column name (required). · default ""
Returns columns
model_name VARCHAR
Name the model was stored under (NULL 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).
n_categorical BIGINT
Number of categorical (string) features.
train_score DOUBLE
In-sample score (accuracy or R^2).
features VARCHAR[]
Ordered feature column names.
model BLOB
The fitted model as a portable `BLOB`.
Example

Train a lgbm_classifier with named hyperparameters

SELECT model_name, task
FROM lightgbm.main.fit_lgbm_classifier((SELECT * EXCLUDE (target_name) FROM lightgbm.main.iris()), model_name := 'm', target := 'target', id := 'sample_id', n_estimators := 100, num_leaves := 31);
Link
fit_lgbm_regressor (data TABLE, boosting_type := VARCHAR, colsample_bytree := DOUBLE, id := VARCHAR, learning_rate := DOUBLE, max_depth := BIGINT, min_child_samples := BIGINT, model_name := VARCHAR, n_estimators := BIGINT, num_leaves := BIGINT, objective := VARCHAR, random_state := BIGINT, reg_alpha := DOUBLE, reg_lambda := DOUBLE, subsample := DOUBLE, target := VARCHAR) 1 example

Fit a lgbm_regressor with typed LightGBM hyperparameters; returns/stores the model

Positional arguments
data TABLE
Training rows: features + target [+ id].
Named arguments
boosting_type := VARCHAR
Boosting algorithm. · default "gbdt"
colsample_bytree := DOUBLE
Column subsampling fraction per tree. · default 1.0
id := VARCHAR
Optional id passthrough column. · default ""
learning_rate := DOUBLE
Shrinkage applied to each tree. · default 0.1
max_depth := BIGINT
Max tree depth; 0 = unlimited. · default 0
min_child_samples := BIGINT
Min data in a leaf (regularization). · default 20
model_name := VARCHAR
Optional registry name; the model is always returned as a `BLOB`. · default ""
n_estimators := BIGINT
Number of boosting iterations (trees). · default 100
num_leaves := BIGINT
Max leaves per tree (the main capacity knob). · default 31
objective := VARCHAR
LightGBM objective; '' keeps the task default. · default "regression"
random_state := BIGINT
Random seed. · default 0
reg_alpha := DOUBLE
L1 regularization. · default 0.0
reg_lambda := DOUBLE
L2 regularization. · default 0.0
subsample := DOUBLE
Row subsampling fraction (bagging_fraction). · default 1.0
target := VARCHAR
Label column name (required). · default ""
Returns columns
model_name VARCHAR
Name the model was stored under (NULL 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).
n_categorical BIGINT
Number of categorical (string) features.
train_score DOUBLE
In-sample score (accuracy or R^2).
features VARCHAR[]
Ordered feature column names.
model BLOB
The fitted model as a portable `BLOB`.
Example

Train a lgbm_regressor with named hyperparameters

SELECT model_name, task
FROM lightgbm.main.fit_lgbm_regressor((SELECT * EXCLUDE (target_name) FROM lightgbm.main.iris()), model_name := 'm', target := 'target', id := 'sample_id', n_estimators := 100, num_leaves := 31);
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 label (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 feature_value, round(partial_dependence, 4) AS pd
FROM lightgbm.main.partial_dependence((SELECT * EXCLUDE (target_name) FROM lightgbm.main.iris()), model_name := 'iris_clf', feature := 'petal_length_cm', grid_resolution := 5)
WHERE class = 0
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, ranked

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, round(importance_mean, 4) AS importance_mean
FROM lightgbm.main.permutation_importance((SELECT * EXCLUDE (target_name) FROM lightgbm.main.iris()), model_name := 'iris_clf', target := 'target', n_repeats := 1)
WHERE rank <= 3
ORDER BY rank;
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 (model_name) or an inline model BLOB

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 from fit() (alternative to model_name). · default "b''"
model_name := VARCHAR
Name of a stored model (or pass 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
prediction BIGINT
Predicted class label, decoded to the original label value.
prediction VARCHAR
Predicted class label, decoded to the original label value.
prediction DOUBLE
Predicted value.
proba_<label> DOUBLE
Predicted probability of that class; one column per class, keyed by the original label.
margin DOUBLE
Raw (pre-link) margin score from the booster.
leaf INTEGER[]
Leaf index reached in each tree, one element per tree.
sample_id INTEGER
The named id column, carried through as the first column.
Returns columns · depends on the arguments
Default — classification with integer or boolean labels
prediction BIGINT
Predicted class label, decoded to the original label value.
Default — classification with string labels
prediction VARCHAR
Predicted class label, decoded to the original label value.
Default — regression
prediction DOUBLE
Predicted value.
`with_proba := true` (classifiers only)
proba_<label> DOUBLE
Predicted probability of that class; one column per class, keyed by the original label.
`output_margin := true`
margin DOUBLE
Raw (pre-link) margin score from the booster.
`pred_leaf := true`
leaf INTEGER[]
Leaf index reached in each tree, one element per tree.
`id := '<column>'` passthrough
sample_id INTEGER
The named id column, carried through as the first column.
Example

Predict with the stored 'iris_clf' model

SELECT sample_id, prediction
FROM lightgbm.main.predict((SELECT * FROM lightgbm.main.iris()), model_name := 'iris_clf', id := 'sample_id')
ORDER BY sample_id
LIMIT 10;
Link

Try these queries

Load the built-in iris dataset.

SELECT * FROM lightgbm.main.iris LIMIT 5;

Uses iris

Fit a LightGBM classifier on iris, then predict with the fitted model.

SET VARIABLE iris_model = (SELECT model FROM lightgbm.main.fit((SELECT * EXCLUDE (target_name) FROM lightgbm.main.iris), estimator := 'lgbm_classifier', target := 'target', id := 'sample_id'));
SELECT sample_id, prediction FROM lightgbm.main.predict((SELECT * FROM lightgbm.main.iris), model := getvariable('iris_model'), id := 'sample_id') LIMIT 5;

Uses fitirispredict

Three-fold cross-validated accuracy of a LightGBM classifier on iris.

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

Uses cross_val_scoreiris

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

SELECT params, mean_score, rank
FROM lightgbm.main.grid_search((SELECT * EXCLUDE (target_name) FROM lightgbm.main.iris), target := 'target', cv := 3, estimator := 'lgbm_classifier', num_leaves := [15, 31], learning_rate := [0.1])
ORDER BY rank;

Uses grid_searchiris

Do split-gain and permutation importance agree? Join the stored 'iris_clf' model's gain ranking to its permutation (accuracy-drop) ranking per feature; both put the two petal measurements first

SELECT f.feature, f.rank AS gain_rank, p.rank AS permutation_rank,
  round(f.importance, 1) AS gain,
  round(p.importance_mean, 4) AS accuracy_drop
FROM lightgbm.main.feature_importance('iris_clf', importance_type := 'gain') f
JOIN lightgbm.main.permutation_importance((SELECT * EXCLUDE (target_name) FROM lightgbm.main.iris()), model_name := 'iris_clf', target := 'target', random_state := 42) p USING (feature)
ORDER BY f.rank

Uses feature_importancepermutation_importance

Which features push each flower toward its own species? Join SHAP contributions from the stored 'iris_clf' to iris on sample and true class, then average |SHAP| per species and feature (petal length leads for all three species)

SELECT i.target_name, e.feature,
  round(avg(abs(e.shap_value)), 3) AS mean_abs_shap
FROM lightgbm.main.explain((SELECT * EXCLUDE (target_name) FROM lightgbm.main.iris()), model_name := 'iris_clf', id := 'sample_id') e
JOIN lightgbm.main.iris() i ON i.sample_id = e.sample_id AND i.target = e.class
GROUP BY i.target_name, e.feature
ORDER BY i.target_name, mean_abs_shap DESC

Uses explain

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

LightGBM 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.