tensorflow: keras.models.load_model() fails when the model uses a keras.losses.Loss subclass
System information
- Have I written custom code (as opposed to using a stock example script provided in TensorFlow): Yes
- OS Platform and Distribution (e.g., Linux Ubuntu 16.04): Mac OS X 10.13.6
- Mobile device (e.g. iPhone 8, Pixel 2, Samsung Galaxy) if the issue happens on mobile device: N/A
- TensorFlow installed from (source or binary): binary
- TensorFlow version (use command below): tf.version.VERSION: ‘2.0.0-dev20190220’ tf.version.GIT_VERSION: ‘v1.12.0-8385-gaaef4e8e43’
- Python version: 3.6.8
- Bazel version (if compiling from source): N/A
- GCC/Compiler version (if compiling from source): N/A
- CUDA/cuDNN version: N/A
- GPU model and memory: N/A
Describe the current behavior
keras.models.load_model()
raises a ValueError
when the model to be loaded uses a keras.losses.Loss
subclass, such as keras.losses.Huber
.
Describe the expected behavior Should load normally, and I should be able to continue training where it left off using the loss.
Code to reproduce the issue
import tensorflow as tf
from tensorflow import keras
X_train = np.random.randn(100, 2)
y_train = np.random.randn(100, 1)
model = keras.models.Sequential([keras.layers.Dense(1, input_dim=2)])
model.compile(loss=keras.losses.Huber(2.0), optimizer="sgd")
model.fit(X_train, y_train, epochs=2)
model.save("my_model.h5")
model = keras.models.load_model("my_model.h5") # Raises a ValueErro
Other info / logs Here is the stacktrace:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/ageron/.virtualenvs/tf2/lib/python3.6/site-packages/tensorflow/python/keras/saving/hdf5_format.py", line 248, in load_model
sample_weight_mode=sample_weight_mode)
File "/Users/ageron/.virtualenvs/tf2/lib/python3.6/site-packages/tensorflow/python/training/tracking/base.py", line 456, in _method_wrapper
method(self, *args, **kwargs)
File "/Users/ageron/.virtualenvs/tf2/lib/python3.6/site-packages/tensorflow/python/keras/engine/training.py", line 281, in compile
loss, self.output_names)
File "/Users/ageron/.virtualenvs/tf2/lib/python3.6/site-packages/tensorflow/python/keras/engine/training_utils.py", line 1142, in prepare_loss_functions
'following keys: {}'.format(name, output_names))
ValueError: Unknown entry in loss dictionary: class_name. Only expected following keys: ['dense']
I did some debugging, and I think I found the origin of the problem. In hdf5_format.py
, around line 233, the following lines use convert_custom_objects()
, but they should be using losses.deserialize()
and metrics.deserialize()
. I’ll send a PR.
# Recover loss functions and metrics.
loss = convert_custom_objects(training_config['loss'])
metrics = convert_custom_objects(training_config['metrics'])
weighted_metrics = convert_custom_objects(
training_config.get('weighted_metrics', None))
About this issue
- Original URL
- State: closed
- Created 5 years ago
- Reactions: 6
- Comments: 15 (3 by maintainers)
i find the reason, in my code: loss_object=tf.losses.SparseCategoricalCrossentropy() model.complie(loss=loss_object, optimizer=“sgd”)
it raise the error.
the i change my code to model.complie(loss=“sparse_categorical_crossentropy”, optimizer=“sgd”)
it is ok
Same issue on the stable 2.0.0 release 😦
This is fixed TF 2.0 nightly ‘2.0.0-dev20190718’ Thanks!
Hi there, I am still seeing the same issue.
Below is my model code.
After successfully train and save the model, I come across with ‘Unknown entries in loss dictionary’ error. Full error message as follows:
Anyone can help?
I am using tf.version=‘2.0.0’ on Ubuntu 16.6.
Can confirm changing the loss function to a string removes this error.