Python 如何使用Keras中的可训练内核创建自定义卷积操作?
我试图在Keras中创建一个自定义层,它将执行模糊运算,而不是卷积中的求和和和积 我已经在一个单独的项目上完成了卷积运算,代码如下:Python 如何使用Keras中的可训练内核创建自定义卷积操作?,python,tensorflow,keras,Python,Tensorflow,Keras,我试图在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_m
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是输入图像的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)