From ef046dfc6d2b66237b7b71a8be84a8032e0bae22 Mon Sep 17 00:00:00 2001 From: Donato Meoli Date: Wed, 2 Dec 2026 05:37:05 +0100 Subject: [PATCH 1/2] Compute conv1D as equation 21.8, without flipping the kernel np.convolve flips the kernel, so an asymmetric kernel gave the opposite result of the book, and a kernel longer than the input gave max(n, l) values. conv1D now computes z_i = sum_j k_j x_{j+i-(l+1)/2} with zero padding, always n values; for an even l the kernel covers one element more to the right of x_i. The [1, 0, -1] expectations of the ConvLayer1D test change sign, and the long kernel gives [6, 6, 6] instead of [3, 6, 6, 6, 5]. --- aima/utils.py | 19 +++++++++++++++++-- tests/test_deep_learning.py | 21 ++++++++++++++++----- 2 files changed, 33 insertions(+), 7 deletions(-) diff --git a/aima/utils.py b/aima/utils.py index 79dff7dad..b5a11525a 100644 --- a/aima/utils.py +++ b/aima/utils.py @@ -840,8 +840,23 @@ def gaussian_kernel_2D(size=3, sigma=0.5): def conv1D(x, k): - """1D convolution. x: input vector; K: kernel vector.""" - return np.convolve(x, k, mode='same') + """1D convolution of the input vector x with the kernel vector k, as in equation + (21.8): z_i = sum_{j=1..l} k_j x_{j+i-(l+1)/2}, where l is the length of k. + + As in the book (footnote 4 of chapter 21), the kernel is not flipped, i.e., this is + the cross-correlation of signal processing, and as in figure 21.5 the input is + padded with zeros, so that z is as long as x also when k is longer than x. For an + even l, (l+1)/2 is rounded down: the kernel covers one element more to the right + of x_i than to the left, as the 'same' padding of the deep-learning libraries. + """ + x, k = np.asarray(x), np.asarray(k) + n, l = len(x), len(k) + left = (l - 1) // 2 + padded = np.pad(x, (left, l - 1 - left)) + z = np.zeros(n, dtype=np.result_type(x, k)) + for j in range(l): + z += k[j] * padded[j:j + n] + return z def map_vector(f, x): diff --git a/tests/test_deep_learning.py b/tests/test_deep_learning.py index f7bd3ebd1..81b2b0698 100644 --- a/tests/test_deep_learning.py +++ b/tests/test_deep_learning.py @@ -3,6 +3,7 @@ from aima.deep_learning import * from aima.learning import DataSet, grade_learner, err_ratio +from aima.utils import conv1D random.seed("aima-python") @@ -57,12 +58,13 @@ def test_conv_layer_1d(): layer = ConvLayer1D(size=2, kernel_size=3) # the default kernel is a narrow gaussian, peaked at its centre assert np.argmax(layer.nodes[0].weights) == 1 - # with kernel [1, 0, -1] each output is x[i + 1] - x[i - 1] (zero padding at the ends) + # with kernel [1, 0, -1], not flipped (eq. 21.8), each output is x[i - 1] - x[i + 1] + # (zero padding at the ends) for node in layer.nodes: node.weights = [1, 0, -1] out = layer.forward([[1, 2, 3, 4, 5], [0, 0, 1, 0, 0]]) - assert list(out[0]) == [2, 2, 2, 2, -4] and list(out[1]) == [0, 1, 0, -1, 0] - assert list(layer.nodes[1].value) == [0, 1, 0, -1, 0] + assert list(out[0]) == [-2, -2, -2, -2, 4] and list(out[1]) == [0, -1, 0, 1, 0] + assert list(layer.nodes[1].value) == [0, -1, 0, 1, 0] def test_max_pooling_layer_1d(): @@ -142,10 +144,19 @@ def test_convolution_pooling_and_normalization_of_a_constant_input(): def test_convolution_with_a_kernel_longer_than_the_input(): - # the book does not define it: conv1D (numpy mode 'same') returns max(n, m) values + # eq. 21.8 with zero padding: as many outputs as inputs, the kernel centred on each layer = ConvLayer1D(size=1, kernel_size=5) layer.nodes[0].weights = [1, 1, 1, 1, 1] - assert list(layer.forward([[1, 2, 3]])[0]) == [3, 6, 6, 6, 5] + assert list(layer.forward([[1, 2, 3]])[0]) == [6, 6, 6] + layer.nodes[0].weights = [1, 2, 3, 4, 5] + assert list(layer.forward([[1, 2, 3]])[0]) == [26, 20, 14] + + +def test_convolution_with_an_asymmetric_kernel(): + # z_i = sum_j k_j x_{j+i-(l+1)/2} (eq. 21.8): the kernel is not flipped + assert list(conv1D([1, 2, 3, 4], [1, 0, -1])) == [-2, -2, -2, 3] + # an even kernel covers one more element to the right of x_i than to the left + assert list(conv1D([1, 2, 3, 4], [1, -1])) == [-1, -1, -1, 4] def weights_of(net): From 1b03118132960b7054fd045bc19330202eed00ce Mon Sep 17 00:00:00 2001 From: Donato Meoli Date: Wed, 2 Dec 2026 05:37:05 +0100 Subject: [PATCH 2/2] Detect edges with a 2D convolution as equation 21.8 The edge detectors used scipy.signal.convolve2d, which flips the kernel. conv2D applies equation 21.8 along both dimensions with the conventions of conv1D. With the 4 columns of the derivative of gaussian not flipped, the uniform region right of the step is compared at column 5 instead of column 6, which the kernel reaches from the padding. --- aima/perception.py | 14 +++++++------- aima/utils.py | 17 +++++++++++++++++ tests/test_deep_learning.py | 4 +++- tests/test_perception.py | 5 +++-- 4 files changed, 30 insertions(+), 10 deletions(-) diff --git a/aima/perception.py b/aima/perception.py index 89aab9434..a7dad6d72 100644 --- a/aima/perception.py +++ b/aima/perception.py @@ -11,7 +11,7 @@ from keras.layers import Dense, Activation, Flatten, InputLayer, Conv2D, MaxPooling2D from keras.models import Sequential -from aima.utils import gaussian_kernel_2D +from aima.utils import conv2D, gaussian_kernel_2D # repo root (the directory containing the `aima` package), so the bundled sample # images resolve regardless of the current working directory @@ -44,9 +44,9 @@ def gradient_edge_detector(image): image = np.asarray(image) # gradient filters of x and y direction edges x_filter, y_filter = np.array([[1, -1]]), np.array([[1], [-1]]) - # convolution between filter and image to get edges - y_edges = scipy.signal.convolve2d(image, x_filter, 'same') - x_edges = scipy.signal.convolve2d(image, y_filter, 'same') + # convolution (21.8) between filter and image to get edges + y_edges = conv2D(image, x_filter) + x_edges = conv2D(image, y_filter) edges = array_normalization(x_edges + y_edges, 0, 255) return edges @@ -61,8 +61,8 @@ def gaussian_derivative_edge_detector(image): x_filter = scipy.signal.convolve2d(gaussian_filter, np.asarray([[1, -1]]), 'full') y_filter = scipy.signal.convolve2d(gaussian_filter, np.asarray([[1], [-1]]), 'full') # extract edges using convolution - y_edges = scipy.signal.convolve2d(image, x_filter, 'same') - x_edges = scipy.signal.convolve2d(image, y_filter, 'same') + y_edges = conv2D(image, x_filter) + x_edges = conv2D(image, y_filter) edges = array_normalization(x_edges + y_edges, 0, 255) return edges @@ -116,7 +116,7 @@ def laplacian_edge_detector(image): # init laplacian filter laplacian_kernel = np.asarray([[0, -1, 0], [-1, 4, -1], [0, -1, 0]]) # extract edges with convolution - edges = scipy.signal.convolve2d(image, laplacian_kernel, 'same') + edges = conv2D(image, laplacian_kernel) edges = array_normalization(edges, 0, 255) return edges diff --git a/aima/utils.py b/aima/utils.py index b5a11525a..30cc72431 100644 --- a/aima/utils.py +++ b/aima/utils.py @@ -859,6 +859,23 @@ def conv1D(x, k): return z +def conv2D(X, K): + """2D convolution of the matrix X with the kernel matrix K: equation (21.8) applied + along both dimensions, i.e., z_{r,c} = sum_{a,b} K_{a,b} X_{a+r-(l_1+1)/2, b+c-(l_2+1)/2} + for a kernel of l_1 rows and l_2 columns, with the same conventions as conv1D (kernel + not flipped, zero padding, output of the shape of X, extra element of an even kernel + side below and to the right).""" + X, K = np.asarray(X), np.asarray(K) + (n1, n2), (l1, l2) = X.shape, K.shape + top, left = (l1 - 1) // 2, (l2 - 1) // 2 + padded = np.pad(X, ((top, l1 - 1 - top), (left, l2 - 1 - left))) + Z = np.zeros((n1, n2), dtype=np.result_type(X, K)) + for a in range(l1): + for b in range(l2): + Z += K[a, b] * padded[a:a + n1, b:b + n2] + return Z + + def map_vector(f, x): """Apply function f to iterable x.""" return [map_vector(f, _x) for _x in x] if hasattr(x, '__iter__') else list(map(f, [x]))[0] diff --git a/tests/test_deep_learning.py b/tests/test_deep_learning.py index 81b2b0698..98cbc77c1 100644 --- a/tests/test_deep_learning.py +++ b/tests/test_deep_learning.py @@ -3,7 +3,7 @@ from aima.deep_learning import * from aima.learning import DataSet, grade_learner, err_ratio -from aima.utils import conv1D +from aima.utils import conv1D, conv2D random.seed("aima-python") @@ -157,6 +157,8 @@ def test_convolution_with_an_asymmetric_kernel(): assert list(conv1D([1, 2, 3, 4], [1, 0, -1])) == [-2, -2, -2, 3] # an even kernel covers one more element to the right of x_i than to the left assert list(conv1D([1, 2, 3, 4], [1, -1])) == [-1, -1, -1, 4] + assert conv2D([[1, 2], [3, 4]], [[1, -1]]).tolist() == [[-1, 2], [-1, 4]] + assert conv2D([[1, 2], [3, 4]], [[1], [-1]]).tolist() == [[-2, -2], [3, 4]] def weights_of(net): diff --git a/tests/test_perception.py b/tests/test_perception.py index f80cf61f2..b127564be 100644 --- a/tests/test_perception.py +++ b/tests/test_perception.py @@ -71,9 +71,10 @@ def test_edge_detectors(detector): edges = detector(step_image) assert edges.shape == step_image.shape and edges.min() == 0 and edges.max() == pytest.approx(255) # away from the image border the uniform regions give the same response on both - # sides of the step, and the step stands out from it + # sides of the step, and the step stands out from it (column 5, not 6: from column 6 + # the 4 columns of the derivative of gaussian, not flipped, reach the padding) for row in edges[2:6]: - assert row[1] == pytest.approx(row[6]) + assert row[1] == pytest.approx(row[5]) assert max(abs(row[3] - row[1]), abs(row[4] - row[1])) > 60 # a uniform image has no edges at all inside flat = detector(np.ones((8, 8)) + np.eye(8)[0])