我想创建自己的Keras噪声层,所以我从Keras GaussianNoise代码开始。调用方法是:
def call(self, inputs, training=None):
def noised():
return inputs + K.random_normal(shape=K.shape(inputs), mean=0., stddev=self.stddev)
return K.in_train_phase(noised, inputs, training=training)
我希望随机噪声仅应用于X%的像素,而不是所有像素。所以我需要生成一个其他随机二进制张量(随机0和1)。在this discussion之后,解决方案似乎使用了一个常数张量并执行类似的操作:
randomtensor = K.random_uniform(shape=K.shape(inputs), minval=0.0, maxval=100.0)
constensor = K.constant(0.0, shape=K.shape(inputs))
cond = K.less(randomvalues, constensor)
randomtensor = K.switch(cond, 1, randomtensor)
cond = K.greater_equal(randomvalues, constensor)
randomtensor = K.switch(cond, 0, randomtensor)
不幸的是,常量张量存在问题,我收到以下错误:
File "/Users/firetiti/NN/Keras/Contributions_Noise.py", line 50, in noised
constensor = K.constant(0.0, shape=K.shape(inputs))
File "/opt/local/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/keras/backend/tensorflow_backend.py", line 358, in constant
return tf.constant(value, dtype=dtype, shape=shape, name=name)
File "/opt/local/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/tensorflow/python/framework/constant_op.py", line 102, in constant
tensor_util.make_tensor_proto(value, dtype=dtype, shape=shape, verify_shape=verify_shape))
File "/opt/local/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/tensorflow/python/framework/tensor_util.py", line 416, in make_tensor_proto
shape = [int(dim) for dim in shape]
File "/opt/local/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/tensorflow/python/framework/ops.py", line 541, in iter
raise TypeError("'Tensor' object is not iterable.")
TypeError: 'Tensor' object is not iterable.
我做错了什么?
有没有更好的方法来生成随机二元张量?
答案 0 :(得分:2)
K.switch()
采用零维度表达式(即不是按元素划分if
)
以下是否符合您的要求?
from keras import backend as K
import numpy as np
a = np.asarray([[3,4,2,44,22,4,5,6,77,86,3,2,3,23,44,21],
[3,4,22,44,2,4,54,6,77,8,3,2,36,23,4,2]], dtype=np.float)
inputs = K.variable(a)
# probability per pixel to add noise
prob_noise = 0.2
# standard deviation of noise
noise_stddev = 0.1
# noise_mask will be a tensor of floats which are one
# if and only if the corresponding random value falls into the interval
# [0..prob_noise)
noise_mask = K.cast(
K.less(
K.random_uniform(shape=inputs.shape, minval=0.0, maxval=1.0),
prob_noise),
'float32')
noise = K.random_normal(shape = inputs.shape , mean=0., stddev = noise_stddev)
noised = inputs + noise * noise_mask
print K.eval(noised)
请注意,这并不能保证每张图像中的prob_noise
像素都会被噪声污染,这只能保持平均值。