Issue with setting TensorFlow as the session in Keras

18.8k Views Asked by At

Performing the following:

from keras import backend as K
sess = tf.Session()
K.set_session(sess)

Even though I've imported Keras and TensorFlow correctly, I get the following:

module 'keras.backend' has no attribute 'set_session'

Any help would be appreciated!

5

There are 5 best solutions below

0
On

I think you need this :

from keras.backend.tensorflow_backend import set_session

Use it like this :

from keras import backend as K
K.tensorflow_backend.set_session(sess)

Works fine for me

0
On

Try this,

import tensorflow as tf
from tensorflow import keras
from tensorflow.python.keras.callbacks import ModelCheckpoint

# Set the config values 
config = tf.ConfigProto(intra_op_parallelism_threads=<NUM_PARALLEL_EXEC_UNITS>, 
inter_op_parallelism_threads=2, allow_soft_placement=True, device_count = {'CPU': 
<NUM_PARALLEL_EXEC_UNITS> })

#Create the session
session = tf.Session(config=config)
tf.keras.backend.set_session(session)
0
On

This will also work for tensorflow 2.0.0

import tensorflow.keras.backend as K
cfg = tf.compat.v1.ConfigProto()
0
On

Just to add to previous answers, unless you want to specify what GPU Tensorflow needs to use, you do not need to define what GPU to run. As it is written here, Tensorflow will by default use a GPU available.

0
On

Requires .compat.v1. after the tf

Example:

tf.compat.v1.keras.backend.set_session(tf.compat.v1.Session(config=config));

(Tested in Anaconda, Python 3.7, tensorflow 2.0.0)