Search code examples
pythonkerasnoiseuniform-distribution

How to add a noise with uniform distribution to input data in Keras?


I need to add quantization noise to my input data. I read often these kinds of noises are modeled as noise with uniform distribution.

I have an encoding/decoding network implemented with Keras (input data is time series raw data), there is a layer implemented in Keras with which you can add Gaussian noise (GaussianNoise layer), can I use this layer to create uniform noise?

If not, are there other implemented layers that I can use?


Solution

  • You can create your own layer as such,

    import tensorflow as tf
    
    class noiseLayer(tf.keras.layers.Layer):
    
        def __init__(self,mean,std):
            super(noiseLayer, self).__init__()
            self.mean = mean
            self.std  = std
    
        def call(self, input):
    
            mean = self.mean
            std  = self.std
    
            return input + tf.random.normal(tf.shape(input).numpy(), 
                                        mean = mean,
                                        stddev = std)
    
    X = tf.ones([10,10,10]) * 100
    Y = noiseLayer(mean = 0, std = 0.1)(X)
    

    This code works in the latest Tensorflow 2.0.