Beispiele · scikit-learn
Stacking-Ensemble aus XGBoost, LightGBM und CatBoost
Wer Wettbewerbe gewinnt, reicht selten ein einzelnes Modell ein. Hier klassifizieren XGBoost, LightGBM und CatBoost dieselben 20 Merkmale, und eine logistische Regression lernt, wie sehr sie jedem davon trauen kann.
- Code
- scikit-learn
- Aufgabe
- Klassifikation
- Eingabe
- 20
- Bausteine
- 5
- Modell
- StackingClassifier
Was das Netz macht
Die drei Modelle bekommen die Merkmale vom Input: XGBClassifier mit 300 Bäumen der Tiefe 6, LGBMClassifier mit 300 blattweise gewachsenen Bäumen mit bis zu 31 Blättern und CatBoostClassifier mit 500 symmetrischen Bäumen der Tiefe 6, alle mit der Lernrate 0,05. Sie bauen ihre Bäume verschieden und machen daher verschiedene Fehler. Die gepunkteten Verbindungen zum StackingClassifier tragen die Modelle selbst.
Mit cv = 5 wird jedes Modell fünfmal angepasst, jedes Mal ohne ein Fünftel der Trainingszeilen, und sagt die Klassenwahrscheinlichkeiten dieses Fünftels vorher. Die logistische Regression lernt aus diesen Vorhersagen für Zeilen, die die Modelle nicht gesehen haben; danach wird jedes Modell noch einmal auf allen Zeilen angepasst. In einem Ensemble bekommen die Modelle keine Validierungszeilen und passen daher alle ihre Bäume an: Das frühe Stoppen ist aus, und die Zahl der Bäume ist kleiner als bei einem einzelnen Modell.
Wann es passt
- Wenn jede Bibliothek für sich gute Einstellungen erreicht hat und Sie die zusätzliche Genauigkeit der Kombination wollen.
- Für Tabellen bis zu Hunderttausenden Zeilen: Die Anpassung dauert etwa sechsmal so lange wie die der drei Modelle einzeln.
- Um die Bibliotheken zu vergleichen: Der Lauf zeigt die Bewertung jedes Modells neben der des Ensembles.
Schichten, Formen und Parameter
| Baustein | Typ | Einstellungen | Ausgabe | Parameter |
|---|---|---|---|---|
features | Input | shape=20 | 20 | 0 |
xgboost | XGBClassifier | n_estimators=300 learning_rate=0.05 max_depth=6 subsample=0.8 colsample_bytree=0.8 early_stopping_rounds=0 random_state=0 | Modell | – |
lightgbm | LGBMClassifier | n_estimators=300 learning_rate=0.05 num_leaves=31 subsample=0.8 colsample_bytree=0.8 early_stopping_rounds=0 random_state=0 | Modell | – |
catboost | CatBoostClassifier | iterations=500 learning_rate=0.05 depth=6 early_stopping_rounds=0 random_state=0 | Modell | – |
stack | StackingClassifier | cv=5 passthrough=false | Klassen | – |
| Gesamt | keine: scikit-learn passt das Modell an | |||
Training in Brick DNN
Laden Sie eine CSV-Datei mit 20 numerischen Merkmalen und einer Klassenspalte hoch oder nehmen Sie einen Datensatz aus dem Bereich Daten. Das Ensemble trainiert wie ein einzelnes klassisches Modell, mit derselben Auswertung, denselben Erklärungen und demselben Download; das erzeugte Skript braucht installiertes xgboost, lightgbm und catboost.
Der erzeugte Code
Das ist das scikit-learn-Skript, das der Code-Dialog des Editors aus dem Graphen oben erzeugt (boosting_stacking_ensemble.py). Es läuft für sich: python boosting_stacking_ensemble.py passt das Modell an Zufallsdaten an, --csv daten.csv an Ihre Tabelle und speichert es, --predict sagt neue Zeilen vorher.
# Built with Brick DNN: https://brickdnn.com, https://github.com/alexanderKuehling/brick-dnn
"""Stacking classifier: generated with Brick DNN.
A scikit-learn ensemble for 20 numeric features: they are standardised, then
StackingClassifier combines 3 models (xgboost: XGBClassifier, lightgbm: LGBMClassifier,
catboost: CatBoostClassifier) and predicts the class of each row. LogisticRegression learns
from their predictions for rows they were not fitted on (5-fold cross-validation) how to
combine them.
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 catboost import CatBoostClassifier
from lightgbm import LGBMClassifier
from sklearn.ensemble import StackingClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score, balanced_accuracy_score, f1_score, roc_auc_score
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from xgboost import XGBClassifier
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 StackingClassifier with its 3 models."""
xgboost = XGBClassifier(
n_estimators=300,
learning_rate=0.05,
max_depth=6,
min_child_weight=1.0,
subsample=0.8,
colsample_bytree=0.8,
reg_alpha=0.0,
reg_lambda=1.0,
random_state=0,
)
lightgbm = LGBMClassifier(
n_estimators=300,
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,
random_state=0,
verbose=-1,
)
catboost = CatBoostClassifier(
iterations=500,
learning_rate=0.05,
depth=6,
l2_leaf_reg=3.0,
random_seed=0,
verbose=0,
allow_writing_files=False,
)
model = StackingClassifier(
estimators=[("xgboost", xgboost), ("lightgbm", lightgbm), ("catboost", catboost)],
final_estimator=LogisticRegression(),
cv=5,
passthrough=False,
)
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()
model.fit(features[train_rows], target[train_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%}")
ensemble = model.named_steps["model"]
print(f"Models: {', '.join(ensemble.named_estimators_)}")
print(f"Final estimator: {ensemble.final_estimator_}")
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]) -> 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(name) for name 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, "yes", "no")
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="Stacking classifier, 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)
# Logged to Brick DNN only with the environment variable BRICKDNN_TOKEN.
with BrickDNNRun.start(
name="Stacking classifier",
config={
"model": "StackingClassifier",
"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)
return
demo(model)
if __name__ == "__main__":
main()