Beispiele · PyTorch + scikit-learn

MLP-Merkmale für Gradient Boosting

Eine Mischung aus Deep Learning und Bäumen: Zwei Linear-Schichten lernen aus acht Spalten 32 neue Merkmale, und ein Gradient-Boosting-Klassifikator wird auf diese Merkmale angepasst statt auf die Rohspalten.

Im Editor öffnen Zum Code

Code
PyTorch + scikit-learn
Aufgabe
Klassifikation
Eingabe
8
Bausteine
5
Trainierbare Parameter
2.656

Was das Netz macht

Das Training hat zwei Phasen in einem Lauf. Zuerst lernen die neuronalen Schichten mit einem vorübergehenden linearen Kopf auf die Zielgröße, wie ein kleines eigenes Netz: 8 → 64 → ReLU → 32, mit 2.656 trainierbaren Parametern. Dann fällt der Kopf weg, die Schichten berechnen die 32 Merkmale jeder Zeile, und der HistGradientBoostingClassifier wird auf die Merkmale der Trainingszeilen angepasst.

Das erzeugte Skript enthält beide Teile: die Schichten als PyTorch-Modul (FeatureExtractor), den Klassifikator als scikit-learn-Pipeline und den Code, der beide Phasen auf einer CSV-Datei trainiert und beides speichert.

Wann es passt

  • Um zu prüfen, ob gelernte Merkmale den Bäumen auf Ihrer Tabelle helfen: Vergleichen Sie auf demselben Split mit dem reinen Gradient Boosting.
  • Mit eingefrorenen Zufallsmerkmalen in den Trainingseinstellungen als schnelle Basis dafür, was das Lernen der Merkmale bringt.
  • Als Muster für Bilder: ein kleines CNN, das mit Flatten oder Linear endet, vor einer SVM oder einem Gradient Boosting.

Schichten, Formen und Parameter

Diagramm des Beispiels MLP-Merkmale für Gradient BoostingInput (8) → Linear (64) → Activation (64) → Linear (32) → HistGradientBoostingClassifier (Klassen)Input8Linear64576 ParameterActivation64Linear322.080 ParameterHistGradientBoostingClassifierKlassen
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 MLP-Merkmale für Gradient Boosting: Einstellungen, Ausgabeform und Parameter, berechnet von der Formprüfung von Brick DNN
BausteinTypEinstellungenAusgabeParameter
featuresInputshape=880
fc1Linearout_features=6464576
relu1Activationfunction=relu640
fc2Linearout_features=32322.080
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=0Klassen–
Gesamt2.656 Parameter + HistGradientBoostingClassifier

Training in Brick DNN

Setzen Sie den Input auf die Zahl der Merkmalsspalten Ihrer Daten und trainieren Sie dann auf einer CSV-Datei, einem Datensatz aus dem Bereich Daten oder auf Demodaten. Der Trainingsbereich zeigt für die erste Phase die Einstellungen eines Netzes (Epochen, Lernrate …); die Kurven gehören zum Lernen der Merkmale, die Auswertung zum angepassten Klassifikator. Der Download ist eine ZIP-Datei mit beiden Teilen und dem Skript.

Der erzeugte Code

Das ist das Skript, das der Code-Dialog des Editors aus dem Graphen oben erzeugt (hybrid_mlp_gradient_boosting.py): die neuronalen Schichten als PyTorch-Modul, das klassische Modell als scikit-learn-Pipeline und der Code, der beide Phasen auf einer CSV-Datei trainiert.

