gpt4 book ai didi

python - 如何在 Keras 中实现 Salt&Pepper 层?

转载 作者:行者123 更新时间:2023-12-04 15:46:16 26 4
gpt4 key购买 nike

我需要像高斯噪声一样在 keras 中实现盐和胡椒层,我尝试使用以下代码但它产生了几个错误。你能告诉我有什么问题吗?您对实现 S&P 层还有其他建议吗?谢谢你。

from keras.engine.topology import Layer

class SaltAndPepper(Layer):

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

def call(self, inputs, training=None):
def noised():
r = self.ratio*10
s = inputs.shape[1]
n = int( s * r/10 )
perm = np.random.permutation(r)[:n]
inputs[perm] = (np.random.rand(n) > 0.5)
return inputs

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()))

Traceback (most recent call last):

File "", line 125, in decoded_noise=SaltAndPepper(0.5)(decoded)

File "D:\software\Anaconda3\envs\py36\lib\site-packages\keras\engine\base_layer.py", line 457, in call output = self.call(inputs, **kwargs)

File "", line 57, in call return K.in_train_phase(noised(), inputs, training=training)

File "", line 52, in noised n = int( s * r/10 )

TypeError: unsupported operand type(s) for /: 'Dimension' and 'int'



更新:

我使用了@today 的解决方案并编写了以下代码:
decoded_noise=call(0.05,bncv11)#16

其中 bncv11 是它之前的批归一化层的输出。

但它会产生这个错误,为什么会发生?

Traceback (most recent call last):

File "", line 59, in decoded_noise=call(0.05,bncv11)#16

File "", line 34, in call return K.in_train_phase(noised(), inputs, training=training)

File "", line 29, in noised mask_select = K.random_binomial(shape=shp, p=self.ratio)

AttributeError: 'float' object has no attribute 'ratio'



保存模型并使用它后会产生此错误:

回溯(最近一次调用最后一次):

文件“”,第 1 行,在
b=load_model('桌面/los4x4_con_tile_convolw_FBN_SigAct_SandPAttack05.h5',custom_objects={'tf':tf})

文件
"D:\software\Anaconda3\envs\py36\lib\site-packages\keras\engine\Saving.py",
第 419 行,在 load_model 中
模型 = _deserialize_model(f, custom_objects, compile)

文件
"D:\software\Anaconda3\envs\py36\lib\site-packages\keras\engine\Saving.py",
第 225 行,在 _deserialize_model 中
模型 = model_from_config(model_config, custom_objects=custom_objects)

文件
"D:\software\Anaconda3\envs\py36\lib\site-packages\keras\engine\Saving.py",
第 458 行,在 model_from_config 中
返回反序列化(配置,custom_objects=custom_objects)

文件
"D:\software\Anaconda3\envs\py36\lib\site-packages\keras\layers__init__.py",
第 55 行,反序列化
printable_module_name='layer')

文件
"D:\software\Anaconda3\envs\py36\lib\site-packages\keras\utils\generic_utils.py",
第 145 行,在 deserialize_keras_object 中
列表(custom_objects.items())))

文件
"D:\software\Anaconda3\envs\py36\lib\site-packages\keras\engine\network.py",
第 1022 行,在 from_config 中
过程层(层数据)

文件
"D:\software\Anaconda3\envs\py36\lib\site-packages\keras\engine\network.py",
第 1008 行,在 process_layer
custom_objects=custom_objects)

文件
"D:\software\Anaconda3\envs\py36\lib\site-packages\keras\layers__init__.py",
第 55 行,反序列化
printable_module_name='layer')

文件
"D:\software\Anaconda3\envs\py36\lib\site-packages\keras\utils\generic_utils.py",
第 138 行,在 deserialize_keras_object 中
':' + class_name)

ValueError:未知层:SaltAndPepper

我将此代码放在我定义网络结构的程序中:
from keras.engine.topology import Layer

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=True):
def noised():
shp = K.shape(inputs)[1:]
mask_select = K.random_binomial(shape=shp, p=self.ratio)
mask_noise = K.random_binomial(shape=shp, p=0.5) # salt and pepper have the same chance
out = inputs * (1-mask_select) + mask_noise * mask_select
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()))

最佳答案

在图像处理中,椒盐噪声基本上是将随机选择的像素比值改变为盐(即白色,根据图像值的范围通常为 1 或 255)或胡椒(即黑色)通常为 0)。虽然,除了图像处理之外,我们还可以在其他领域使用相同的想法。因此,您必须首先指定三件事:

  • 应该改变多少像素? (噪声比)
  • 应该选择和更改哪些像素?
  • 哪些选定的像素应该加盐(和另一个加胡椒粉)?

  • 由于 Keras 后端有一个函数可以从具有给定 的二项式分布(即 0 或 1)中生成随机值。概率 ,我们可以通过生成两个掩码轻松完成上述所有步骤:一个用于选择具有给定比率的像素,另一个用于将盐或胡椒应用于这些选定的像素。这是如何做到的:
    from keras import backend as K

    # NOTE: this is the definition of the call method of custom layer class (i.e. SaltAndPepper)
    def call(self, inputs, training=None):
    def noised():
    shp = K.shape(inputs)[1:]
    mask_select = K.random_binomial(shape=shp, p=self.ratio)
    mask_noise = K.random_binomial(shape=shp, p=0.5) # salt and pepper have the same chance
    out = inputs * (1-mask_select) + mask_noise * mask_select
    return out

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

    请注意,在上面的代码中,我假设了一些事情:
  • 给定噪声比的值在 [0,1] 范围内。
  • 如果您使用此图层直接将其应用于图像,那么您必须注意它假定图像是灰度的(即单色 channel )。要将其用于 RGB 图像(即三个颜色 channel ),您可能需要稍微修改它,以便选择具有所有 channel 的像素来添加噪声(尽管,这取决于您如何定义和使用椒盐噪声) )。
  • 它假设盐的值为 1,胡椒的值为 0。不过,您可以轻松地将盐的值更改为 x。和胡椒粉到y通过更改 mask_noise 的定义如下:
    mask_noise = K.random_binomial(shape=shp, p=0.5) * (x-y) + y
  • 相同的噪声模式应用于批次中的所有样本(但是,批次之间会有所不同)。
  • 关于python - 如何在 Keras 中实现 Salt&Pepper 层?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55653940/

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