I am reading the online TensorFlow Probability (TFP) version of "Bayesian Methods for Hackers".
But when I excecute the first cell of Ch2_MorePyMC_TFP.ipynb
the following error occurs:
AttributeError: module 'tensorflow' has no attribute 'contrib'
I suppose this version of "Bayesian Methods for Hackers" jupyter notebook was written for TF1.
Do you have an easy fix or a updated version of this jupyter notebook working with TF2 ?
Some of the contrib functions are removed and some of them are merged into TensorFlow core. You need to find the equivalent version of them.
import tensorflow as tf
import tensorflow_probability as tfp
tfd = tfp.distributions
tfb = tfp.bijectors
print(tf.__version__) # 2.5.0
print(tfp.__version__) # 0.12.1
For example first contrib functions are available in TensorFlow and can be re-written as:
parameter = tfd.Exponential(rate=1., name="poisson_param").sample()
rv_data_generator = tfd.Poisson(parameter, name="data_generator")
data_generator = rv_data_generator.sample()
data_generator_ = tf.nest.pack_sequence_as(
data_generator,
[t.numpy() if tf.is_tensor(t) else t
for t in tf.nest.flatten(data_generator)])
print("Value of sample from data generator random variable:", data_generator_)
For other TF Operations you can replace them like this:
with tf.compat.v1.variable_scope(tf.compat.v1.get_variable_scope(), reuse=tf.compat.v1.AUTO_REUSE):
step_size = tf.compat.v1.get_variable(
name='step_size',
initializer=tf.constant(0.5, dtype=tf.float32),
trainable=False,
use_resource=True
)
More info can be found in the documentation
Frightera, I have problems getting rid of the following error :
module 'tensorflow' has no attribute 'variable_scope'
at cell :
# Initialize the step_size. (It will be automatically adapted.)
with tf.variable_scope(tf.get_variable_scope(), reuse=tf.AUTO_REUSE):
step_size = tf.get_variable(
name='step_size',
initializer=tf.constant(0.5, dtype=tf.float),
trainable=False,
use_resource=True
)
Do you have any clue how to replace this one?
I'm trying to load a pretrained retinanet model with keras by running:
# import keras
import keras
# import keras_retinanet
from keras_retinanet import models
from keras_retinanet.utils.image import read_image_bgr, preprocess_image, resize_image
from keras_retinanet.utils.visualization import draw_box, draw_caption
from keras_retinanet.utils.colors import label_color
# set tf backend to allow memory to grow, instead of claiming everything
import tensorflow as tf
def get_session():
config = tf.ConfigProto()
config.gpu_options.allow_growth = True
return tf.Session(config=config)
model_path = os.path.join('sample_data/snapshots', sorted(os.listdir('sample_data/snapshots'), reverse=True)[0])
print(model_path)
# load retinanet model
model = models.load_model(model_path, backbone_name='resnet50')
model = models.convert_model(model)
I am facing the following error with both codes:
OSError: SavedModel file does not exist at: sample_data/snapshots/training_5000(640_480).h5/{saved_model.pbtxt|saved_model.pb}
the cause might be some new versions of Keras or tensorflow,
soo I am going to list the versions that I am currently using.
keras.__version__
2.4.3
tf.__version__
2.4.1
Note: I am trying to run this code in my Colab.
I am trying to build a NER model in Keras using ELMO Embeddings. SO I stumped across this tutorial and started implementing. I got lots of errors and some of them are as:
import tensorflow as tf
import tensorflow_hub as hub
from keras import backend as K
sess = tf.Session()
K.set_session(sess)
elmo_model = hub.Module("https://tfhub.dev/google/elmo/2", trainable=True)
sess.run(tf.global_variables_initializer())
sess.run(tf.tables_initializer())
def ElmoEmbedding(x):
return elmo_model(inputs={"tokens": tf.squeeze(tf.cast(x, tf.string)),
"sequence_len": tf.constant(batch_size*[max_len])},signature="tokens",as_dict=True)["elmo"]
input_text = Input(shape=(max_len,), dtype=tf.string)
embedding = Lambda(ElmoEmbedding, output_shape=(None, 1024))(input_text)
It gives me AttributeError: module 'tensorflow' has no attribute 'Session' . So if I comment out sess= code and run, it gives me AttributeError: module 'keras.backend' has no attribute 'set_session'.
Then again, Elmo code line is giving me RuntimeError: Exporting/importing meta graphs is not supported when eager execution is enabled. No graph exists when eager execution is enabled..
I have the following configurations:
tf.__version__
'2.3.1'
keras.__version__
'2.4.3'
import sys
sys.version
'3.8.3 (default, Jul 2 2020, 17:30:36) [MSC v.1916 64 bit (AMD64)]'
How can I use ELMO Embeddings in Keras Model?
You are using the old Tensorflow 1.x syntax but you have tensorflow 2 installed.
This is the new way to do elmo in TF2
Extracting ELMo features using tensorflow and convert them to numpy
I load a saved h5 model and want to save the model as pb.
The model is saved during training with the tf.keras.callbacks.ModelCheckpoint callback function.
TF version: 2.0.0a
edit: same issue also with 2.0.0-beta1
My steps to save a pb:
I first set K.set_learning_phase(0)
then I load the model with tf.keras.models.load_model
Then, I define the freeze_session() function.
(optional I compile the model)
Then using the freeze_session() function with tf.keras.backend.get_session
The error I get, with and without compiling:
AttributeError: module 'tensorflow.python.keras.api._v2.keras.backend'
has no attribute 'get_session'
My Question:
Does TF2 not have the get_session anymore?
(I know that tf.contrib.saved_model.save_keras_model does not exist anymore and I also tried tf.saved_model.save which not really worked)
Or does get_session only work when I actually train the model and just loading the h5 does not work
Edit: Also with a freshly trained session, no get_session is available.
If so, how would I go about to convert the h5 without training to pb? Is there a good tutorial?
Thank you for your help
update:
Since the official release of TF2.x graph/session concept has changed. The savedmodel api should be used.
You can use the tf.compat.v1.disable_eager_execution() with TF2.x and it will result in a pb file. However, I am not sure what kind of pb file type it is, as saved model composition changed from TF1 to TF2. I will keep digging.
I do save the model to pb from h5 model:
import logging
import tensorflow as tf
from tensorflow.compat.v1 import graph_util
from tensorflow.python.keras import backend as K
from tensorflow import keras
# necessary !!!
tf.compat.v1.disable_eager_execution()
h5_path = '/path/to/model.h5'
model = keras.models.load_model(h5_path)
model.summary()
# save pb
with K.get_session() as sess:
output_names = [out.op.name for out in model.outputs]
input_graph_def = sess.graph.as_graph_def()
for node in input_graph_def.node:
node.device = ""
graph = graph_util.remove_training_nodes(input_graph_def)
graph_frozen = graph_util.convert_variables_to_constants(sess, graph, output_names)
tf.io.write_graph(graph_frozen, '/path/to/pb/model.pb', as_text=False)
logging.info("save pb successfully!")
I use TF2 to convert model like:
pass keras.callbacks.ModelCheckpoint(save_weights_only=True) to model.fit and save checkpoint while training;
After training, self.model.load_weights(self.checkpoint_path) load checkpoint;
self.model.save(h5_path, overwrite=True, include_optimizer=False) save as h5;
convert h5 to pb just like above;
I'm wondering the same thing, as I'm trying to use get_session() and set_session() to free up GPU memory. These functions seem to be missing and aren't in the TF2.0 Keras documentation. I imagine it has something to do with Tensorflow's switch to eager execution, as direct session access is no longer required.
use
from tensorflow.compat.v1.keras.backend import get_session
in keras 2 & tensorflow 2.2
then call
import logging
import tensorflow as tf
from tensorflow.compat.v1 import graph_util
from tensorflow.python.keras import backend as K
from tensorflow import keras
from tensorflow.compat.v1.keras.backend import get_session
# necessary !!!
tf.compat.v1.disable_eager_execution()
h5_path = '/path/to/model.h5'
model = keras.models.load_model(h5_path)
model.summary()
# save pb
with get_session() as sess:
output_names = [out.op.name for out in model.outputs]
input_graph_def = sess.graph.as_graph_def()
for node in input_graph_def.node:
node.device = ""
graph = graph_util.remove_training_nodes(input_graph_def)
graph_frozen = graph_util.convert_variables_to_constants(sess, graph, output_names)
tf.io.write_graph(graph_frozen, '/path/to/pb/model.pb', as_text=False)
logging.info("save pb successfully!")
I'm unable to import this module
import keras.applications.resnet
ModuleNotFoundError
in ()
----> 1 import keras.applications.resnet
ModuleNotFoundError: No module named 'keras.applications.resnet'
keras resnet link
Keras team hasn't included resnet, resnet_v2 and resnext in the current module, they will be added from Keras 2.2.5, as mentioned here.
For a workaround, you can use keras_applications module directly to import all ResNet, ResNetV2 and ResNeXt models, as given below
from keras_applications.resnet import ResNet50
Or if you just want to use ResNet50
from keras.applications.resnet50 import ResNet50
Alternatively, you can always build from source as mentioned here.
try to use
from tensorflow.keras.applications.resnet50 import ResNet50
Found a workaround to use ResNeXt in Keras 2.2.4 here.
ResNeXt50() function needs 4 more arguments: backend, layers, models and utils.
import keras
from keras_applications.resnext import ResNeXt50
model = ResNeXt50(weights='imagenet',
backend=keras.backend,
layers=keras.layers,
models=keras.models,
utils=keras.utils)
In Keras there are multiple flavours of ResNet, you will have to specify the version of ResNet that you want e.g. You wish to load the ResNet50.
Use
from keras.applications import ResNet50
Edit 2 This is the list you get when you use dir() command on applications
['DenseNet121', 'DenseNet169', 'DenseNet201', 'InceptionResNetV2', 'InceptionV3', 'MobileNet', 'MobileNetV2', 'NASNetLarge', 'NASNetMobile', 'ResNet50', 'VGG16', 'VGG19', 'Xception', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__path__', '__spec__', 'absolute_import', 'backend', 'densenet', 'division', 'inception_resnet_v2', 'inception_v3', 'keras_applications', 'keras_modules_injection', 'layers', 'mobilenet', 'mobilenet_v2', 'models', 'nasnet', 'print_function', 'resnet50', 'utils', 'vgg16', 'vgg19', 'xception'], the models visible here can be laoded like this, There are some models like ResNet101 missing here, let me see if I can come up with a way to fix this.
Edit Proof that this works too
To see all the available versions of the Resnet models, visit https://keras.io/applications/#resnet
There is a python package named 'keras-resnet' which has ResNet50, ResNet101, ResNet152 and many more variants of ResNet. (https://pypi.org/project/keras-resnet/)
Installation is also quite easy. Just type
pip install keras-resnet
It will install this module and then use it like:
from keras_resnet.models import ResNet50, ResNet101, ResNet152
backbone = ResNet50(inputs=image_input, include_top=False, freeze_bn=True)
C2, C3, C4, C5 = backbone.outputs # this will give you intermediate
# outputs of four blocks of resnet if you want to merge low and high level features
I am using backbones from this module and is working fine for me!
Check the versions:
pip list | grep Keras
If it's already installed, uninstall and upgrade:
pip uninstall Keras
pip install Keras==2.3.1
pip uninstall Keras-Applications
pip install Keras-Applications==1.0.8
pip uninstall Keras-Preprocessing
pip install Keras-Preprocessing==1.1.0
from keras.applications.resnet
import ResNet101
tf.keras.backend.clear_session
model=VGG19()
model.summary()
tf.keras.utils.plot_model(model,show_shapes=True)
visualkeras.layered_view(model,legend=True)
Before running
tensorflow.keras.applications.resnet50 import ResNet50
you need to run
from tensorflow import keras