gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 16:03:54 25 4
gpt4 key购买 nike

我有一个自动编码器,我需要在输出后添加一个高斯噪声层。我需要一个自定义层来执行此操作,但我真的不知道如何生成它,我需要使用张量生成它。
enter image description here

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

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 层来实现,但它不起作用。

最佳答案

如果您正在寻找 添加剂 乘法高斯噪声,那么它们已经在 Keras 中实现为一层: GuassianNoise (添加剂)和 GuassianDropout (乘法)。

但是,如果您专门寻找 Gaussian blur 中的模糊效果在图像处理中使用过滤器,然后您可以简单地使用深度卷积层(在每个输入 channel 上独立应用过滤器)和 固定 权重以获得所需的输出(请注意,您需要生成高斯核的权重以将它们设置为 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...

关于python - 如何在 Keras 中实现高斯模糊层?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55643675/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com