ML Foundations

Pad one NumPy axis and track real values

Use per-axis padding widths and a validity mask to distinguish padding from real zeros.

Example results for Pad one NumPy axis and track real values. padded: [0, 0, 2, 0, 0], [0, 3, 4, 0, 0]
Illustration: Original illustration by Tensor Almanac
Evidence and testing

Review record: Tensor Almanac automated evidence gate (no independent human review). Example versions, recorded outputs and limitations appear below.

Pad widths describe each axis

A two-dimensional feature table can need extra columns without changing its row count. NumPy pad accepts a before-and-after pair for each axis. For a matrix, the first pair controls rows and the second controls columns. [1]

The widths ((0, 0), (1, 2)) add no rows, one column before the original columns, and two after them. A scalar padding width instead applies the same amount before and after every axis, so it describes a different shape. [1]

References: [1]

Carry an explicit validity mask

Run python examples/numpy_pad_axis_mask.py. The input has two rows and two columns, including a real zero. Padding the column axis with zeros produces two rows and five columns. A padded zero alone does not indicate whether a position was originally present. [1]

The example creates a Boolean array of true values matching the input, then applies the same padding widths with false as the padding value. The mask preserves the real zero as valid and marks only added positions false. Assertions check that the masked output recovers the original values in this fixture. [1, 2]

Executed with Python 3.12.14; stdout and checksum recorded in private evidence.

import numpy as np

data = np.array([[0, 2], [3, 4]])
widths = ((0, 0), (1, 2))
padded = np.pad(data, widths, mode='constant', constant_values=0)
valid = np.pad(np.ones_like(data, dtype=bool), widths, mode='constant', constant_values=False)
print('padded:', padded.tolist())
print('valid:', valid.tolist())
print('shape:', padded.shape)
assert np.array_equal(padded[valid], data.ravel())
assert valid.sum() == data.size

Recorded output

padded: [[0, 0, 2, 0, 0], [0, 3, 4, 0, 0]]
valid: [[False, True, True, False, False], [False, True, True, False, False]]
shape: (2, 5)

References: [1], [2]

Use the same alignment downstream

Pass the mask along with the padded array when later operations should ignore padded positions. Padding values and their interpretation are a choice of the application; zero may also be a legitimate observation, as in this fixture.

This example uses a two-dimensional integer array and constant padding only. Other modes, multiple sequences with different lengths, and reductions over masked data need their own handling. The example does not measure performance. [1]

References: [1]

Sources

  1. NumPy pad
  2. NumPy ones_like