Beispiele · PyTorch

MLP für MNIST in PyTorch

Das klassische erste Netz für handgeschriebene Ziffern: Jedes 28×28-Bild wird zu 784 Zahlen ausgerollt, zwei vollständig verbundene Schichten mit ReLU lernen daraus, und eine letzte Schicht liefert für jede der zehn Ziffern einen Score.

Im Editor öffnen Zum Code

Code
PyTorch
Aufgabe
Klassifikation
Eingabe
784
Bausteine
7
Trainierbare Parameter
235.146

Was das Netz macht

Der Input nimmt einen flachen Vektor aus 784 Werten, einen je Pixel. Linear-Schichten verbinden jeden Wert mit jeder Einheit: Von 784 Eingaben auf 256 Einheiten sind das 784 × 256 Gewichte plus 256 Bias-Werte, also 200.960 Parameter und damit fast alle der 235.146 des Netzes. ReLU nach jeder verdeckten Schicht macht das Netz nichtlinear, und Dropout mit p = 0,2 schaltet beim Training zufällig ein Fünftel der Einheiten der ersten Schicht ab, was Überanpassung bremst.

Die letzte Linear-Schicht gibt zehn rohe Scores (Logits) aus, einen je Ziffer. Ein Softmax am Ende fehlt mit Absicht: Die Kreuzentropie, mit der trainiert wird, erwartet rohe Scores und wendet den Softmax selbst an.

Wann es passt

  • Um zu verstehen, wie sich ein dichtes Netz, seine Parameterzahl und sein Training verhalten, bevor es um Faltungen geht.
  • Als Vergleichsbasis für Bilddaten: Ein CNN wie das kleine CNN für MNIST sollte mit weniger Parametern besser abschneiden, weil es die Nachbarschaft der Pixel nutzt.
  • Für jede Eingabe, die schon ein flacher Merkmalsvektor ist: Form des Inputs und Größe der letzten Schicht anpassen, fertig.

Schichten, Formen und Parameter

Diagramm des Beispiels MLP für MNISTInput (784) → Linear (256) → Activation (256) → Dropout (256) → Linear (128) → Activation (128) → Linear (10)Input784Linear256200.960 ParameterActivation256Dropout256Linear12832.896 ParameterActivation128Linear101.290 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 MLP für MNIST: Einstellungen, Ausgabeform und Parameter, berechnet von der Formprüfung von Brick DNN
BausteinTypEinstellungenAusgabeParameter
inputInputshape=7847840
fc1Linearout_features=256256200.960
relu1Activationfunction=relu2560
drop1Dropoutp=0.22560
fc2Linearout_features=12812832.896
relu2Activationfunction=relu1280
fc3Linearout_features=10101.290
Gesamt235.146

Training in Brick DNN

Klicken Sie auf Trainieren und wählen Sie MNIST: Der eingebaute Datensatz (70.000 Bilder, einmalig auf den Server geladen) passt zu diesem Input, weil MNIST sowohl als 784 flache Werte als auch als 1, 28, 28 angenommen wird. Brick DNN hält 20 % der Trainingsbilder zur Validierung zurück, testet auf den offiziellen 10.000 Testbildern und zeigt nach jeder Epoche Verlust und Genauigkeit. Weil das Netz einen flachen Vektor nimmt und einen ausgibt, enthält das exportierte Skript zusätzlich eine Trainingsschleife für CSV-Dateien.

Der erzeugte Code

Das ist das PyTorch-Skript, das der Code-Dialog des Editors aus dem Graphen oben erzeugt (mlp_mnist.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, 784)
Output: (batch, 10)
Trainable parameters: 235,146

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(784, 256)
        self.relu_1 = nn.ReLU()
        self.dropout_1 = nn.Dropout(p=0.2)
        self.linear_2 = nn.Linear(256, 128)
        self.relu_2 = nn.ReLU()
        self.linear_3 = nn.Linear(128, 10)

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        x = self.linear_1(x)
        x = self.relu_1(x)
        x = self.dropout_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 = 784
NUM_CLASSES = 10  # classification: the target column holds the class index 0..9


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]}.")
    if target.min() < 0 or target.max() >= NUM_CLASSES:
        raise SystemExit(f"Targets must be class indices 0..{NUM_CLASSES - 1}.")
    return header, features, target.long()


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.CrossEntropyLoss()
    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, correct = 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)
                correct += (outputs.argmax(dim=1) == targets).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}  val acc {correct / len(val_set):.1%}"
        )
        summary = {
            "train_loss": train_loss / max(seen, 1),
            "val_loss": val_loss / len(val_set),
            "val_accuracy": correct / len(val_set),
        }
        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_accuracy"] = (outputs.argmax(dim=1) == targets).float().mean().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": "classification",
        "num_classes": NUM_CLASSES,
    }
    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.argmax(dim=1).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": "cross_entropy",
                "val_split": 0.2,
                "test_split": args.test_split,
            },
            project=BRICKDNN_PROJECT,
            dataset=os.path.basename(args.csv),
            task="classification",
            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, 784)
    with torch.no_grad():
        out = model(x)
    print("Output shape:", tuple(out.shape))  # expected (2, 10)


if __name__ == "__main__":
    main()

Im Editor öffnen

Anleitungen