Implementation:Tensorflow Tfjs RandomWidth Layer
Appearance
| Knowledge Sources | |
|---|---|
| Domains | Deep_Learning, Layers_API, Preprocessing, Data_Augmentation |
| Last Updated | 2026-02-10 06:00 GMT |
Overview
The RandomWidth layer is a data augmentation preprocessing layer that randomly adjusts the width of images during training. The width is scaled by a random factor drawn uniformly from the range [1 + widthLower, 1 + widthUpper]. The layer supports both bilinear and nearest interpolation methods. It extends BaseRandomLayer for reproducible random number generation.
Code Reference
Source Location
tfjs-layers/src/layers/preprocessing/random_width.ts (GitHub)
Key Imports
import {image, Rank, serialization, Tensor, tidy} from '@tensorflow/tfjs-core';
import {BaseRandomLayerArgs, BaseRandomLayer} from '../../engine/base_random_layer';
import {randomUniform} from '@tensorflow/tfjs-core';
Layer Class
export class RandomWidth extends BaseRandomLayer {
static override className = 'RandomWidth';
constructor(args: RandomWidthArgs);
override getConfig(): serialization.ConfigDict;
override computeOutputShape(inputShape: Shape | Shape[]): Shape | Shape[];
override call(inputs: Tensor<Rank.R3> | Tensor<Rank.R4>,
kwargs: Kwargs): Tensor[] | Tensor;
}
RandomWidthArgs
export interface RandomWidthArgs extends BaseRandomLayerArgs {
factor: number | [number, number]; // width adjustment factor range
interpolation?: InterpolationType; // 'bilinear' (default) or 'nearest'
seed?: number;
autoVectorize?: boolean;
}
Factor Interpretation
- Single number (e.g.,
0.2): Interpreted as[-0.2, 0.2], so width is scaled by a factor in[0.8, 1.2]. - Tuple (e.g.,
[-0.1, 0.3]): Width is scaled by a factor in[0.9, 1.3]. - Both bounds must be >= -1.0, and upper bound must be >= lower bound.
I/O Contract
| Method | Input | Output |
|---|---|---|
call |
3D or 4D image tensor | Tensor with randomly adjusted width, height unchanged |
computeOutputShape |
Input shape | [imgHeight, -1, numChannels] (width is dynamic)
|
Usage Example
import * as tf from '@tensorflow/tfjs';
const augmenter = tf.layers.randomWidth({
factor: 0.2, // width varies by +/- 20%
interpolation: 'bilinear',
seed: 42
});
const images = tf.randomNormal([4, 100, 100, 3]);
const augmented = augmenter.apply(images, {training: true});
// width will be randomly adjusted between 80 and 120 pixels
Related Pages
- Tensorflow_Tfjs_RandomHeight_Layer - Random height augmentation layer (symmetric counterpart)
- Tensorflow_Tfjs_Resizing_Layer - Deterministic image resizing layer
- Tensorflow_Tfjs_CenterCrop_Layer - Center crop preprocessing layer
Page Connections
Double-click a node to navigate. Hold to expand connections.
Principle
Implementation
Heuristic
Environment