1

I'm having a problem similar to the one described here: ValueError: Unknown layer: Functional

import tensorflow as tf
model = tf.keras.models.load_model("model.h5")

which throws: ValueError: Unknown layer: Functional.

I'm pretty sure this is because the h5 file was saved in TF 2.3.0 and I'm trying to load it in 2.2.0. I'd rather not convert using tf 2.3.0 directly, and I'm hoping to find a way of manually fixing the h5py file itself, or passing the right custom object to the model loader. I've noticed that it seems like it's just an extra key wherever the config file is stored, e.g. https://github.com/tensorflow/tensorflow/issues/41929

The problem is, I'm not sure how to manually get rid of the Functional layer in the h5 file. Specifically, I've tried:

import h5py
f = h5py.File("model.h5",'r')
print(f['model_weights'].keys())

which gives:

 <KeysViewHDF5 ['concatenate_1', 'conv1d_3', 'conv1d_4', 'conv1d_5', 'dense_1', 'dropout_4', 'dropout_5', 'dropout_6', 'dropout_7', 'embedding_1', 'global_average_pooling1d_1', 'global_max_pooling1d_1', 'input_2']>

and I don't see the Functional layer anywhere. Where exactly is the config for the model stored in this file? E.g. I'm looking for something like {"class_name": "Functional", "config": {"name": "model", "layers":...}}

Question: is there a way I can manually edit the h5 file using h5py to get rid of the Functional layer?

Alternatively, can I pass a specific custom_obects={'Functiona':???} to the load_model function? I've tried {'Functional':tf.keras.models.Model} but that returns ('Keyword argument not understood:', 'groups') because I think it's trying to load a model into weights?

Alex R.
  • 1,397
  • 3
  • 18
  • 33
  • 1
    I'm facing the same issue, apparently there's no other solution than to use equal tensorflow versions. If you find other solution would be much appreciated. – Stack Oct 20 '20 at 18:02

2 Answers2

2

I had a similar problem. The only way I could solve it without changing the Tensorflow version and retraining the model is by building the model structure again using Keras API in TensorFlow 2.2.0 and then call:

model.load_weights(<h5 file>)

where the original h5 file was created using TensorFlow 2.3.0. If you already have the code that builds the model structure then this method should be relatively easy since all you have to do is replace load_model(<h5 file>) with the line above.

-1

Just change

keras.models import load_model
tensorflow.keras.models import load_model

then

load_model('model.h5', compile = False)
Timbus Calin
  • 13,809
  • 5
  • 41
  • 59
  • The comment does not answer to the question; the error comes from different versions of tensorflow, and keras is imported in both of them via tensorflow.keras, not tensorflow.keras vs keras – Timbus Calin Sep 04 '20 at 08:26