# How to optimize useless tensors in memory

**URL:** <https://discuss.ai.google.dev/t/how-to-optimize-useless-tensors-in-memory/28145>\
**Category:** General Discussion\
**Tags:** keras, tensorflow, memory, help\_request\
**Created:** [June 28, 2022, 6:34am UTC](https://discuss.ai.google.dev/t/how-to-optimize-useless-tensors-in-memory/28145 "2022-06-28T06:34:55Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![jun\_yin](https://d1dlmcr85iqnpo.cloudfront.net/user_avatar/discuss.ai.google.dev/jun_yin/32/9610_2.png) [@jun\_yin](https://discuss.ai.google.dev/u/jun_yin)\
**Post date:** [June 28, 2022, 6:34am UTC](https://discuss.ai.google.dev/t/how-to-optimize-useless-tensors-in-memory/28145/1 "2022-06-28T06:34:55Z")

</div>

During the process of using tensor, I find that I seem to waste too much memory. A large number of reshapes and numpy to tensor, and tensor to numpy without clearing the memory seem to be a burden to my program. How can I clean up these useless tensors? Just set them to none?

---

<div class="post-metadata">

**Author:** ![Aniket\_Dubey](https://d1dlmcr85iqnpo.cloudfront.net/user_avatar/discuss.ai.google.dev/aniket_dubey/32/16664_2.png) [@Aniket\_Dubey](https://discuss.ai.google.dev/u/Aniket_Dubey)\
**Post date:** [July 16, 2024, 5:46am UTC](https://discuss.ai.google.dev/t/how-to-optimize-useless-tensors-in-memory/28145/3 "2024-07-16T05:46:19Z")

</div>

Hi @jun_yin ,

Here are some strategies to help manage memory more effectively when working with TensorFlow,

1. Explicit garbage collection:Python’s garbage collector usually handles memory management, but you can explicitly call it.
2. Using `tf.keras.backend.clear_session()`: This function clears the current TensorFlow graph and free up memory.
3. Use `with` statements for temporary tensors: It automatically manage resources like tensors. The resources are automatically released when the context exits.
4. Use `tf.function` for better performance: This can help reduce memory usage by optimizing operations.
5. Control Memory Growth : If you are using a GPU, you can set memory growth to prevent TensorFlow from consuming all the available GPU memory at once.

Hope This Helps ,

Thank You .
