Przemysław
Przemysław

Reputation: 1

Why function model.predict() doesn't free RAM memory?

Function model.predict() doesn't free it's memory. Every literation of loop it takes more and more RAM.Im trying that on Ubuntu 22.04 with Conda env.

Keras model is created via teachablemachine from google.

Thanks!

Here is my code:

import keras # TensorFlow is required for Keras to work
import cv2  # Install opencv-python
import numpy as np

np.set_printoptions(suppress=True)


model = keras.models.load_model('ml_files/model_lid.h5',compile=False)

camera = cv2.VideoCapture(2)

while True:
    ret, image = camera.read()

    image = cv2.resize(image, (224, 224), interpolation=cv2.INTER_AREA)

    cv2.imshow("Webcam Image", image)

    image = np.asarray(image, dtype=np.float32).reshape(1, 224, 224, 3)

    image = (image / 127.5) - 1

    model.predict(image)

    keyboard_input = cv2.waitKey(1)

    if keyboard_input == 27:
        break
 
    del image

    keras.backend.clear_session()


camera.release()
cv2.destroyAllWindows()

When I comment model.predict(), RAM is stable. Even keras.backend.clear_session() can't clear that.

Upvotes: 0

Views: 221

Answers (1)

delirium78
delirium78

Reputation: 614

This was a struggle for me as well. A few thing you could try:

  1. use garbage collection after each call with gc.collect()
  2. Call the prediction with model(image, training=False)

Upvotes: 0

Related Questions