Sound way of managing multiple sessions and graphs

前端 未结 1 1951
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-23 14:48

I\'d like to manage multiple Keras models in multiple sessions. My application is constructed such that models can be live at the same time, in addition to creating, saving and

1条回答
  •  北恋
    北恋 (楼主)
    2021-01-23 15:17

    EDIT: Actually, seeing again how K.get_session() works, it should return the current default session, so I'm not sure set_session is doing anything meaningful there. I'll leave the answer just in case you want to try but probably this won't help.


    Maybe you can get it to work with something like this:

    from contextlib import contextmanager
    
    class NN:
        def __init__(self):
            self.graph = tf.Graph()
            self.session = tf.Session(graph=self.graph)
    
        def predict(self, x):
            with self._context():
                return self.model.predict(x)
    
        @contextmanager
        def _context(self):
            prev_sess = K.get_session()
            K.set_session(self.session)
            with self.graph.as_default(), self.session.as_default():
                yield
            K.set_session(prev_sess)
    

    Note that the Keras session object is a global variable, so I suppose this should work as long as you don't try to use these contexts from multiple threads.

    0 讨论(0)
提交回复
热议问题