Im writing a project about convolutional neural network's and I need to implement an example of a convolution with a given input which is a 3x4-matrix and a 2x2 kernel.
I already have the answer for this equation, which is the picture under.
I have written this code where the output isn't right and I can't figure out what is wrong. Im sorry if this is the wrong format, I hope someone can help!
import numpy as np
def convolution(I,k):
#sikre dig først at de givende matricer er 2-dimensionelle
assert(I.ndim == 2)
assert(k.ndim == 2)
#Find størrelsen af de givende matricer rækker m og søjler n
I_x = I.shape[1]
I_y = I.shape[0]
k_x = k.shape[1]
k_y = k.shape[0]
# find herefter størrelsen af rækker og søjler i output-matrixen
Output_x = I_x - k_x + 1
Output_y = I_y - k_y + 1
#Skab nu en tom output-matrix
Output = np.zeros((Output_y, Output_x))
#Find først størrelsen af output matrixen
for m in range(Output_y):
for n in range(Output_x):
#"Scan" nu kernel-matrixen over input-matrixen og find elementerne i output-matrixen.
for i in range(k_y):
for j in range(k_x):
if (m-i >= 0) and (m-i < I_y) and (n-j >= 0) and (n-j < I_x):
Output[m,n] = Output[m,n] + k[i,j]*I[i-m,j-n]
return Output
if __name__=="__main__":
Input_data = np.array([[2,3,6,9],
[1,9,5,1],
[4,7,8,5]])
kernel = np.array([[1,2],
[3,1]])
print(convolution(Input_data, kernel))