Beispiele · PyTorch

Regression mit neuronalem Netz auf Tabellendaten

Ein kleines mehrschichtiges Perzeptron für Tabellen: Acht numerische Spalten gehen hinein, eine Zahl kommt heraus, etwa ein Preis, ein Ertrag oder eine Temperatur. Das erzeugte Skript trainiert es selbständig auf einer CSV-Datei.

Im Editor öffnen Zum Code

Code
PyTorch
Aufgabe
Regression
Eingabe
8
Bausteine
7
Trainierbare Parameter
2.817

Was das Netz macht

Zwei verdeckte Linear-Schichten mit 64 und 32 Einheiten und ReLU lernen den Zusammenhang zwischen den acht Merkmalen und der Zielgröße. BatchNorm1d nach der ersten verdeckten Schicht normalisiert deren Ausgaben über jeden Batch, was das Training weniger empfindlich für die Lernrate macht. Die letzte Schicht hat eine einzige Ausgabe ohne Aktivierung und kann so jede Zahl vorhersagen. Das Netz hat 2.817 Parameter.

Bei einer Regression standardisiert Brick DNN Merkmale und Zielgröße (Mittelwert 0, Standardabweichung 1, aus den Trainingszeilen) und trainiert mit der mittleren quadratischen Abweichung. Die Ergebnisse erscheinen zusätzlich als RMSE in der Einheit der Zielgröße und als R².

Wann es passt

  • Für Regression auf Tabellen mit wenigen bis einigen hundert numerischen Spalten, sobald die Daten sauber sind (keine fehlenden Werte, Kategorien kodiert).
  • Zum Vergleich mit Gradient Boosting, das auf Tabellen oft die stärkere Basis ist: siehe die Anleitung Gradient Boosting oder MLP.
  • Bei mehr Merkmalen setzen Sie den Input auf deren Anzahl, bei mehreren Zielgrößen bekommt die letzte Schicht eine Ausgabe je Zielgröße.

Schichten, Formen und Parameter

Diagramm des Beispiels Regression auf TabellendatenInput (8) → Linear (64) → Activation (64) → BatchNorm1d (64) → Linear (32) → Activation (32) → Linear (1)Input8Linear64576 ParameterActivation64BatchNorm1d64128 ParameterLinear322.080 ParameterActivation32Linear133 Parameter
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 Regression auf Tabellendaten: Einstellungen, Ausgabeform und Parameter, berechnet von der Formprüfung von Brick DNN
BausteinTypEinstellungenAusgabeParameter
featuresInputshape=880
fc1Linearout_features=6464576
relu1Activationfunction=relu640
bnBatchNorm1dStandardwerte64128
fc2Linearout_features=32322.080
relu2Activationfunction=relu320
outLinearout_features=1133
Gesamt2.817

Training in Brick DNN

Laden Sie eine CSV-Datei hoch, deren letzte Spalte die Zielgröße ist und deren übrige Spalten numerische Merkmale sind, oder bereiten Sie eine Tabelle im Bereich Daten auf (fehlende Werte, Kategorien, Datumsangaben) und klicken Sie auf Trainingsdatensatz erstellen; der Datensatz erscheint dann im Trainingsbereich. Der Input folgt der Zahl der Merkmale des Datensatzes. Weil das Netz einen flachen Vektor nimmt und einen ausgibt, enthält das exportierte Skript eine Trainingsschleife: python tabular_regression.py --csv daten.csv.

Der erzeugte Code

Das ist das PyTorch-Skript, das der Code-Dialog des Editors aus dem Graphen oben erzeugt (tabular_regression.py): ein nn.Module mit einem Attribut je Schicht und einer forward-Methode, dazu ein Test, der einen zufälligen Batch durch das Netz schickt, und, weil das Netz einen flachen Vektor nimmt und einen ausgibt, eine Trainingsschleife für CSV-Dateien (--csv daten.csv). Es braucht nur PyTorch.

