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
| Brick | Type | Settings | Output | Parameters |
|---|---|---|---|---|
image | Input | shape=1×28×28 | 1 × 28 × 28 | 0 |
flatten | Flatten | defaults | 784 | 0 |
img_fc | Linear | out_features=64 | 64 | 50,240 |
img_relu | Activation | function=relu | 64 | 0 |
meta | Input | shape=10 | 10 | 0 |
meta_fc | Linear | out_features=16 | 16 | 176 |
meta_relu | Activation | function=relu | 16 | 0 |
concat | Concat | dim=-1 | 80 | 0 |
head | Linear | out_features=1 | 1 | 81 |
| Total | 50,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()