ML Foundations

Choose reflect or symmetric padding in NumPy

Compare whether edge values repeat when extending a sequence with mirrored padding.

Example results for Choose reflect or symmetric padding in NumPy. input: 10, 20, 30, 40
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.

Two ways to mirror a boundary

Image and sequence preprocessing may require values outside the original array. NumPy pad supports both reflect and symmetric modes, but they differ at the edge. With the default even reflection used here, reflect starts from the next value inside the array, while symmetric includes the edge value in the reflection. [1]

For the signal 10, 20, 30, 40 with two added values on each side, the immediate left padding is 20 in reflect mode and 10 in symmetric mode. The choice changes the boundary values seen by later operations.

References: [1]

Inspect both padded arrays

Run python examples/numpy_pad_reflect_symmetric.py. The script pads the same one-dimensional array with two entries before and two after. It prints both results and checks their full contents. [1]

A slice from index 2 up to but excluding index 6 recovers the original signal in both padded arrays. The assertion checks the actual result, not an assumption about an image-processing pipeline. NumPy basic slicing uses a half-open interval. [2]

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

import numpy as np

signal = np.array([10, 20, 30, 40])
reflect = np.pad(signal, (2, 2), mode='reflect')
symmetric = np.pad(signal, (2, 2), mode='symmetric')
print('input:', signal.tolist())
print('reflect:', reflect.tolist())
print('symmetric:', symmetric.tolist())
print('center unchanged:', bool(np.array_equal(reflect[2:6], signal) and np.array_equal(symmetric[2:6], signal)))
assert reflect.tolist() == [30, 20, 10, 20, 30, 40, 30, 20]
assert symmetric.tolist() == [20, 10, 10, 20, 30, 40, 40, 30]

Recorded output

input: [10, 20, 30, 40]
reflect: [30, 20, 10, 20, 30, 40, 30, 20]
symmetric: [20, 10, 10, 20, 30, 40, 40, 30]
center unchanged: True

References: [1], [2]

Apply the mode to your own data

Choose the mode that matches the intended boundary condition and check a small example before applying it to image rows or other features. The number of added values is specified independently of the mode. NumPy also supports per-axis widths for multidimensional arrays. [1]

This fixture uses even reflection, a nonempty one-dimensional integer array and a width of two. It does not test odd reflection, empty inputs, model accuracy or runtime. A result from another library may require checking that library’s own definition of reflection.

References: [1]

Sources

  1. NumPy pad
  2. NumPy indexing and slicing