NumPy patterns and a batch generator

Drawing images without a single loop, and feeding a network one shuffled, augmented batch at a time.

What you'll learn
  • Build images from whole-array operations — tile, meshgrid, broadcasting — instead of loops
  • Write a batch generator that shuffles once per epoch and wraps around at the end
  • Recognise the difference between resizing an image and np.resize

The second half of this course moves to a separate repository, Deep-Learning-Problems, which rebuilds a deep learning framework in plain NumPy before returning to PyTorch for transformers. It opens with a warm-up: draw three images using NumPy only, with no loops allowed.

Three patterns, zero loops

A checkerboard is one 2×2-tile pattern repeated. pattern.py builds the tile and lets np.tile do the rest:

size = int(self.tile_size * 2)
tile = np.zeros((size, size), dtype=int)
tile[self.tile_size:, :self.tile_size] = 1
tile[:self.tile_size, self.tile_size:] = 1
num = int(self.resolution / (self.tile_size * 2))
self.output = np.tile(tile, (num, num))

A circle is a comparison evaluated at every pixel at once. np.meshgrid gives each pixel its \((x, y)\) coordinates, and broadcasting computes all the distances in one expression:

x, y = np.meshgrid(np.arange(res), np.arange(res))
distance = np.sqrt((x - self.position[0])**2 + (y - self.position[1])**2)
self.output = distance <= self.radius

The spectrum assigns a linear ramp to each colour channel — red increasing left to right, green top to bottom, blue decreasing left to right. Assigning a 1-D np.linspace(0, 1, res) to spectrum[:, :, 0] broadcasts it across every row; reshaping it to (res, 1) broadcasts it down every column instead. The same broadcasting rule is what makes the layer code in the next lessons short.

A batch generator

generator.py serves CIFAR-style images in batches: shuffle the index map at the start of each epoch, cut it into batch_size slices, optionally mirror or rotate each image, and when the last batch runs short, top it up from the start of the data. That is the job of every data loader, including PyTorch’s DataLoader in lesson 13.

Running it on ten dummy images with a batch size of 4 shows the first three calls behaving — images 0–3, 4–7, then 8, 9 and the wrap-around 0, 1 — and then a problem: every later call returns 8, 9, 0, 1 again, and the epoch counter stays at 0. The short final batch is filled but __batch_num is never advanced:

elif self.__batch_num * self.batch_size < self.__nsamples:
    ...                      # fill the last batch, wrap around
    # missing: self.__batch_num += 1

so the next call takes the same branch forever. Incrementing it there lets the following call start a new epoch (and reshuffle).

Two smaller things in the same file:

  • augment “resizes” with np.resize, which does not interpolate. It reads the pixels in memory order and repeats or truncates them to fill the new shape — a (2, 3) image resized to (3, 3) gets its first row again at the bottom. For real resizing use skimage.transform.resize or PIL.
  • class_name(x) returns self.labels[str(x)], which is the integer label of image x, not a name; the names live in self.class_dict.

Try it yourself. Add the missing increment and check with ten dummy images that the fourth call starts epoch 1. Then make Circle anti-aliased without a loop: replace the hard comparison with np.clip(self.radius + 0.5 - distance, 0, 1) and explain what that expression computes at the edge.

View source on GitHub →