Implementation:Tensorflow Tfjs Container GetLayer
Metadata
| Field | Value |
|---|---|
| Implementation Name | Tensorflow Tfjs Container GetLayer |
| Library | TensorFlow.js |
| Domains | Transfer_Learning, Neural_Networks |
| Type | API Doc |
| Implements | Principle:Tensorflow_Tfjs_Feature_Extraction_Layer_Selection |
| Source | TensorFlow.js |
| Last Updated | 2026-02-10 00:00 GMT |
Environment:Tensorflow_Tfjs_Browser_Runtime
Overview
Container.getLayer is the TensorFlow.js method for retrieving a specific layer from a model by its name or index. In transfer learning, this method is used to select the intermediate layer whose output will serve as the feature extraction boundary. The companion property Container.layers provides the complete ordered list of all layers in the model, enabling inspection of the full architecture before selecting the extraction point.
Description
The getLayer method is defined on the Container class (the parent class of both Sequential and LayersModel) and returns a single Layer instance. The returned layer's output property (a SymbolicTensor) is the critical piece needed to construct a new transfer learning model using the Functional API.
The layers property provides an array of all layers in the model, ordered by horizontal graph traversal. This is useful for iterating over layers to inspect their names, output shapes, and positions before deciding which layer to extract features from.
Code Reference
Source file: tfjs-layers/src/engine/container.ts
- getLayer: Lines 1023-1044
- layers property: Line 69
Function Signatures
// Overloaded signatures
getLayer(name: string): Layer;
getLayer(index: number): Layer;
getLayer(name: string, index: number): Layer;
getLayer(nameOrIndex?: string | number, index?: number): Layer;
Property
// Property on Container class
layers: Layer[] // Array of all layers in horizontal graph traversal order
Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
| nameOrIndex | number | No | The name (string) or index (number) of the layer to retrieve. If both name and index are provided, both must match. |
| index | number |
No | When used as the second argument alongside a name, serves as additional validation. The layer at the given index must have the given name. |
Return Value
| Type | Description |
|---|---|
Layer |
The retrieved Layer instance. Use layer.output (a SymbolicTensor) to obtain the feature tensor for building a new model graph. Use layer.outputShape to inspect the tensor shape. |
I/O Contract
| Direction | Description |
|---|---|
| Inputs | A loaded base model (LayersModel or Sequential), plus a layer name (string) or layer index (number) identifying the desired extraction point. |
| Outputs | A Layer instance. The key properties for transfer learning are layer.output (SymbolicTensor for graph construction) and layer.outputShape (the tensor shape at that layer). |
| Side Effects | None. This is a pure accessor method. |
| Errors | Throws ValueError if no layer matches the given name or if the index is out of bounds. |
Usage Examples
Example 1: List All Layers to Choose Extraction Point
// List all layers to choose extraction point
baseModel.layers.forEach((layer, i) => {
console.log(i, layer.name, layer.outputShape);
});
Example 2: Get Layer by Name
// Get by name
const featureLayer = baseModel.getLayer('conv_pw_13_relu');
console.log('Feature layer output shape:', featureLayer.outputShape);
// Use layer output as feature tensor
const features = featureLayer.output; // SymbolicTensor
Example 3: Get Layer by Index
// Get by index (e.g., second-to-last layer)
const featureLayer = baseModel.getLayer(baseModel.layers.length - 2);
console.log('Selected layer:', featureLayer.name);
console.log('Output shape:', featureLayer.outputShape);
// Use layer output as feature tensor
const features = featureLayer.output; // SymbolicTensor
Example 4: Inspect and Select for Transfer Learning Pipeline
// Load base model
const baseModel = await tf.loadLayersModel(
'https://storage.googleapis.com/tfjs-models/tfjs/mobilenet_v1_0.25_224/model.json'
);
// Find layers that produce spatial feature maps (4D output)
const candidateLayers = baseModel.layers.filter(layer => {
const shape = layer.outputShape;
return Array.isArray(shape) && shape.length === 4;
});
console.log('Candidate feature extraction layers:');
candidateLayers.forEach(layer => {
console.log(` ${layer.name}: ${JSON.stringify(layer.outputShape)}`);
});
// Select the desired layer
const featureLayer = baseModel.getLayer('conv_pw_13_relu');
const featureOutput = featureLayer.output;
// featureOutput is now a SymbolicTensor ready for tf.model()
Example 5: Get Layer with Both Name and Index Validation
// Validate that a specific layer is at the expected index
// Throws if the layer at index 86 is not named 'conv_pw_13_relu'
const featureLayer = baseModel.getLayer('conv_pw_13_relu', 86);
Usage
In the transfer learning workflow, getLayer is used immediately after loading the base model and before constructing the task head:
- Load the base model with tf.loadLayersModel().
- Inspect layers using the layers property to understand the architecture.
- Select the extraction layer using getLayer() by name or index.
- Access the output SymbolicTensor via layer.output.
- Pass this SymbolicTensor to the task head layers and then to tf.model() to construct the complete transfer learning model.
Related Pages
- Principle:Tensorflow_Tfjs_Feature_Extraction_Layer_Selection -- The principle this implementation realizes
- Implementation:Tensorflow_Tfjs_Tf_LoadLayersModel_For_Transfer -- Loading the base model (prerequisite)
- Implementation:Tensorflow_Tfjs_Layer_Trainable_Setter -- Freezing the extracted feature layers
- Implementation:Tensorflow_Tfjs_Tf_Model_Functional -- Building the transfer learning model using the extracted features
Environments
- Environment:Tensorflow_Tfjs_Browser_Runtime -- Browser runtime (WebGL / WebGPU / WASM / CPU backends)