Examples · scikit-learn
LightGBM classifier for tabular data
LightGBM is one of the gradient boosting libraries that win tabular competitions. This example classifies rows of 20 numeric features and lets early stopping decide how many trees it needs.
Open in the editor See the code
- Code
- scikit-learn
- Task
- Classification
- Input
- 20
- Bricks
- 2
- Model
- LGBMClassifier
What the network does
The LGBMClassifier brick adds trees one after the other, each correcting the errors of the trees before it, scaled by the learning rate of 0.05. LightGBM grows each tree leaf by leaf, always splitting the leaf that helps most, up to 31 leaves (num_leaves) with at least 20 rows each. Each tree sees 80 % of the training rows and of the features (subsample, colsample_bytree), which makes the trees differ and the model generalise better.
At most 1,000 trees (n_estimators): with early_stopping_rounds = 50 the fit watches the loss on the validation rows, stops when 50 trees in a row have not improved it and keeps the best round. The validation metrics are then a little optimistic; the test rows stay untouched. class_weight = balanced weights each class inversely to its frequency.
When to use it
- For tables with tens of thousands to millions of rows: LightGBM is among the fastest boosting libraries. Brick DNN fits it on up to 1,000,000 training rows.
- When the last per cent of accuracy counts, as in competitions; combine it with XGBoost and CatBoost in a stacking ensemble.
- Text columns are one-hot encoded in the Data tab first, as for the other classical models.
Layers, shapes and parameters
| Brick | Type | Settings | Output | Parameters |
|---|---|---|---|---|
features | Input | shape=20 | 20 | 0 |
lightgbm | LGBMClassifier | n_estimators=1000 learning_rate=0.05 num_leaves=31 min_child_samples=20 subsample=0.8 colsample_bytree=0.8 reg_alpha=0 reg_lambda=0 early_stopping_rounds=50 class_weight=balanced random_state=0 | classes | – |
| Total | none: fitted by scikit-learn | |||
Training it in Brick DNN
Upload a CSV file of 20 numeric features and a class column, or a dataset from the Data tab, and keep a validation split above 0 for early stopping. The run reports how many trees early stopping kept, accuracy, balanced accuracy, the confusion matrix and, for two classes, ROC and PR curves. A search over learning rate, leaves and rows per leaf finds better settings; the downloaded model works in the generated script with LightGBM installed.
The generated code
This is the scikit-learn script that the editor’s code dialog generates from the graph above (lightgbm_classifier.py). It runs on its own: python lightgbm_classifier.py fits the model to random data, --csv data.csv fits it to your table and saves it, --predict predicts new rows.
# Built with Brick DNN: https://brickdnn.com, https://github.com/alexanderKuehling/brick-dnn
"""LightGBM classification: generated with Brick DNN.
A scikit-learn model for 20 numeric features: they are standardised, then LGBMClassifier
predicts the class of each row. The trees do not need standardised features (their splits
stay the same); the scaler keeps the saved model in the format of the other classical
models. Early stopping: the fit to a CSV file stops adding trees when the loss on the
validation rows has not improved for 50 rounds.
Print the model and fit it to random data:
python this_file.py
Fit it to a CSV file (every column but the last is a feature, the last column is
the target), then predict new rows with the saved model:
python this_file.py --csv data.csv
python this_file.py --predict new_data.csv
Log the fit to Brick DNN, to see its results next to the runs trained there (the runs
page): create an API token on the page API tokens (one that may only log runs is enough)
and set it in the environment before you train:
export BRICKDNN_TOKEN=<your token>
python this_file.py --csv data.csv
It sends the model and its hyperparameters, the name of the CSV file, the accuracy,
balanced accuracy, F1 and (two classes) ROC AUC on the validation rows and the time the
fit took to BRICKDNN_URL (default https://brickdnn.com). Without BRICKDNN_TOKEN nothing
is sent and the script runs offline with the same results; a network error never stops
the training. The token is never stored in this file.
"""
from __future__ import annotations
import argparse
import csv
import json
import math
import os
import sys
import time
import urllib.error
import urllib.request
import warnings
import joblib
import numpy as np
from lightgbm import LGBMClassifier
from sklearn.metrics import accuracy_score, balanced_accuracy_score, f1_score, roc_auc_score
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
NUM_FEATURES = 20
def make_model() -> Pipeline:
"""Standardise the features (with the mean and standard deviation of the data
it is fitted to), then fit LGBMClassifier."""
model = LGBMClassifier(
n_estimators=1000,
learning_rate=0.05,
num_leaves=31,
max_depth=-1,
min_child_samples=20,
subsample=0.8,
subsample_freq=1,
colsample_bytree=0.8,
reg_alpha=0.0,
reg_lambda=0.0,
early_stopping_rounds=50,
class_weight="balanced",
random_state=0,
verbose=-1,
)
return Pipeline([("scale", StandardScaler()), ("model", model)])
# --------------------------------------------------------------------------- #
# CSV files: fitting, saving and predictions for new rows
# --------------------------------------------------------------------------- #
def read_csv(path: str) -> tuple[list[str], list[list[str]]]:
"""Read a CSV file: the column names of its header line (an empty list if it has none)
and the rows (as text)."""
with open(path, newline="") as f:
rows = [row for row in csv.reader(f) if row]
header: list[str] = []
if rows:
cells = rows[0][:-1] or rows[0] # the last column (the target) may hold text
try:
[float(value) for value in cells]
except ValueError:
header, rows = [name.strip() for name in rows[0]], rows[1:]
if not rows:
raise SystemExit(f"{path} contains no data rows.")
return header, rows
def numbers(rows: list[list[str]], path: str) -> np.ndarray:
try:
return np.array([[float(value) for value in row] for row in rows])
except ValueError as exc:
raise SystemExit(f"{path}: {exc}") from None
def load_csv(path: str) -> tuple[list[str], np.ndarray, np.ndarray]:
"""Training data: every column but the last is a feature, the last one is the target."""
header, rows = read_csv(path)
if any(len(row) != NUM_FEATURES + 1 for row in rows):
raise SystemExit(f"Expected {NUM_FEATURES} feature columns and the target in every row.")
features = numbers([row[:-1] for row in rows], path)
target = np.array([row[-1].strip() for row in rows]) # the class labels
return header, features, target
def fit(
model: Pipeline,
features: np.ndarray,
target: np.ndarray,
seed: int,
run: BrickDNNRun | None = None,
) -> None:
"""Fit on a random 80 % of the rows and validate on the rest (the split depends only on
``seed``). The StandardScaler of the pipeline learns from the training rows only."""
if len(features) < 4:
raise SystemExit("The CSV file needs at least 4 rows (training + validation).")
order = np.random.default_rng(seed).permutation(len(features))
n_val = max(1, len(features) // 5)
val_rows, train_rows = order[:n_val], order[n_val:]
print(f"Fitting on {len(train_rows)} rows, {len(val_rows)} for validation")
started = time.perf_counter()
# Early stopping: LightGBM watches the loss on the validation rows (standardised
# like the training rows) and keeps the trees up to its best round.
watch = model[:-1].fit(features[train_rows]).transform(features[val_rows])
model.fit(
features[train_rows],
target[train_rows],
model__eval_X=watch,
model__eval_y=target[val_rows],
)
seconds = time.perf_counter() - started
print(f"Fitted in {seconds:.1f} s")
accuracy = float(np.mean(model.predict(features[val_rows]) == target[val_rows]))
print(f"Validation accuracy {accuracy:.1%}")
boosting = model.named_steps["model"]
# Early stopping keeps the trees up to the best round on the validation rows.
print(f"Trees: {boosting.best_iteration_} of at most {boosting.n_estimators}")
if run is not None and run.active:
summary = scores(model, features[val_rows], target[val_rows])
run.finish(summary={**summary, "fit_seconds": round(seconds, 3)})
def save_model(model: Pipeline, path: str, header: list[str], class_names: np.ndarray) -> None:
"""Save the fitted pipeline with what predict() needs to read new rows. joblib files
are pickles: only load files you trust."""
bundle = {
"format": "brickdnn-sklearn-1",
"model": model,
"columns": header[:-1], # the feature columns by name (empty: no header line)
"target": header[-1] if header else "target",
"task": "classification",
# one name per column of model.predict_proba()
"class_names": [str(class_names[i]) for i in model.classes_],
}
joblib.dump(bundle, path)
print(f"Saved the fitted model to {path}")
def scores(model: Pipeline, features: np.ndarray, target: np.ndarray) -> dict[str, float]:
"""The numbers of the fitted model on the validation rows that are logged to Brick DNN,
named like the columns of its runs table. Logging never stops the script: a number that
cannot be computed is left out."""
found: dict[str, float] = {}
try:
with warnings.catch_warnings():
warnings.simplefilter("ignore") # e.g. a class without validation rows
predicted = model.predict(features)
found["val_accuracy"] = float(accuracy_score(target, predicted))
found["val_balanced_accuracy"] = float(balanced_accuracy_score(target, predicted))
for average in ("macro", "weighted"):
f1 = f1_score(target, predicted, average=average, zero_division=0)
found[f"val_{average}_f1"] = float(f1)
if len(model.classes_) == 2:
positive = target == model.classes_[1]
probability = model.predict_proba(features)[:, 1]
found["val_roc_auc"] = float(roc_auc_score(positive, probability))
except Exception:
pass
return found
def model_settings(model: Pipeline) -> dict:
"""The hyperparameters of the model for its run in Brick DNN: numbers, words and
switches, other objects (an inner model) as text, at most 60. It only reads them."""
found: dict = {}
try:
for key, value in model.named_steps["model"].get_params().items():
if isinstance(value, np.generic):
value = value.item()
if isinstance(value, float) and not math.isfinite(value):
value = str(value)
if value is None or isinstance(value, (bool, int, float)):
found[key] = value
elif isinstance(value, str) or ("__" not in key and hasattr(value, "get_params")):
found[key] = str(value)[:120]
if len(found) == 60:
break
except Exception: # logging never stops the script
pass
return found
def predict(path: str, csv_path: str) -> None:
"""Print a prediction for every row of a CSV file.
If both the saved model and the file have a header line, the feature columns are found
by their names; otherwise they have to come first. Other columns (such as the target)
are ignored. The pipeline standardises the features like the training data.
"""
bundle = joblib.load(path) # a pickle: only load files you trust
model, columns = bundle["model"], bundle["columns"]
header, rows = read_csv(csv_path)
if columns and header:
missing = [name for name in columns if name not in header]
if missing:
raise SystemExit(f"{csv_path} lacks the columns {', '.join(missing)}.")
rows = [[row[header.index(name)] for name in columns] for row in rows]
elif all(len(row) >= NUM_FEATURES for row in rows):
rows = [row[:NUM_FEATURES] for row in rows]
else:
raise SystemExit(f"Expected {NUM_FEATURES} feature columns.")
features = numbers(rows, csv_path)
probabilities = model.predict_proba(features)
names = bundle["class_names"]
print(f"{bundle['target']},probability")
for row in probabilities:
best = int(np.argmax(row))
print(f"{names[best]},{row[best]:.4f}")
def demo(model: Pipeline) -> None:
"""Fit the model to 40 random rows and predict two of them (shows that it works)."""
rng = np.random.default_rng(0)
features = rng.normal(size=(40, NUM_FEATURES))
target = np.where(features[:, 0] + features[:, -1] > 0, 1, 0) # indices
# The demo sets no validation rows aside, which early stopping needs.
model.set_params(model__early_stopping_rounds=None)
model.fit(features, target)
print("Predictions for 2 random rows:", model.predict(features[:2]))
# --------------------------------------------------------------------------- #
# Logging to Brick DNN, only with the environment variable BRICKDNN_TOKEN
# --------------------------------------------------------------------------- #
# The server and the saved network the runs belong to (BRICKDNN_URL and BRICKDNN_PROJECT
# override them). The token is never stored here: it is read from BRICKDNN_TOKEN.
BRICKDNN_URL = "https://brickdnn.com"
BRICKDNN_PROJECT = None
class BrickDNNRun:
"""A run logged to Brick DNN (see brickdnn/tracking.py), or an inert one without the
environment variable BRICKDNN_TOKEN."""
# Points are sent in batches: when this many are waiting, or after INTERVAL seconds.
BATCH = 200
INTERVAL = 2.0
# Points kept while the server cannot be reached; failures in a row before giving up.
BUFFER = 1000
ATTEMPTS = 3
RETRY_SECONDS = 10.0
TIMEOUT = 5.0
def __init__(self, url: str | None = None, token: str | None = None) -> None:
url = os.environ.get("BRICKDNN_URL") or url or "https://brickdnn.com"
self.url = url.strip().rstrip("/")
self.token = (token if token is not None else os.environ.get("BRICKDNN_TOKEN", "")).strip()
self.id: str | None = None
self.active = bool(self.token)
self.points: list[dict] = []
self._create: dict = {}
self._started = time.monotonic()
self._sent = self._started # the first batch waits INTERVAL too
self._failures = 0
self._retry_at = 0.0
self._warned = False
@classmethod
def start(
cls,
name: str | None = None,
config: dict | None = None,
project: int | None = None,
dataset: str | None = None,
task: str | None = None,
epochs: int | None = None,
url: str | None = None,
token: str | None = None,
) -> BrickDNNRun:
"""Create the run on the server (nothing happens without a token)."""
run = cls(url, token)
if not run.active:
return run
if os.environ.get("BRICKDNN_PROJECT", "").strip().isdigit():
project = int(os.environ["BRICKDNN_PROJECT"].strip())
body = {
"name": os.environ.get("BRICKDNN_RUN_NAME") or name,
"config": config or {},
"project": project,
"dataset": dataset,
"task": task,
"epochs": epochs,
"client": "brickdnn-tracking/1",
}
run._create = {key: value for key, value in body.items() if value is not None}
run._open()
return run
def _open(self) -> bool:
"""Create the run on the server if that has not worked yet."""
if self.id is None and self.active and time.monotonic() >= self._retry_at:
answer = self._send("POST", "/api/tracking/runs/", self._create)
if isinstance(answer, dict) and isinstance(answer.get("id"), str):
self.id = answer["id"]
print(f"Brick DNN: logging this run to {self.url}/runs", file=sys.stderr)
return self.id is not None
def log(self, epoch: int | None = None, step: int | None = None, **metrics) -> None:
"""One point of the curves: ``epoch`` (or ``step``) and numbers such as
``train_loss``, ``val_loss`` or ``val_accuracy``; other values are left out."""
if not self.active:
return
try:
point: dict = {"time": round(time.monotonic() - self._started, 3)}
if epoch is not None:
point["epoch"] = int(epoch)
if step is not None:
point["step"] = int(step)
for key, value in metrics.items():
number = self._number(value)
if number is not None:
point[str(key)] = number
self.points.append(point)
del self.points[: max(0, len(self.points) - self.BUFFER)]
if len(self.points) >= self.BATCH or time.monotonic() - self._sent >= self.INTERVAL:
self.flush()
except Exception as error: # logging never stops the training
self._fail(error)
def flush(self) -> None:
"""Send the points that wait."""
if not self.active or not self.points or time.monotonic() < self._retry_at:
return
if not self._open():
return
while self.active and self.points:
batch = self.points[: self.BATCH]
if self._send("POST", f"/api/tracking/runs/{self.id}/log/", {"points": batch}) is None:
return
del self.points[: len(batch)]
self._sent = time.monotonic()
def finish(
self, status: str = "completed", summary: dict | None = None, message: str | None = None
) -> None:
"""End the run: ``completed``, ``failed`` or ``stopped``, with its final numbers
(e.g. ``{"test_accuracy": 0.93}``)."""
if not self.active:
return
try:
self._retry_at = 0.0
self.flush()
if self.active and self._open():
numbers = {str(k): self._number(v) for k, v in (summary or {}).items()}
body: dict = {
"status": status,
"summary": {k: v for k, v in numbers.items() if v is not None},
}
if message:
body["message"] = str(message)[:500]
self._send("POST", f"/api/tracking/runs/{self.id}/finish/", body)
except Exception as error:
self._fail(error)
self.active = False
def __enter__(self) -> BrickDNNRun:
return self
def __exit__(self, kind, error, traceback) -> bool:
if kind is None:
self.finish("completed")
elif issubclass(kind, KeyboardInterrupt):
self.finish("stopped", message="Stopped with Ctrl+C.")
else:
self.finish("failed", message=f"{kind.__name__}: {error}")
return False # an error goes on as before
@staticmethod
def _number(value) -> float | int | None:
try:
if hasattr(value, "item"):
value = value.item() # a tensor or a NumPy number
if isinstance(value, bool) or not isinstance(value, (int, float)):
return None
return value if math.isfinite(value) else None
except Exception:
return None
def _send(self, method: str, path: str, body: dict) -> dict | None:
"""The server's answer, or None if the request failed (warned once)."""
try:
request = urllib.request.Request(
self.url + path,
data=json.dumps(body).encode(),
method=method,
headers={
"Authorization": f"Bearer {self.token}",
"Content-Type": "application/json",
"User-Agent": "brickdnn-tracking/1",
},
)
with urllib.request.urlopen(request, timeout=self.TIMEOUT) as response:
answer = json.loads(response.read().decode() or "{}")
self._failures = 0
return answer if isinstance(answer, dict) else {}
except urllib.error.HTTPError as error:
# Busy or broken for a moment: again later. Refused (token, limit, the run was
# stopped in the app): for good.
self._fail(error, final=error.code not in (408, 429) and error.code < 500)
except Exception as error:
self._fail(error)
return None
def _fail(self, error: Exception, final: bool = False) -> None:
self._failures += 1
if not self._warned:
self._warned = True
detail = str(error)
if isinstance(error, urllib.error.HTTPError):
try:
detail = json.loads(error.read().decode()).get("detail") or detail
except Exception:
detail = f"HTTP {error.code}"
print(
f"Brick DNN: could not log to {self.url} ({detail}). The training goes on"
+ ("." if final else "; logging is tried again a few times."),
file=sys.stderr,
)
if final or self._failures >= self.ATTEMPTS:
self.active = False
self.points = []
else:
self._retry_at = time.monotonic() + self.RETRY_SECONDS
def main() -> None:
parser = argparse.ArgumentParser(
description="LightGBM classification, generated with Brick DNN"
)
parser.add_argument("--csv", help="fit the model to this CSV file (last column = target)")
parser.add_argument("--predict", metavar="CSV", help="predict the rows of this file")
parser.add_argument("--seed", type=int, default=0, help="for a repeatable split")
parser.add_argument(
"--save",
default="model.joblib",
help="the fitted model (--csv writes it, --predict reads it)",
)
args = parser.parse_args()
if args.predict:
predict(args.save, args.predict)
return
model = make_model()
print(model)
if args.csv:
header, features, target = load_csv(args.csv)
# The model learns the classes as indices 0, 1, …: save_model() names them again.
class_names, target = np.unique(target, return_inverse=True)
# Logged to Brick DNN only with the environment variable BRICKDNN_TOKEN.
with BrickDNNRun.start(
name="LightGBM classification",
config={
"model": "LGBMClassifier",
"seed": args.seed,
"val_split": 0.2,
"params": model_settings(model),
},
project=BRICKDNN_PROJECT,
dataset=os.path.basename(args.csv),
task="classification",
url=BRICKDNN_URL,
) as run:
fit(model, features, target, args.seed, run)
save_model(model, args.save, header, class_names)
return
demo(model)
if __name__ == "__main__":
main()