<br />

|---|
| [![](https://www.tensorflow.org/images/GitHub-Mark-32px.png) View source on GitHub](https://github.com/keras-team/keras/tree/v3.15.1/keras/src/backend/common/global_state.py#L24-L98) |

Resets all state generated by Keras.

#### View aliases


**Main aliases**

[`tf.keras.utils.clear_session`](https://www.tensorflow.org/api_docs/python/tf/keras/backend/clear_session)

<br />

    tf.keras.backend.clear_session(
        free_memory=True
    )

### Used in the notebooks

| Used in the guide | Used in the tutorials |
|---|---|
| - [Estimators](https://www.tensorflow.org/guide/estimator) | - [Transfer learning for video classification with MoViNet](https://www.tensorflow.org/tutorials/video/transfer_learning_with_movinet) - [Classifying CIFAR-10 with XLA](https://www.tensorflow.org/xla/tf2xla/tutorials/autoclustering_xla) - [Graph regularization for sentiment classification using synthesized graphs](https://www.tensorflow.org/neural_structured_learning/tutorials/graph_keras_lstm_imdb) - [Graph regularization for document classification using natural graphs](https://www.tensorflow.org/neural_structured_learning/tutorials/graph_keras_mlp_cora) |

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.

<br />

<br />

<br />

| ## Args ||
|---|---|
| `free_memory` | Whether to call Python garbage collection. It's usually a good practice to call it to make sure memory used by deleted objects is immediately freed. However, it may take a few seconds to execute, so when using `clear_session()` in a short loop, you may want to skip it. |

<br />

Example 1: calling `clear_session()` when creating models in a loop

    for _ in range(100):
      # Without `clear_session()`, each iteration of this loop will
      # slightly increase the size of the global state managed by Keras
      model = keras.Sequential([
          keras.layers.Dense(10) for _ in range(10)])

    for _ in range(100):
      # With `clear_session()` called at the beginning,
      # Keras starts with a blank state at each iteration
      # and memory consumption is constant over time.
      keras.backend.clear_session()
      model = keras.Sequential([
          keras.layers.Dense(10) for _ in range(10)])

Example 2: resetting the layer name generation counter

    layers = [keras.layers.Dense(10) for _ in range(10)]
    new_layer = keras.layers.Dense(10)
    print(new_layer.name)
    dense_10
    keras.backend.clear_session()
    new_layer = keras.layers.Dense(10)
    print(new_layer.name)
    dense