18

I'm new to keras and tensorflow. When I write programs with tensorflow, I must bulid a session to run the graph. However, when I use keras, although the backend is obviously tensorflow, I don't see session in the keras code. It seems all thing is done after the model.compile and model.fit.

So, how does Keras work? where is the tensorflow session? and instead of session, can I use eager execution with keras?

Thanks in advance and sorry for my English

LinTIna
  • 481
  • 1
  • 6
  • 14

1 Answers1

19

Keras doesn't directly have a session because it supports multiple backends. Assuming you use TF as backend, you can get the global session as:

from keras import backend as K
sess = K.get_session()

If, on the other hand, yo already have an open Session and want to set it as the session Keras should use, you can do so via:

K.set_session(sess)
GPhilo
  • 18,519
  • 9
  • 63
  • 89
  • What happens if I use `tf.Session()` instead of `tf.keras.backend.get_session()`. Since, I'm using `tensorflow.keras`, shouldn't it be the same? also `tf.get_default_session`. – aspiring1 Mar 28 '20 at 16:14
  • 1
    (Note: we're talking about TF 1.X, in 2.X Sessions do not exist anymore) tf.Session creates a new Session instance, it doesn't return you the one Keras uses. As per the get_default_session, it might work if you never changed Keras' session, but it's not guaranteed to be the same – GPhilo Mar 28 '20 at 16:30
  • I am using `tf.Session`, before loading the `keras` model from the disk, so won't `tf.keras` end up using that session instance? Also, can you explain _As per the get_default_session, it might work if you never changed Keras' session, but it's not guaranteed to be the same_ – aspiring1 Mar 28 '20 at 16:36
  • Won't Keras use the instance you create? I'd say likely no, but I can't be certain of it right now. For the second part of the comment, in my answer (second half) I show you how to set a specific session as the Keras one. Unless you manually set the session that way, Keras will use its default one. Whether this is "the" TF default session, I do not know, you'll have to check that – GPhilo Mar 28 '20 at 16:47
  • 1
    With my experiments, I see as you said `tf.Session()` creates a new session everytime it is called upon, and `tf.keras.backend.get_session()` is different from this, but it's strange that for `tf.get_default_session()` returns `None` always, can't understand why. – aspiring1 Mar 28 '20 at 20:28