我正在尝试在Keras中创建一个自定义层,该层将执行模糊运算,而不是卷积中的求和与积。
我已经在一个单独的项目上进行了卷积运算,代码如下:
activation_map = np.random.random((img_x - kern_x + 1, img_y - kern_y + 1))
for i in range(activation_map.shape[0]):
for j in range(activation_map.shape[1]):
activation_map[i][j] = t_conorm(weighting(scaled_matrix[i:i+kern_x,j:j+kern_y],kern))
print(activation_map)
在这里,kern_x和kern_y是2D内核的尺寸。 img_x和img_y是输入图像的。我使用了28x28的图像和3x3的内核。图像和内核都是numpy数组。
如何在Keras中将其实现为自定义图层?我查看了Keras的文档,了解如何构建自定义图层,并且发现它很难理解。我需要内核是可训练的。
这是我到目前为止所做的:
class F_Conv2D(Layer):
def __init__(self, output_dim, **kwargs):
self.output_dim = output_dim
super(F_Conv2D, self).__init__(**kwargs)
def build(self, input_shape):
# Create a trainable weight variable for this layer.
self.kernel = self.add_weight(name='kernel',
shape=(3,3),
initializer='uniform',
trainable=True)
super(F_Conv2D, self).build(input_shape) # Be sure to call this at the end
def call(self, x):
# return K.dot(x, self.kernel)
kern_x,kern_y = self.kernel.eval().shape
img_x,img_y = x.eval().shape
fuzzy_activation_map = np.random.random((img_x - kern_x + 1, img_y - kern_y + 1))
for i in range(activation_map.shape[0]):
for j in range(activation_map.shape[1]):
fuzzy_activation_map[i][j] = t_conorm(weighting(scaled_matrix[i:i+kern_x,j:j+kern_y],kern))
return fuzzy_activation_map
def compute_output_shape(self, input_shape):
return (input_shape[0], self.output_dim)