Beispiele · scikit-learn

Voting-Ensemble zur Klassifikation in scikit-learn

Drei unterschiedliche Klassifikatoren betrachten dieselben vier Merkmale, und das Ensemble mittelt ihre Klassenwahrscheinlichkeiten. Modelle, die verschiedene Fehler machen, gleichen einen Teil davon gegenseitig aus.

Im Editor öffnen Zum Code

Code
scikit-learn
Aufgabe
Klassifikation
Eingabe
4
Bausteine
5
Modell
VotingClassifier

Was das Netz macht

Der Input versorgt alle drei Modelle: HistGradientBoostingClassifier (Bäume), SVC (eine Kernel-Grenze) und GaussianProcessClassifier (mit seinem Standardkernel, einem skalierten RBF). Die gepunkteten Verbindungen zum VotingClassifier tragen die Modelle selbst, nicht ihre Vorhersagen; das Ensemble passt jedes davon an die Trainingszeilen an.

Mit voting = soft mittelt das Ensemble die vorhergesagten Wahrscheinlichkeiten und wählt die wahrscheinlichste Klasse. Hard Voting würde stattdessen die vorhergesagten Klassen auszählen. Optionale Gewichte lassen ein Modell stärker zählen; sie folgen der Reihenfolge der Verbindungen.

Wann es passt

  • Wenn mehrere Modelle etwa gleich gut sind und bei verschiedenen Zeilen danebenliegen: Der Mittelwert ist oft besser als das beste Einzelmodell.
  • Für kleine und mittlere Tabellen: Das langsamste Modell setzt die Grenze, hier der Gauß-Prozess-Klassifikator (höchstens 2.000 Trainingszeilen in Brick DNN).
  • Um zu prüfen, ob das Kombinieren hilft: Der Lauf zeigt den Score jedes Modells neben dem des Ensembles.

Schichten, Formen und Parameter

Diagramm des Beispiels Voting-EnsembleInput (4), HistGradientBoostingClassifier (Modell), SVC (Modell), GaussianProcessClassifier (Modell), VotingClassifier (Klassen)Input4HistGradientBoostingClassifierModellSVCModellGaussianProcessClassifierModell2 HyperparameterVotingClassifierKlassen
Das Netz so, wie es im Editor angeordnet ist. Jeder Kasten zeigt die Ausgabeform (ohne Batch-Dimension) und die Zahl der Parameter.
Die Bausteine von Voting-Ensemble: Einstellungen, Ausgabeform und Parameter, berechnet von der Formprüfung von Brick DNN
BausteinTypEinstellungenAusgabeParameter
featuresInputshape=440
boostingHistGradientBoostingClassifierlearning_rate=0.1 max_iter=200 max_leaf_nodes=31 min_samples_leaf=20 l2_regularization=0 early_stopping=auto class_weight=none random_state=0Modell–
svcSVCkernel=rbf C=1 gamma=scale class_weight=noneModell–
gpGaussianProcessClassifiern_restarts_optimizer=0Modell2 Hyperparameter
voteVotingClassifiervoting=soft weights=NoneKlassen–
Gesamtkeine: scikit-learn passt das Modell an

Training in Brick DNN

Laden Sie eine CSV-Datei mit vier numerischen Merkmalen und einer Klassenspalte hoch oder verwenden Sie einen Datensatz aus dem Bereich Daten. Das Ensemble trainiert wie ein einzelnes klassisches Modell, mit derselben Auswertung (Konfusionsmatrix, Schwellenanalyse bei zwei Klassen), denselben Erklärungen und demselben Download.

Der erzeugte Code

Das ist das scikit-learn-Skript, das der Code-Dialog des Editors aus dem Graphen oben erzeugt (voting_ensemble_classifier.py). Es läuft für sich: python voting_ensemble_classifier.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
"""Voting classifier: generated with Brick DNN.

A scikit-learn ensemble for 4 numeric features: they are standardised, then VotingClassifier
combines 3 models (boosting: HistGradientBoostingClassifier, svc: SVC, gp:
GaussianProcessClassifier) and predicts the class of each row. Soft voting averages their
class probabilities. Platt scaling (5-fold cross-validation) turns the SVM's scores into
class probabilities.

Kernel of gp (the starting point; fitting optimises it):
    ConstantKernel(constant_value=1.0)
    * RBF(length_scale=1.0)

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 sklearn.calibration import CalibratedClassifierCV
from sklearn.ensemble import HistGradientBoostingClassifier, VotingClassifier
from sklearn.gaussian_process import GaussianProcessClassifier
from sklearn.gaussian_process.kernels import RBF, ConstantKernel
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 sklearn.svm import SVC

NUM_FEATURES = 4


def make_model() -> Pipeline:
    """Standardise the features (with the mean and standard deviation of the data
    it is fitted to), then fit VotingClassifier with its 3 models."""
    boosting = HistGradientBoostingClassifier(
        learning_rate=0.1,
        max_iter=200,
        max_leaf_nodes=31,
        max_depth=None,
        min_samples_leaf=20,
        l2_regularization=0.0,
        early_stopping="auto",
        random_state=0,
    )
    svc_svm = SVC(kernel="rbf", C=1.0, gamma="scale")
    # Platt scaling: 5-fold cross-validation turns the scores into probabilities.
    svc = CalibratedClassifierCV(svc_svm, ensemble=False)
    gp_kernel = ConstantKernel(constant_value=1.0) * RBF(length_scale=1.0)
    gp = GaussianProcessClassifier(kernel=gp_kernel)
    model = VotingClassifier(
        estimators=[("boosting", boosting), ("svc", svc), ("gp", gp)],
        voting="soft",
    )
    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_)}")
    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="Voting 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="Voting classifier",
            config={
                "model": "VotingClassifier",
                "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()

Im Editor öffnen

Anleitungen