Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 7 additions & 7 deletions aima/perception.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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

Expand All @@ -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

Expand Down Expand Up @@ -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

Expand Down
36 changes: 34 additions & 2 deletions aima/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -840,8 +840,40 @@ 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 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):
Expand Down
23 changes: 18 additions & 5 deletions tests/test_deep_learning.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

from aima.deep_learning import *
from aima.learning import DataSet, grade_learner, err_ratio
from aima.utils import conv1D, conv2D

random.seed("aima-python")

Expand Down Expand Up @@ -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():
Expand Down Expand Up @@ -142,10 +144,21 @@ 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]
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):
Expand Down
5 changes: 3 additions & 2 deletions tests/test_perception.py
Original file line number Diff line number Diff line change
Expand Up @@ -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])
Expand Down
Loading