Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Graph models

Use GraphBuilder when a model needs branches, residual connections, multiple inputs, multiple outputs, or shared layers. In a graph model, a node represents a model input or one call to a layer. A node can use tensors from one or more earlier nodes.

Build a graph model

  1. Create a GraphBuilder.
  2. Call input with a Shape for each model input.
  3. Call add with a layer and the IDs of the nodes it reads.
  4. Call build with the output node IDs in the order you want the model to return their tensors.

input and add return a NodeId. Pass node IDs to the builder and tensors to the model. build checks the node connections and layer shapes before it returns a Graph. Every node must contribute to at least one output or serve as an output itself.

Put the sample count on axis zero of each input tensor. For tabular data, use [samples, features].

Train and predict

  1. Call compile with an optimizer and a loss.
  2. Call fit with the input tensors, target tensors, and number of epochs.
  3. Call predict with the input tensors.

Pass one tensor per input in the order of the input calls. Pass one target tensor per output in the order of the node IDs in build. Use the same sample count for all input and target tensors in a fit call. For mean squared error, match each target tensor shape to its prediction tensor shape.

fit returns a History with one loss per epoch. predict returns a Vec<Tensor> in the output order from build. For a single output, use predictions[0] to get its tensor. You can call predict before compile.

Train a model with a residual connection

The input tensor has four samples with eight features each. The first Dense layer produces eight values per sample. The residual connection passes the input tensor directly to Add. Add sums the input tensor and the first Dense layer output element by element. The second Dense layer produces two values per sample from the sum. The example checks that training lowers the loss and that the prediction tensor has shape [4, 2].

The source also lives in guide/examples/nn_graph.rs.

use ndarray::Array;
use rustyml::prelude::neural_network::*;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let x = Array::ones((4, 8)).into_dyn();
    let y = Array::ones((4, 2)).into_dyn();

    let mut builder = GraphBuilder::new();
    let input = builder.input(Shape::known(x.shape()));
    let hidden = builder.add(
        Dense::new(8, Activation::ReLU)?.with_random_state(7),
        &[input],
    );
    let sum = builder.add(Add::new(), &[input, hidden]);
    let output = builder.add(
        Dense::new(2, Activation::Linear)?.with_random_state(8),
        &[sum],
    );
    let mut model = builder.build(&[output])?;

    model.compile(SGD::new(0.01, 0.0, false, 0.0)?, MeanSquaredError::new());
    let initial_loss = model.evaluate(&[&x], &[&y])?;
    let history = model.fit(&[&x], &[&y], 10)?;
    let final_loss = model.evaluate(&[&x], &[&y])?;
    let predictions = model.predict(&[&x])?;

    assert!(final_loss < initial_loss);
    assert_eq!(predictions[0].shape(), &[4, 2]);
    println!("epochs: {}", history.loss().len());
    println!("loss decreased: {}", final_loss < initial_loss);
    println!("prediction shape: {:?}", predictions[0].shape());
    Ok(())
}

The program prints the following output.

epochs: 10
loss decreased: true
prediction shape: [4, 2]

Use multiple inputs, multiple outputs, and shared layers

For multiple inputs, call input once per input. For multiple outputs, pass each output node ID to build in the same slice. Call compile to set the same loss for every output. If the outputs need different losses, use compile_many with an optimizer and one boxed Loss per output. List the losses in the output order.

To share a layer, call layer once to get its LayerId. Call apply with that LayerId for each node that uses the layer. Each apply call returns a distinct NodeId. Those nodes use the same layer weights.

Check errors

If build reports that a node reaches no output, connect the node to an output or remove it. If build reports an incompatible shape at Add, check the shapes of both branches. Add supports broadcasting on axes after the sample axis. Add requires matching sample counts. If fit reports a tensor count error, compare the tensor slices with the model inputs and outputs.