Keras GaussianNoise 层没有效果? [英] Keras GaussianNoise layer no effect?

查看:42
本文介绍了Keras GaussianNoise 层没有效果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 keras 的功能 API 为我的 CNN 中的图像添加一些高斯噪声,但是在测试一些不同的 stddev 值时,我注意到高斯层对输入数据没有任何作用.我使用以下代码进行测试:

I wanted to add some Gaussian noise to my Images in my CNN with the keras's functional API, but while testing some different stddev values, I noticed that the Gaussian Layer does nothing to the input data. I used the following code for testing:

import tensorflow as tf
import numpy as np
import cv2

stddev = 0.1
image = cv2.imread(<img_path>)
image = (image.astype('float32') - 127.5) / 127.5

input_layer = tf.keras.layers.Input(shape=(128,128,3))
gaus = tf.keras.layers.GaussianNoise(stddev)(input_layer)
model = tf.keras.models.Model(inputs=input_layer, outputs=gaus)

noisy_image = model(image)

print(f'Pixel value at 0,0: {image[0,0]}')
print(f'Pixel value at 0,0: {noisy_image.numpy()[0,0]}')
# Output
# Pixel value at 0,0: [ 0.09803922 -0.30980393 -0.56078434]
# Pixel value at 0,0: [ 0.09803922 -0.30980393 -0.56078434]

我为 stddev 设置的值并不重要(尝试了从 0.001 到 10000 的所有内容).我预计这些值会略有不同(或者当 stddev=1000 时差异很大).我做错了什么吗?

It doesn't matter what value I put in for stddev (tried everything from 0.001 to 10000). I expected the values to differ slightly (or heavily when stddev=1000). Am I doing something wrong?

也许我应该提到我在 Windows 10 上使用 tensorflow-gpu==2.0.0-rc0

Maybe I should mention that I'm using tensorflow-gpu==2.0.0-rc0 on Windows 10

推荐答案

如果你检查 the docs,它说该层仅在训练期间处于活动状态,因为它应该用作正则化器.查看源代码证实了这一点.所以看起来你是否需要确保模型知道"它处于训练模式.有几种方法可以做到这一点:

If you check the docs, it says the layer is only active during training as it's supposed to serve as a regularizer. Looking at the source code confirms this. So it looks like if you will need to make sure the model "knows" that it's in training mode. There are several ways to do this:

  • 如果您使用 model.compile/model.fit 接口,这应该会自动完成.
  • 如果您将模型用作可调用对象,它应该接受一个 training 参数,您可以将其设置为 training=True 以在每次调用时激活"训练模式基础.IE.noisy_image = model(image, training=True).
  • 您可以使用 tf.keras.backend.set_learning_phase(1) 来全局"激活训练模式(稍后使用参数 0 再次调用以停用).
  • If you use the model.compile/ model.fit interface, this should be done automatically.
  • If you use the model as a callable it should accept a training parameter that you can set as training=True to "activate" training mode on a per-call basis. I.e. noisy_image = model(image, training=True).
  • You can use tf.keras.backend.set_learning_phase(1) to "globally" activate training mode (call it again later with argument 0 to deactivate).

这篇关于Keras GaussianNoise 层没有效果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