ML Foundations

Edit a NumPy broadcast view safely

Understand why broadcast_to is read-only and make a writable copy for independent channel edits.

Example results for Edit a NumPy broadcast view safely. broadcast assignment rejected: True
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.

Broadcasting can expose repeated positions

A grayscale image can be expanded to three channels by adding a length-one axis and broadcasting it. The resulting shape may look like a regular three-channel array, but NumPy broadcast_to returns a read-only view. Multiple displayed positions can refer to the same underlying memory location. [1]

Assigning into that view raises a ValueError. Reading from it is appropriate when repeated values are enough and no independent channel changes are needed.

References: [1]

Copy before independent edits

Run python examples/numpy_broadcast_writable_copy.py. The example broadcasts a two-by-two grayscale array across three channels and confirms that assignment to the view is rejected. It then copies the view and changes only the first channel of the first pixel. [1, 2]

The printed source pixel remains one while the copied channels become nine, one and one. The example also checks writeability and verifies that this numeric copy does not share memory with the source. [2]

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

import numpy as np

gray = np.array([[1, 2], [3, 4]])
view = np.broadcast_to(gray[..., None], (2, 2, 3))
try:
    view[0, 0, 0] = 9
except ValueError:
    print("broadcast assignment rejected:", True)
else:
    raise AssertionError("expected a read-only view")

rgb = view.copy()
rgb[0, 0, 0] = 9
assert gray[0, 0] == 1
assert rgb[0, 0].tolist() == [9, 1, 1]
assert not np.shares_memory(gray, rgb)
print("view writable:", view.flags.writeable)
print("copy writable:", rgb.flags.writeable)
print("source pixel:", int(gray[0, 0]))
print("copied channels:", rgb[0, 0].tolist())
print("copy shares source memory:", np.shares_memory(gray, rgb))

Recorded output

broadcast assignment rejected: True
view writable: False
copy writable: True
source pixel: 1
copied channels: [9, 1, 1]
copy shares source memory: False

References: [1], [2]

Choose the representation for the next operation

Keep the read-only broadcast view for operations that only consume the repeated values. Make a copy when downstream code must modify channels independently, and account for the storage required for the full copied shape. [1, 2]

This fixture uses a small numeric array and a channel-last layout. A copy of an object array is shallow with respect to the Python objects it contains, so copying the array does not recursively copy those objects. [2]

References: [1], [2]

Sources

  1. NumPy broadcast_to
  2. NumPy copy