Examples · PyTorch

Multi-input neural network in PyTorch

Two kinds of data in one network: a 28×28 image goes through one branch, ten numbers of metadata through another, and Concat joins what both learned before a last layer predicts a single value, for example a price from a photo and the attributes of an item.

Open in the editor See the code

Code
PyTorch
Task
Regression
Input
1 × 28 × 28 + 10
Bricks
9
Trainable parameters
50,497

What the network does

The image branch flattens the 1 × 28 × 28 image and reduces it to 64 features with a Linear layer and ReLU (50,240 parameters). The metadata branch maps ten values to 16 features (176 parameters). Concat joins the two vectors to one of 80 values, and the head, a Linear layer with one output, predicts the target.

The generated forward method takes two tensors, one per Input layer: x_1 the image, x_2 the metadata. Swap the image branch for convolutions (as in the small CNN) when the images matter more.

When to use it

  • When one example has data of different kinds: a photo and a table row, a signal and the patient’s age, a text and its metadata.
  • To learn how branches and merges work in a graph, and how the code of a network with several inputs looks.
  • Instead of two separate models whose predictions are averaged: the network learns how the inputs interact.

Layers, shapes and parameters

Diagram of the example Multi-input modelInput (1 × 28 × 28) → Flatten (784) → Linear (64) → Activation (64) → Input (10) → Linear (16) → Activation (16) → Concat (80) → Linear (1)Input1 × 28 × 28Flatten784Linear6450,240 parametersActivation64Input10Linear16176 parametersActivation16Concat80Linear181 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 Multi-input model: settings, output shape and parameters, computed by Brick DNN's shape inference
BrickTypeSettingsOutputParameters
imageInputshape=1×28×281 × 28 × 280
flattenFlattendefaults7840
img_fcLinearout_features=646450,240
img_reluActivationfunction=relu640
metaInputshape=10100
meta_fcLinearout_features=1616176
meta_reluActivationfunction=relu160
concatConcatdim=-1800
headLinearout_features=1181
Total50,497

Training it in Brick DNN

Networks with several inputs train on demo data in Brick DNN so far, which checks that the network learns from both inputs. The exported module takes both tensors in forward(x_1, x_2), ready for your own data loader.

The generated code

This is the PyTorch script that the editor’s code dialog generates from the graph above (multi_input.py): an nn.Module with one attribute per layer and a forward method, plus a check that runs a random batch through it. It needs nothing but PyTorch.

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

Input x_1: (batch, 1, 28, 28)
Input x_2: (batch, 10)
Output: (batch, 1)
Trainable parameters: 50,497

Print the model and run it on a random batch:

    python this_file.py
"""

import torch
import torch.nn as nn


class NeuralNetwork(nn.Module):
    def __init__(self) -> None:
        super().__init__()
        self.flatten_1 = nn.Flatten()
        self.linear_1 = nn.Linear(784, 64)
        self.relu_1 = nn.ReLU()
        self.linear_2 = nn.Linear(10, 16)
        self.relu_2 = nn.ReLU()
        self.linear_3 = nn.Linear(80, 1)

    def forward(self, x_1: torch.Tensor, x_2: torch.Tensor) -> torch.Tensor:
        flatten_1 = self.flatten_1(x_1)
        linear_1 = self.linear_1(flatten_1)
        relu_1 = self.relu_1(linear_1)
        linear_2 = self.linear_2(x_2)
        relu_2 = self.relu_2(linear_2)
        concat_1 = torch.cat([relu_1, relu_2], dim=-1)
        linear_3 = self.linear_3(concat_1)
        return linear_3


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


def main() -> None:
    model = NeuralNetwork()
    print(model)
    print(f"Trainable parameters: {count_parameters(model):,}")

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


if __name__ == "__main__":
    main()

Open in the editor