Keras manages a global state, which it uses to implement the Functional model-building API and to uniquify autogenerated layer names.
If you are creating many models in a loop, this global state will consume
an increasing amount of memory over time, and you may want to clear it.
Calling clear_session()
releases the global state: this helps avoid
clutter from old models and layers, especially when memory is limited.
Example 1: calling clear_session()
when creating models in a loop
for (i in 1:100) {
# Without `clear_session()`, each iteration of this loop will
# slightly increase the size of the global state managed by Keras
model <- keras_model_sequential()
for (j in 1:10) {
model <- model |> layer_dense(units = 10)
}
}
for (i in 1:100) {
# With `clear_session()` called at the beginning,
# Keras starts with a blank state at each iteration
# and memory consumption is constant over time.
clear_session()
model <- keras_model_sequential()
for (j in 1:10) {
model <- model |> layer_dense(units = 10)
}
}
Example 2: resetting the layer name generation counter
layers <- lapply(1:10, \(i) layer_dense(units = 10))
new_layer <- layer_dense(units = 10)
print(new_layer$name)
clear_session()
new_layer <- layer_dense(units = 10)
print(new_layer$name)
See also
Other backend: config_backend()
config_epsilon()
config_floatx()
config_image_data_format()
config_set_epsilon()
config_set_floatx()
config_set_image_data_format()
Other utils: audio_dataset_from_directory()
config_disable_interactive_logging()
config_disable_traceback_filtering()
config_enable_interactive_logging()
config_enable_traceback_filtering()
config_is_interactive_logging_enabled()
config_is_traceback_filtering_enabled()
get_file()
get_source_inputs()
image_array_save()
image_dataset_from_directory()
image_from_array()
image_load()
image_smart_resize()
image_to_array()
layer_feature_space()
normalize()
pad_sequences()
set_random_seed()
split_dataset()
text_dataset_from_directory()
timeseries_dataset_from_array()
to_categorical()
zip_lists()