Skip to contents

In Keras, all RNG-using methods (such as random_normal()) are stateless, meaning that if you pass an integer seed to them (such as seed = 42), they will return the same values at each call. In order to get different values at each call, you must use a SeedGenerator instead as the seed argument. The SeedGenerator object is stateful.

Usage

random_seed_generator(seed = NULL, name = NULL, ...)

Arguments

seed

Initial seed for the random number generator

name

String, name for the object

...

For forward/backward compatability.

Value

A SeedGenerator instance, which can be passed as the seed = argument to other random tensor generators.

Examples

seed_gen <- random_seed_generator(seed = 42)
values <- random_normal(shape = c(2, 3), seed = seed_gen)
new_values <- random_normal(shape = c(2, 3), seed = seed_gen)

Usage in a layer:

layer_dropout2 <- new_layer_class(
  "dropout2",
  initialize = function(...) {
    super$initialize(...)
    self$seed_generator <- random_seed_generator(seed = 1337)
  },
  call = function(x, training = FALSE) {
    if (training) {
      return(random_dropout(x, rate = 0.5, seed = self$seed_generator))
    }
    return(x)
  }
)

out <- layer_dropout(rate = 0.8)
out(op_ones(10), training = TRUE)

## tf.Tensor([0. 5. 5. 0. 0. 0. 0. 0. 0. 0.], shape=(10), dtype=float32)