Layer Utils#
Utility functions and classes for working with layers.
Note: This section is mainly useful for advanced customization of visualkeras, debugging renderer behavior, or contributing to the visualkeras codebase. Most users can rely on the higher-level renderer APIs instead.
API Reference#
- class visualkeras.layer_utils.SpacingDummyLayer(spacing=50)[source]#
Bases:
LayerPlaceholder layer used only to create visual gaps in a diagram.
This layer has no semantic effect on the underlying model architecture. It exists so that renderers can detect intentional spacing between model sections without requiring a separate external layout description.
- Parameters:
spacing (int, default=50) –
Requested amount of visual separation associated with this layer.
Renderers may interpret this as extra layout space between neighboring blocks. The value exists to support intentional grouping in diagrams and is not used during model training or inference.
- visualkeras.layer_utils.get_layers(model)[source]#
Return the sequence of layers tracked by a Keras model.
This helper normalizes the internal layer container differences between older and newer Keras or TensorFlow builds. It is used throughout the renderers whenever they need a stable ordered list of layers.
- Parameters:
model (Any) – Keras or TensorFlow model instance.
- Returns:
Sequence of layers tracked by the model.
- Return type:
- Raises:
RuntimeError – If the model does not expose a supported internal layer container.
- visualkeras.layer_utils.get_incoming_layers(layer)[source]#
Yield the layers that feed directly into
layer.This helper abstracts over the legacy and modern Keras node APIs so the rest of the package can treat inbound edges uniformly.
- Parameters:
layer (Any) – Keras or TensorFlow layer instance whose parents should be discovered.
- Yields:
Any – Layer objects that connect directly into
layer.
- visualkeras.layer_utils.get_outgoing_layers(layer)[source]#
Yield the layers that receive output directly from
layer.- Parameters:
layer (Any) – Keras or TensorFlow layer instance whose children should be discovered.
- Yields:
Any – Layer objects that consume the output of
layer.
- visualkeras.layer_utils.model_to_adj_matrix(model)[source]#
Build an adjacency matrix describing model connectivity.
The returned matrix records directed layer-to-layer edges using the model’s internal graph representation. This is a foundational helper for renderers that need to reason about graph structure, hierarchy levels, or terminal nodes.
- Parameters:
model (Any) – Keras or TensorFlow model instance.
- Returns:
Two-item tuple
(id_to_num_mapping, adj_matrix)whereid_to_num_mappingmapsid(layer)to a row or column index andadj_matrixis a square NumPy array counting directed edges.- Return type:
- visualkeras.layer_utils.find_layer_by_id(model, _id)[source]#
Return a model layer by its Python object id.
- Parameters:
model (Any) – Keras or TensorFlow model instance to search.
_id (int) – Result of calling
id(layer)for the target layer.
- Returns:
Matching layer instance, or
Noneif no layer has the requested id.- Return type:
Any or None
- visualkeras.layer_utils.find_layer_by_name(model, name)[source]#
Return a model layer by its
nameattribute.- Parameters:
model (Any) – Keras or TensorFlow model instance to search.
name (str) – Layer name to match.
- Returns:
Matching layer instance, or
Noneif no layer has the requested name.- Return type:
Any or None
- visualkeras.layer_utils.find_input_layers(model, id_to_num_mapping=None, adj_matrix=None)[source]#
Yield graph input layers for a model.
Inputs are identified as layers with zero in-degree in the model adjacency matrix. Precomputed graph structures may be supplied when this helper is used inside a larger connectivity pipeline.
- Parameters:
model (Any) – Model whose input layers should be discovered.
id_to_num_mapping (dict, optional) – Precomputed mapping from
id(layer)to adjacency-matrix index.adj_matrix (numpy.ndarray, optional) – Precomputed adjacency matrix.
- Yields:
Any – Layers that behave as graph inputs.
- visualkeras.layer_utils.find_output_layers(model)[source]#
Yield graph output layers for a model.
This helper supports both older and newer Keras APIs by using
model.output_nameswhen available and falling back to output tensor provenance when necessary.- Parameters:
model (Any) – Model whose output-producing layers should be discovered.
- Yields:
Any – Layers that produce model outputs.
- visualkeras.layer_utils.model_to_hierarchy_lists(model, id_to_num_mapping=None, adj_matrix=None)[source]#
Group model layers into topological hierarchy levels.
Starting from graph inputs, this helper collects each successive wave of layers whose inbound dependencies have already been satisfied. The result is useful for renderers that organize diagrams by rank or stage.
- Parameters:
model (Any) – Model whose layers should be grouped.
id_to_num_mapping (dict, optional) – Precomputed mapping from
id(layer)to adjacency-matrix index.adj_matrix (numpy.ndarray, optional) – Precomputed adjacency matrix.
- Returns:
Layers grouped by hierarchy level from inputs to outputs.
- Return type:
- visualkeras.layer_utils.augment_output_layers(model, output_layers, id_to_num_mapping, adj_matrix)[source]#
Append synthetic output layers to an existing adjacency graph.
Some renderers benefit from explicit terminal nodes even when the original model ends on real layers. This helper extends both the adjacency matrix and the id mapping so those synthetic sinks can be treated like ordinary nodes.
- Parameters:
model (Any) – Source model whose output layers should be connected to synthetic sinks.
output_layers (sequence) – Synthetic output-layer objects to append.
id_to_num_mapping (dict) – Existing mapping from
id(layer)to adjacency-matrix index.adj_matrix (numpy.ndarray) – Existing adjacency matrix to extend.
- Returns:
Updated
(id_to_num_mapping, adj_matrix)pair.- Return type:
- visualkeras.layer_utils.is_internal_input(layer)[source]#
Return whether
layershould be treated as an internal input layer.Keras and TensorFlow have exposed input-layer classes from several import paths over time. This helper centralizes the compatibility checks so the renderers can treat all of them consistently.
- Parameters:
layer (Any) – Layer instance to classify.
- Returns:
Truewhen the layer behaves like an internal input node.- Return type:
- visualkeras.layer_utils.extract_primary_shape(layer_output_shape, layer_name=None)[source]#
Return the primary output shape for visualization.
Some layers expose multiple output shapes, but most renderers need a single representative tensor shape. This helper selects the first output as the primary one and emits a warning when information is being discarded.
- Parameters:
- Returns:
Single shape tuple to use for visualization.
- Return type:
- Raises:
RuntimeError – If the shape uses an unsupported container format.
- visualkeras.layer_utils.calculate_layer_dimensions(shape, scale_z, scale_xy, max_z, max_xy, min_z, min_xy, one_dim_orientation='y', sizing_mode='accurate', dimension_caps=None, relative_base_size=20)[source]#
Calculate rendered box dimensions for a layer shape.
This helper converts a tensor shape into the pixel dimensions used by layered and functional renderers. The exact conversion depends on the selected sizing mode and on the scaling, minimum, and maximum bounds that accompany it.
- Parameters:
shape (tuple) – Tensor shape to convert. The batch dimension is ignored when present.
scale_z (float) – Multiplier applied to depth-like dimensions before clamping.
scale_xy (float) – Multiplier applied to width and height dimensions before clamping.
max_z (int) – Upper bound for the rendered depth dimension.
max_xy (int) – Upper bound for rendered width and height.
min_z (int) – Lower bound for the rendered depth dimension.
min_xy (int) – Lower bound for rendered width and height.
one_dim_orientation ({'y', 'z'}, default='y') – Axis used when rendering one-dimensional layers.
sizing_mode ({'accurate', 'capped', 'balanced', 'logarithmic', 'relative'}, default='accurate') – Strategy used to transform tensor dimensions into pixels.
dimension_caps (mapping, optional) – Optional per-dimension caps used by sizing modes that support them.
relative_base_size (int, default=20) – Base pixel size used by
relativemode.
- Returns:
Three-item tuple
(x, y, z)describing the rendered dimensions.- Return type:
Notes
See the layer-utils API page for a fuller discussion of the sizing modes and their tradeoffs.
Full documentation: https://visualkeras.readthedocs.io/en/latest/api/layer_utils_details.html
SpacingDummyLayer#
Special layer for adding visual spacing in sequential models.
Purpose#
SpacingDummyLayer is a no-op layer that serves purely for visualization purposes. It creates visual breaks between sections of your model, helping organize the diagram.
Basic Usage#
import tensorflow as tf
from tensorflow import keras
import visualkeras
model = keras.Sequential([
keras.layers.Conv2D(32, (3, 3)),
keras.layers.Conv2D(32, (3, 3)),
visualkeras.SpacingDummyLayer(), # Visual separator
keras.layers.Conv2D(64, (3, 3)),
keras.layers.Conv2D(64, (3, 3)),
])
When visualizing, typically ignore these layers to keep the diagram clean:
visualkeras.layered_view(
model,
type_ignore=[visualkeras.SpacingDummyLayer]
).show()
Custom Spacing#
Control the size of the spacing:
visualkeras.SpacingDummyLayer(spacing=100) # Custom spacing size
The spacing parameter controls how much space is added. Default is 50 pixels.
When to Use#
Use SpacingDummyLayer to:
Separate feature extraction from classification sections
Group convolutional blocks visually
Organize encoder and decoder sections
Divide architectural stages
It has no effect on model training or inference – it’s purely for visualization.
Why Useful#
In large complex models, visual organization helps readers understand the architecture at a glance. Compare:
# Without spacing - hard to see structure
model = Sequential([
Conv2D(...), # Block 1
Conv2D(...),
MaxPooling2D(...),
Conv2D(...), # Block 2
Conv2D(...),
MaxPooling2D(...),
Flatten(),
Dense(...), # Classification
Dense(...)
])
# With spacing - clear structure
model = Sequential([
Conv2D(...),
Conv2D(...),
MaxPooling2D(...),
SpacingDummyLayer(), # Break between blocks
Conv2D(...),
Conv2D(...),
MaxPooling2D(...),
SpacingDummyLayer(), # Break before classification
Flatten(),
Dense(...),
Dense(...)
])
Real-World Example#
VGG-style network with clear section breaks:
model = keras.Sequential([
# Block 1
Conv2D(64, (3, 3), padding='same'),
Conv2D(64, (3, 3), padding='same'),
MaxPooling2D((2, 2)),
SpacingDummyLayer(),
# Block 2
Conv2D(128, (3, 3), padding='same'),
Conv2D(128, (3, 3), padding='same'),
MaxPooling2D((2, 2)),
SpacingDummyLayer(),
# Block 3
Conv2D(256, (3, 3), padding='same'),
Conv2D(256, (3, 3), padding='same'),
Conv2D(256, (3, 3), padding='same'),
MaxPooling2D((2, 2)),
SpacingDummyLayer(),
# Classification
Flatten(),
Dense(4096, activation='relu'),
Dense(1000, activation='softmax')
])
visualkeras.layered_view(
model,
type_ignore=[SpacingDummyLayer]
).show()
See Also#
Sequential Models for LeNet with spacing examples
Advanced Features and Techniques for filtering and visualization techniques