Examples · PyTorch

Neural network regression on tabular data in PyTorch

A small multi-layer perceptron for tables: eight numeric columns go in, one number comes out, for example a price, a yield or a temperature. The generated script trains it on a CSV file by itself.

Open in the editor See the code

Code
PyTorch
Task
Regression
Input
8
Bricks
7
Trainable parameters
2,817

What the network does

Two hidden Linear layers with 64 and 32 units and ReLU learn the relationship between the eight features and the target. BatchNorm1d after the first hidden layer normalises its outputs over each batch, which makes training less sensitive to the learning rate. The last layer has a single output and no activation, so it can predict any number. The network has 2,817 parameters.

For a regression, Brick DNN standardises the features and the target (mean 0, standard deviation 1, from the training rows) and trains with the mean squared error. The results are also reported as RMSE in the units of the target and as R².

When to use it

  • For regression on tables with a few to a few hundred numeric columns, once the data is clean (no missing values, categories encoded).
  • To compare with gradient boosting, which is often the stronger baseline on tables: see the guide on gradient boosting vs. MLP.
  • For more features, set the Input to their number; for several targets, give the last layer one output per target.

Layers, shapes and parameters

Diagram of the example Tabular regressionInput (8) → Linear (64) → Activation (64) → BatchNorm1d (64) → Linear (32) → Activation (32) → Linear (1)Input8Linear64576 parametersActivation64BatchNorm1d64128 parametersLinear322,080 parametersActivation32Linear133 parameters
The network as it is laid out in the editor. Each box shows the output shape (without the batch dimension) and the number of parameters.
The bricks of Tabular regression: settings, output shape and parameters, computed by Brick DNN's shape inference
BrickTypeSettingsOutputParameters
featuresInputshape=880
fc1Linearout_features=6464576
relu1Activationfunction=relu640
bnBatchNorm1ddefaults64128
fc2Linearout_features=32322,080
relu2Activationfunction=relu320
outLinearout_features=1133
Total2,817

Training it in Brick DNN

Upload a CSV file whose last column is the target and whose other columns are numeric features, or prepare a table in the Data tab (missing values, categories, dates) and press Create training dataset; the dataset then appears in the training panel. The Input follows the number of features of the dataset. Because the network takes one flat vector and returns one, the exported script also contains a training loop: python tabular_regression.py --csv data.csv.

The generated code

This is the PyTorch script that the editor’s code dialog generates from the graph above (tabular_regression.py): an nn.Module with one attribute per layer and a forward method, plus a check that runs a random batch through it, and, because the network takes one flat vector and returns one, a training loop for CSV files (--csv data.csv). It needs nothing but 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()

Open in the editor

Guides