apply additive zerocentered gaussian noise this is useful to mitigate overfitting you could see it as a form of random data augmentation gaussian noise gs is a natural choice as corruption process for real valued inputs as it is a regularization layer it is only active at training time args stddev float standard deviation of the noise distribution seed integer optional random seed to enable deterministic behavior call arguments inputs input tensor of any rank training python boolean indicating whether the layer should behave in training mode adding noise or in inference mode doing nothing apply additive zero centered gaussian noise this is useful to mitigate overfitting you could see it as a form of random data augmentation gaussian noise gs is a natural choice as corruption process for real valued inputs as it is a regularization layer it is only active at training time args stddev float standard deviation of the noise distribution seed integer optional random seed to enable deterministic behavior call arguments inputs input tensor of any rank training python boolean indicating whether the layer should behave in training mode adding noise or in inference mode doing nothing
from keras import backend
from keras import layers
from keras import ops
from keras.api_export import keras_export


@keras_export("keras.layers.GaussianNoise")
class GaussianNoise(layers.Layer):
    

    def __init__(self, stddev, seed=None, **kwargs):
        super().__init__(**kwargs)
        if not 0 <= stddev <= 1:
            raise ValueError(
                f"Invalid value received for argument "
                "`stddev`. Expected a float value between 0 and 1. "
                f"Received: stddev={stddev}"
            )
        self.stddev = stddev
        self.seed = seed
        self.seed_generator = backend.random.SeedGenerator(seed)
        self.supports_masking = True

    def call(self, inputs, training=False):
        if training and self.stddev > 0:
            return inputs + backend.random.normal(
                shape=ops.shape(inputs),
                mean=0.0,
                stddev=self.stddev,
                seed=self.seed_generator,
            )
        return inputs

    def compute_output_shape(self, input_shape):
        return input_shape

    def get_config(self):
        base_config = super().get_config()
        config = {
            "stddev": self.stddev,
            "seed": self.seed,
        }
        return {**base_config, **config}