如何在Keras中实现高斯模糊层?

2024-09-30 10:36:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个自动编码器,我需要添加一个高斯噪声层后,我的输出。我需要一个自定义层来做这件事,但我真的不知道如何产生它,我需要产生它使用张量。 enter image description here

如果我想在下面代码的call部分实现上面的等式,我应该怎么做?在

class SaltAndPepper(Layer):

    def __init__(self, ratio, **kwargs):
        super(SaltAndPepper, self).__init__(**kwargs)
        self.supports_masking = True
        self.ratio = ratio

    # the definition of the call method of custom layer
    def call(self, inputs, training=None):
        def noised():
            shp = K.shape(inputs)[1:]

         **what should I put here????**            
                return out

        return K.in_train_phase(noised(), inputs, training=training)

    def get_config(self):
        config = {'ratio': self.ratio}
        base_config = super(SaltAndPepper, self).get_config()
        return dict(list(base_config.items()) + list(config.items()))

我也尝试使用lambda层实现,但它不起作用。在


Tags: oftheselfconfigreturninitdeftraining
2条回答

作为错误:AttributeError: 'float' object has no attribute 'dtype',只需将K.sqrt更改为math.sqrt,就可以了。在

如果您正在寻找加法乘法高斯噪声,那么它们已经在Keras中实现为一个层:^{}(加法)和{a2}(乘法)。在

但是,如果您特别想要寻找图像处理中的Gaussian blur过滤器中的模糊效果,然后,您可以简单地使用一个深度卷积层(在每个输入通道上独立地应用滤波器)和固定的权重来获得所需的输出(请注意,您需要生成高斯核的权重,将其设置为DepthwiseConv2D层的权重。为此,您可以使用answer中介绍的函数:

import numpy as np
from keras.layers import DepthwiseConv2D

kernel_size = 3  # set the filter size of Gaussian filter
kernel_weights = ... # compute the weights of the filter with the given size (and additional params)

# assuming that the shape of `kernel_weighs` is `(kernel_size, kernel_size)`
# we need to modify it to make it compatible with the number of input channels
in_channels = 3  # the number of input channels
kernel_weights = np.expand_dims(kernel_weights, axis=-1)
kernel_weights = np.repeat(kernel_weights, in_channels, axis=-1) # apply the same filter on all the input channels
kernel_weights = np.expand_dims(kernel_weights, axis=-1)  # for shape compatibility reasons

# define your model...

# somewhere in your model you want to apply the Gaussian blur,
# so define a DepthwiseConv2D layer and set its weights to kernel weights
g_layer = DepthwiseConv2D(kernel_size, use_bias=False, padding='same')
g_layer_out = g_layer(the_input_tensor_for_this_layer)  # apply it on the input Tensor of this layer

# the rest of the model definition...

# do this BEFORE calling `compile` method of the model
g_layer.set_weights([kernel_weights])
g_layer.trainable = False  # the weights should not change during training

# compile the model and start training...

相关问题 更多 >

    热门问题