title: How to free GPU memory from keras model?
body: <p>I'm loading a keras model that I previously trained, to initialize another network with his weights. Unfortunately, the model I load fills my entire memory making the training of the new model impossible. Here is the code :</p>
  
  <pre><code>import gc
  import keras
  from keras.models import model_from_json
  
  def loadModel (path, loss=None, optimizer=None):
      with open(path + '/model.json', 'r') as f:
          model = model_from_json(f.read())
      model.load_weights(path + '/model.h5')
      if loss and optimizer:
          model.compile(loss=loss, optimizer=optimizer)
      return model
  
  model = loadModel('the/path/to/my/model')
  
  # The GPU memory is filled
  
  keras.backend.clear_session()
  
  # memory still filled
  
  del model
  gc.collect()
  
  # memory still filled
  </code></pre>
  
  <p>I checked multiple posts, and usually <code>gc.collect()</code> or <code>clear_session()</code> does the trick, but for me, it doesn't work so far. Any idea?</p>
  
  <p><strong>PS:</strong> I'm using tensorflow as backend.</p>