# Built with Brick DNN: https://brickdnn.com, https://github.com/alexanderKuehling/brick-dnn
"""Gradient boosting classification on learned features: generated with Brick DNN.

Neural layers (FeatureExtractor) turn 8 numeric features into 32 learned features;
HistGradientBoostingClassifier is fitted on them and predicts the class of each row. The
training has two phases: first the neural layers learn with a temporary linear head on the
target (with --frozen they keep their random initial weights), then the head is dropped and
the classical model is fitted on the features of the training rows.

Print the models and fit them to random data:

    python this_file.py

Train on a CSV file (every column but the last is a feature, the last column is
the target); this writes features.pt (the neural layers) and model.joblib (the
classical model). Then predict new rows with both:

    python this_file.py --csv data.csv --epochs 20
    python this_file.py --predict new_data.csv

Log the training to Brick DNN, to see its curves 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 --epochs 20

It sends the losses of every epoch of the features and the validation accuracy of the
temporary head, the settings and the classical model's hyperparameters, the name of the
CSV file, and the classical model's accuracy, balanced accuracy, F1 and (two classes)
ROC AUC on the validation rows and the time its 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
import torch
import torch.nn as nn
from sklearn.ensemble import HistGradientBoostingClassifier
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 torch.utils.data import DataLoader, TensorDataset

NUM_FEATURES = 8  # input columns of the CSV file
NUM_LEARNED = 32  # features the neural layers learn


class FeatureExtractor(nn.Module):
    def __init__(self) -> None:
        super().__init__()
        self.linear_1 = nn.Linear(8, 64)
        self.relu_1 = nn.ReLU()
        self.learned_features = nn.Linear(64, 32)

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        x = self.linear_1(x)
        x = self.relu_1(x)
        x = self.learned_features(x)
        return x


def make_model() -> Pipeline:
    """Standardise the features (with the mean and standard deviation of the data
    it is fitted to), then fit HistGradientBoostingClassifier."""
    model = 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,
    )
    return Pipeline([("scale", StandardScaler()), ("model", model)])


# --------------------------------------------------------------------------- #
# The two phases: learning the features, then fitting the classical model
# --------------------------------------------------------------------------- #


def extract(extractor: nn.Module, inputs: np.ndarray) -> np.ndarray:
    """The learned features of every row (or sample): the output of the neural layers,
    computed in batches without gradients."""
    extractor.eval()
    x = torch.as_tensor(inputs, dtype=torch.float32)
    with torch.no_grad():
        parts = [extractor(x[i : i + 1024]) for i in range(0, len(x), 1024)]
    if not parts:
        return np.empty((0, NUM_LEARNED))
    return torch.cat(parts).double().numpy()


# --------------------------------------------------------------------------- #
# 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 split_rows(n: int, seed: int) -> tuple[np.ndarray, np.ndarray]:
    """A random 80 % of the rows for training, the rest for validation (fixed by ``seed``).
    Both phases use the same split."""
    if n < 4:
        raise SystemExit("The CSV file needs at least 4 rows (training + validation).")
    order = np.random.default_rng(seed).permutation(n)
    n_val = max(1, n // 5)
    return order[n_val:], order[:n_val]


def standardise(features: np.ndarray, train_rows: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
    """The mean and standard deviation of the training rows. New rows are standardised with
    them as well, before the neural layers."""
    mean = features[train_rows].mean(axis=0)
    std = features[train_rows].std(axis=0)
    std[std < 1e-8] = 1.0  # constant columns are left as they are
    return mean, std


def learn_features(
    extractor: FeatureExtractor,
    features: np.ndarray,
    target: np.ndarray,
    train_rows: np.ndarray,
    val_rows: np.ndarray,
    epochs: int,
    batch_size: int,
    lr: float,
    seed: int,
    run: BrickDNNRun | None = None,
) -> None:
    """Phase 1: train the neural layers with a temporary linear head on the target, then
    drop the head. ``features`` are standardised."""
    # Classification: one output per class and the cross-entropy loss.
    classes, labels = np.unique(target, return_inverse=True)
    y = torch.as_tensor(labels, dtype=torch.long)
    head = nn.Linear(NUM_LEARNED, len(classes))
    loss_fn = nn.CrossEntropyLoss()
    x = torch.as_tensor(features, dtype=torch.float32)
    train, val = torch.as_tensor(train_rows), torch.as_tensor(val_rows)
    network = nn.Sequential(extractor, head)
    loader = DataLoader(
        TensorDataset(x[train], y[train]),
        batch_size=batch_size,
        shuffle=True,
        drop_last=len(train) > batch_size,
        generator=torch.Generator().manual_seed(seed),
    )
    optimizer = torch.optim.Adam(network.parameters(), lr=lr)
    print(f"Learning the features on {len(train)} rows, {len(val)} for validation")
    for epoch in range(1, epochs + 1):
        network.train()
        total, seen = 0.0, 0
        for inputs, targets in loader:
            optimizer.zero_grad()
            loss = loss_fn(network(inputs), targets)
            loss.backward()
            optimizer.step()
            total += loss.item() * len(inputs)
            seen += len(inputs)
        network.eval()
        with torch.no_grad():
            outputs = network(x[val])
            val_loss = loss_fn(outputs, y[val]).item()
        print(
            f"Epoch {epoch:3d}/{epochs}  train loss {total / max(seen, 1):.4f}"
            f"  val loss {val_loss:.4f}"
        )
        if run is not None:
            run.log(
                epoch=epoch,
                train_loss=total / max(seen, 1),
                val_loss=val_loss,
                val_accuracy=(outputs.argmax(dim=1) == y[val]).float().mean(),
            )


def fit(
    model: Pipeline,
    features: np.ndarray,
    target: np.ndarray,
    train_rows: np.ndarray,
    val_rows: np.ndarray,
    run: BrickDNNRun | None = None,
) -> None:
    """Phase 2: fit the classical model on the learned features of the training rows and
    validate it on the other rows. Its StandardScaler learns from the training rows only."""
    print(f"Fitting on the {features.shape[1]} learned features of {len(train_rows)} rows")
    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%}")
    boosting = model.named_steps["model"]
    # Early stopping may end before max_iter.
    print(f"Boosting iterations: {boosting.n_iter_} of at most {boosting.max_iter}")
    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(
    extractor: FeatureExtractor,
    model: Pipeline,
    weights_path: str,
    model_path: str,
    header: list[str],
    mean: np.ndarray,
    std: np.ndarray,
) -> None:
    """Save the neural layers with the preprocessing of the input columns (PyTorch) and the
    fitted classical model (joblib, a pickle: only load files you trust)."""
    preprocessing = {
        "columns": header[:-1],  # the input columns by name (empty: no header line)
        "target": header[-1] if header else "target",
        "mean": mean.tolist(),  # every input column is standardised: (value - mean) / std
        "std": std.tolist(),
    }
    torch.save({"state_dict": extractor.state_dict(), "preprocessing": preprocessing}, weights_path)
    bundle = {
        "format": "brickdnn-sklearn-1",
        "model": model,
        "columns": [f"feature_{i + 1}" for i in range(NUM_LEARNED)],  # the learned features
        "target": preprocessing["target"],
        "task": "classification",
        # one name per column of model.predict_proba()
        "class_names": [str(name) for name in model.classes_],
        "hybrid": {"features": NUM_LEARNED, "input_columns": preprocessing["columns"]},
    }
    joblib.dump(bundle, model_path)
    print(f"Saved the neural layers to {weights_path} and the classical model to {model_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(weights_path: str, model_path: str, csv_path: str) -> None:
    """Print a prediction for every row of a CSV file: standardise the input columns like
    the training rows, compute the learned features, then let the classical model predict.

    If both the saved preprocessing and the file have a header line, the input columns are
    found by their names; otherwise they have to come first. Other columns are ignored.
    """
    checkpoint = torch.load(weights_path, map_location="cpu", weights_only=True)
    extractor = FeatureExtractor()
    extractor.load_state_dict(checkpoint["state_dict"])
    preprocessing = checkpoint["preprocessing"]
    bundle = joblib.load(model_path)  # a pickle: only load files you trust
    model, columns = bundle["model"], preprocessing["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} input columns.")
    inputs = numbers(rows, csv_path)
    mean, std = np.asarray(preprocessing["mean"]), np.asarray(preprocessing["std"])
    features = extract(extractor, (inputs - mean) / std)
    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(extractor: FeatureExtractor, model: Pipeline) -> None:
    """Compute the features of 40 random samples with the untrained neural layers, fit the
    model on them and predict two (shows that both parts work together)."""
    rng = np.random.default_rng(0)
    learned = extract(extractor, rng.normal(size=(40, NUM_FEATURES)))
    target = np.where(learned[:, 0] + learned[:, -1] > 0, "yes", "no")
    model.fit(learned, target)
    print("Predictions for 2 random samples:", model.predict(learned[: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="Gradient boosting classification on learned features, generated with Brick DNN"
    )
    parser.add_argument("--csv", help="train on this CSV file (last column = target)")
    parser.add_argument("--predict", metavar="CSV", help="predict the rows of this file")
    parser.add_argument("--epochs", type=int, default=10)
    parser.add_argument("--batch-size", type=int, default=32)
    parser.add_argument("--lr", type=float, default=1e-3, help="learning rate")
    parser.add_argument(
        "--frozen",
        action="store_true",
        help="keep the random initial weights of the neural layers (no training)",
    )
    parser.add_argument("--seed", type=int, default=0, help="for a repeatable run")
    parser.add_argument(
        "--weights", default="features.pt", help="the neural layers (--csv writes it)"
    )
    parser.add_argument(
        "--save", default="model.joblib", help="the classical model (--csv writes it)"
    )
    args = parser.parse_args()
    torch.manual_seed(args.seed)  # the same initial weights for the same seed

    if args.predict:
        predict(args.weights, args.save, args.predict)
        return
    extractor = FeatureExtractor()
    model = make_model()
    print(extractor)
    print(model)
    if args.csv:
        header, features, target = load_csv(args.csv)
        train_rows, val_rows = split_rows(len(features), args.seed)
        mean, std = standardise(features, train_rows)
        features = (features - mean) / std
        # Logged to Brick DNN only with the environment variable BRICKDNN_TOKEN.
        with BrickDNNRun.start(
            name="Gradient boosting classification on learned features",
            config={
                "epochs": 0 if args.frozen else args.epochs,
                "batch_size": args.batch_size,
                "learning_rate": args.lr,
                "optimizer": "adam",
                "seed": args.seed,
                "loss": "cross_entropy",
                "val_split": 0.2,
                "feature_training": "frozen" if args.frozen else "pretrain",
                "learned_features": NUM_LEARNED,
                "model": "HistGradientBoostingClassifier",
                "params": model_settings(model),
            },
            project=BRICKDNN_PROJECT,
            dataset=os.path.basename(args.csv),
            task="classification",
            epochs=None if args.frozen else args.epochs,
            url=BRICKDNN_URL,
        ) as run:
            if args.frozen:
                print("Frozen random features: the neural layers are not trained.")
            else:
                learn_features(
                    extractor,
                    features,
                    target,
                    train_rows,
                    val_rows,
                    args.epochs,
                    args.batch_size,
                    args.lr,
                    args.seed,
                    run,
                )
            learned = extract(extractor, features)
            fit(model, learned, target, train_rows, val_rows, run)
        save_model(extractor, model, args.weights, args.save, header, mean, std)
        return
    demo(extractor, model)


if __name__ == "__main__":
    main()

Im Editor öffnen

Anleitungen