# Built with Brick DNN: https://brickdnn.com, https://github.com/alexanderKuehling/brick-dnn
"""NeuralNetwork: generated with Brick DNN.

Input: (batch, 8)
Output: (batch, 1)
Trainable parameters: 2,817

Print the model and run it on a random batch:

    python this_file.py

Train it on 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 --epochs 20
    python this_file.py --predict new_data.csv

--test-split 0.2 holds out a fifth of the rows and measures the model on them
once at the end.

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 loss and the metrics of every epoch, the settings, the name of the CSV file
and the test results 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 torch
import torch.nn as nn
from torch.utils.data import DataLoader, TensorDataset


class NeuralNetwork(nn.Module):
    def __init__(self) -> None:
        super().__init__()
        self.linear_1 = nn.Linear(8, 64)
        self.relu_1 = nn.ReLU()
        self.batchnorm1d_1 = nn.BatchNorm1d(64)
        self.linear_2 = nn.Linear(64, 32)
        self.relu_2 = nn.ReLU()
        self.linear_3 = nn.Linear(32, 1)

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        x = self.linear_1(x)
        x = self.relu_1(x)
        x = self.batchnorm1d_1(x)
        x = self.linear_2(x)
        x = self.relu_2(x)
        x = self.linear_3(x)
        return x


def count_parameters(model: nn.Module) -> int:
    return sum(p.numel() for p in model.parameters() if p.requires_grad)


# --------------------------------------------------------------------------- #
# Training on a CSV file, and predictions for new rows
# --------------------------------------------------------------------------- #

NUM_FEATURES = 8
# regression: the model has a single output, the target column is a number


def read_csv(path: str) -> tuple[list[str], torch.Tensor]:
    """Read a CSV file of numbers: the column names of its header line (an empty list if it
    has none) and the values."""
    with open(path, newline="") as f:
        rows = [row for row in csv.reader(f) if row]
    header: list[str] = []
    if rows:
        try:
            [float(value) for value in rows[0]]
        except ValueError:
            header, rows = [name.strip() for name in rows[0]], rows[1:]
    if not rows:
        raise SystemExit(f"{path} contains no data rows.")
    values = [[float(value) for value in row] for row in rows]
    return header, torch.tensor(values, dtype=torch.float32)


def load_csv(path: str) -> tuple[list[str], torch.Tensor, torch.Tensor]:
    """Training data: every column but the last is a feature, the last one is the target."""
    header, data = read_csv(path)
    features, target = data[:, :-1], data[:, -1]
    if features.shape[1] != NUM_FEATURES:
        raise SystemExit(f"Expected {NUM_FEATURES} feature columns, found {features.shape[1]}.")
    return header, features, target.unsqueeze(1)


def train(
    model: nn.Module,
    features: torch.Tensor,
    target: torch.Tensor,
    epochs: int,
    batch_size: int,
    lr: float,
    seed: int,
    test_split: float = 0.0,
    run: BrickDNNRun | None = None,
) -> tuple[torch.Tensor, torch.Tensor]:
    """Train on a random 80 % of the rows and validate on the rest (the split depends only
    on ``seed``). With ``test_split``, that share of the rows is held out as a test set and
    measured once at the end.

    Returns the mean and standard deviation that standardise the features. They come from
    the training rows only, and new data has to be standardised with them as well.
    """
    if len(features) < 4:
        raise SystemExit("The CSV file needs at least 4 rows (training + validation).")
    generator = torch.Generator().manual_seed(seed)
    order = torch.randperm(len(features), generator=generator)
    n_val = max(1, len(features) // 5)
    n_test = int(len(features) * test_split)
    if not 0 <= test_split < 1 or len(features) - n_val - n_test < 2:
        raise SystemExit("The test split leaves too few rows for training.")
    val_rows, test_rows = order[:n_val], order[n_val : n_val + n_test]
    train_rows = order[n_val + n_test :]

    mean = features[train_rows].mean(dim=0)
    std = features[train_rows].std(dim=0)
    std[std < 1e-8] = 1.0  # constant columns are left as they are
    features = (features - mean) / std

    train_set = TensorDataset(features[train_rows], target[train_rows])
    val_set = TensorDataset(features[val_rows], target[val_rows])
    train_loader = DataLoader(
        train_set,
        batch_size=batch_size,
        shuffle=True,
        drop_last=len(train_set) > batch_size,
        generator=generator,
    )
    val_loader = DataLoader(val_set, batch_size=batch_size)

    if torch.cuda.is_available():
        device = "cuda"
    elif torch.backends.mps.is_available():
        device = "mps"
    else:
        device = "cpu"
    print(f"Training on {device}: {len(train_set)} rows, {len(val_set)} for validation")
    if n_test:
        print(f"{n_test} rows are held out for the test")
    model.to(device)

    loss_fn = nn.MSELoss()
    optimizer = torch.optim.Adam(model.parameters(), lr=lr)

    summary: dict[str, float] = {}
    for epoch in range(1, epochs + 1):
        model.train()
        train_loss, seen = 0.0, 0
        for inputs, targets in train_loader:
            inputs, targets = inputs.to(device), targets.to(device)
            optimizer.zero_grad()
            loss = loss_fn(model(inputs), targets)
            loss.backward()
            optimizer.step()
            train_loss += loss.item() * len(inputs)
            seen += len(inputs)

        model.eval()
        val_loss, squared = 0.0, 0.0
        with torch.no_grad():
            for inputs, targets in val_loader:
                inputs, targets = inputs.to(device), targets.to(device)
                outputs = model(inputs)
                val_loss += loss_fn(outputs, targets).item() * len(inputs)
                squared += ((outputs - targets) ** 2).sum().item()
        print(
            f"Epoch {epoch:3d}/{epochs}  train loss {train_loss / max(seen, 1):.4f}"
            f"  val loss {val_loss / len(val_set):.4f}"
        )
        summary = {
            "train_loss": train_loss / max(seen, 1),
            "val_loss": val_loss / len(val_set),
            "val_rmse": (squared / len(val_set)) ** 0.5,
        }
        if run is not None:
            run.log(epoch=epoch, **summary)

    if n_test:
        model.eval()
        with torch.no_grad():
            inputs, targets = features[test_rows].to(device), target[test_rows].to(device)
            outputs = model(inputs)
            summary["test_loss"] = loss_fn(outputs, targets).item()
            summary["test_rmse"] = ((outputs - targets) ** 2).mean().sqrt().item()
        tested = [f"{key[5:]} {value:.4f}" for key, value in summary.items() if "test" in key]
        print("Test:", ", ".join(tested))
    if run is not None:
        run.finish(summary=summary)
    model.cpu()
    return mean, std


def save_model(
    model: nn.Module, path: str, header: list[str], mean: torch.Tensor, std: torch.Tensor
) -> None:
    """Save the weights together with what predict() needs to prepare new rows."""
    preprocessing = {
        "columns": header[:-1],  # the feature columns by name (empty: no header line)
        "target": header[-1] if header else "target",
        "mean": mean.tolist(),  # every feature is standardised: (value - mean) / std
        "std": std.tolist(),
        "task": "regression",
    }
    torch.save({"state_dict": model.state_dict(), "preprocessing": preprocessing}, path)
    print(f"Saved the weights and the preprocessing to {path}")


def predict(model: nn.Module, path: str, csv_path: str) -> None:
    """Print a prediction for every row of a CSV file, prepared like the training data.

    If both files 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.
    """
    checkpoint = torch.load(path, map_location="cpu", weights_only=True)
    model.load_state_dict(checkpoint["state_dict"])
    model.eval()
    preprocessing = checkpoint["preprocessing"]
    columns = preprocessing["columns"]
    header, data = 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)}.")
        features = data[:, [header.index(name) for name in columns]]
    elif data.shape[1] >= NUM_FEATURES:
        features = data[:, :NUM_FEATURES]
    else:
        raise SystemExit(f"Expected {NUM_FEATURES} feature columns, found {data.shape[1]}.")
    mean = torch.tensor(preprocessing["mean"])
    std = torch.tensor(preprocessing["std"])
    with torch.no_grad():
        outputs = model((features - mean) / std)
    print(preprocessing["target"])
    for value in outputs[:, 0].tolist():
        print(value)


# --------------------------------------------------------------------------- #
# 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="NeuralNetwork 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("--seed", type=int, default=0, help="for a repeatable run")
    parser.add_argument(
        "--test-split", type=float, default=0.0, help="share of the rows held out as a test set"
    )
    parser.add_argument(
        "--save", default="model.pt", help="the trained model (--csv writes it, --predict reads it)"
    )
    args = parser.parse_args()
    torch.manual_seed(args.seed)  # the same initial weights for the same seed

    model = NeuralNetwork()
    if args.predict:
        predict(model, args.save, args.predict)
        return
    print(model)
    print(f"Trainable parameters: {count_parameters(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="NeuralNetwork",
            config={
                "epochs": args.epochs,
                "batch_size": args.batch_size,
                "learning_rate": args.lr,
                "optimizer": "adam",
                "seed": args.seed,
                "loss": "mse",
                "val_split": 0.2,
                "test_split": args.test_split,
            },
            project=BRICKDNN_PROJECT,
            dataset=os.path.basename(args.csv),
            task="regression",
            epochs=args.epochs,
            url=BRICKDNN_URL,
        ) as run:
            mean, std = train(
                model,
                features,
                target,
                args.epochs,
                args.batch_size,
                args.lr,
                args.seed,
                args.test_split,
                run,
            )
        save_model(model, args.save, header, mean, std)
        return

    # Check the model with a random batch of 2 samples.
    model.eval()
    x = torch.randn(2, 8)
    with torch.no_grad():
        out = model(x)
    print("Output shape:", tuple(out.shape))  # expected (2, 1)


if __name__ == "__main__":
    main()

Im Editor öffnen

Anleitungen