Implementation:Tensorflow Tfjs Padding Layers
| Knowledge Sources | |
|---|---|
| Domains | Deep_Learning, Layers_API, Convolutional |
| Last Updated | 2026-02-10 06:00 GMT |
Overview
This module implements padding layers and utility functions for TensorFlow.js Layers. It provides temporalPadding for 3D tensors (sequence data), spatial2dPadding for 4D tensors (image data), and the ZeroPadding2D layer class that adds rows and columns of zeros to the spatial dimensions of a 4D image tensor. These are ported from Keras convolutional.py but placed in a separate file for clarity.
Code Reference
Source Location
tfjs-layers/src/layers/padding.ts (GitHub)
Key Imports
import * as tfc from '@tensorflow/tfjs-core';
import {serialization, Tensor, tidy} from '@tensorflow/tfjs-core';
import {imageDataFormat} from '../backend/common';
import {InputSpec, Layer, LayerArgs} from '../engine/topology';
Utility Functions
temporalPadding
Pads the middle (temporal) dimension of a 3D tensor with zeros.
export function temporalPadding(x: Tensor, padding?: [number, number]): Tensor
Default padding is [1, 1]. Input must be rank 3.
spatial2dPadding
Pads the 2nd and 3rd spatial dimensions of a 4D tensor, respecting channelsFirst or channelsLast data format.
export function spatial2dPadding(
x: Tensor,
padding?: [[number, number], [number, number]],
dataFormat?: DataFormat): Tensor
Default padding is [[1, 1], [1, 1]].
Layer Class
ZeroPadding2D
export class ZeroPadding2D extends Layer {
static className = 'ZeroPadding2D';
readonly dataFormat: DataFormat;
readonly padding: [[number, number], [number, number]];
constructor(args?: ZeroPadding2DLayerArgs);
override computeOutputShape(inputShape: Shape | Shape[]): Shape | Shape[];
override call(inputs: Tensor | Tensor[], kwargs: Kwargs): Tensor | Tensor[];
override getConfig(): serialization.ConfigDict;
}
ZeroPadding2DLayerArgs
The padding parameter accepts three formats:
- Integer: Symmetric padding applied to both height and width.
- [number, number]: Symmetric padding
[heightPad, widthPad]. - [[number, number], [number, number]]: Explicit
[[topPad, bottomPad], [leftPad, rightPad]].
I/O Contract
| Operation | Input | Output |
|---|---|---|
temporalPadding |
3D Tensor [batch, time, features] | 3D Tensor with padded time dimension |
spatial2dPadding |
4D Tensor | 4D Tensor with padded spatial dimensions |
ZeroPadding2D.call |
4D Tensor [batch, h, w, c] (or channelsFirst) | 4D Tensor with zero-padded height and width |
computeOutputShape |
Input shape array | Output shape with increased spatial dims |
Usage Example
import * as tf from '@tensorflow/tfjs';
const model = tf.sequential();
model.add(tf.layers.zeroPadding2d({
padding: [[1, 1], [2, 2]], // 1px top/bottom, 2px left/right
inputShape: [28, 28, 1]
}));
// Output shape: [null, 30, 32, 1]
Related Pages
- Tensorflow_Tfjs_DepthwiseConv2D_Layer - Depthwise convolution layer often used after padding
- Tensorflow_Tfjs_Resizing_Layer - Image resizing preprocessing layer