Write Conv2D and Active function from scratch
Created | |
---|---|
Tags | ML Coding |
import numpy as np
def convolve2D(image, kernel, padding=0, strides=1):
# Cross Correlation
kernel = np.flipud(np.fliplr(kernel))
# Gather Shapes of Kernel + Image + Padding
xKernShape, yKernShape = kernel.shape
xImgShape, yImgShape = image.shape
# Shape of Output Convolution
xOutput = (xImgShape - xKernShape + 2 * padding) // strides + 1
yOutput = (yImgShape - yKernShape + 2 * padding) // strides + 1
output = np.zeros((xOutput, yOutput))
# Apply Padding
if padding != 0:
imagePadded = np.pad(image, padding, mode='constant')
else:
imagePadded = image
# Iterate through image
for x in range(xOutput):
for y in range(yOutput):
output[x, y] = np.sum(kernel * imagePadded[x * strides: x * strides + xKernShape,
y * strides: y * strides + yKernShape])
return output