Check the shape of a batch before processing
Type one expression at a time and check its delimiters. · 177 words
The shape of a batch gives the size of each dimension, or axis. For tabular data, shape (2, 3) means two records with three features each. The first axis is the batch axis. The second is the feature axis. Check both before model processing: rows = [[0.1, 0.2, 0.3], [0.4, 0.5, 0.6]] assert len(rows) == 2 assert all(len(row) == 3 for row in rows) print('Batch shape:', (len(rows), len(rows[0]))) There are two rows and each has three values, so the assertions pass and the printed shape is (2, 3).
A different experiment may receive images. An image batch can have axes for batch, height, width, and channels. Three channels commonly store red, green, and blue values. NumPy exposes the shape directly: import numpy as np images = np.zeros((2, 16, 16, 3)) assert images.shape == (2, 16, 16, 3) print(images.shape) The output (2, 16, 16, 3) means two images, each 16 pixels high, 16 pixels wide, and three channels. A shape check catches malformed inputs before a model runs. It checks structure, not whether each pixel value is reasonable.
Check your recall
What do the four numbers in the image batch shape (2, 16, 16, 3) represent?
Check your answer
They mean 2 images, each 16 pixels high, 16 pixels wide, and 3 channels per pixel.
Sources and credits
Original KeyTouch lesson. Background reading · Python Software Foundation · The Python Tutorial.