Skip to content

Instantly share code, notes, and snippets.

@NicolaBernini
Created August 23, 2019 10:51
Show Gist options
  • Save NicolaBernini/4b5ffeaa472312c93adc1ee1c07683b9 to your computer and use it in GitHub Desktop.
Save NicolaBernini/4b5ffeaa472312c93adc1ee1c07683b9 to your computer and use it in GitHub Desktop.
ConvFilter Kernel

Overview

In this simple exercise, a simple ConvFilter in Numpy is created

# Defines a WxHxC ConvFilter
# Conventional Internal Representation is C,H,W
class Conv:
# w, h = Kernel Spatial Domain
# in_c = Input Tensor Channels
# out_c = Output Tensor Channels
def __init__(self, w, h, in_c, out_c):
self.w = w
self.h = h
self.in_c = in_c
self.out_c = out_c
# Choose the preferred initialization: ones or random
self.filters = np.ones((out_c, in_c,h,w))
#self.filters = np.random.randn(out_c, in_c,h,w) / 9
# Image Convention is CxHxW
def apply(self, image):
if(self.in_c != image.shape[0]):
raise("Channel Size Mismatch")
out_h = image.shape[1] - 2*(self.h//2)
out_w = image.shape[2] - 2*(self.w//2)
res = np.zeros((self.out_c, out_h, out_w))
# Spatial Loop
for _c in range(self.out_c):
for _h in range( out_h ):
for _w in range( out_w ):
res[_c, _h, _w] = np.sum(image[:, _h:(_h+self.h), _w:(_w+self.w)] * self.filters[_c,:,:,:] )
return res
conv1 = Conv(3,3,1,6)
test_image = np.ones((1, 10, 10))
res = conv1.apply(test_image)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment