keras-team / keras

Deep Learning for humans
http://keras.io/
Apache License 2.0
61.69k stars 19.42k forks source link

ValueError when loading models that reuse weights #20307

Open K1521 opened 1 day ago

K1521 commented 1 day ago

if I create a model wich reuses layers I get a Error when trying to load it again.

import tensorflow as tf
from keras.models import load_model,save_model
from keras import layers

inputs = layers.Input(shape=(10,))
x=inputs

t=layers.Dense(10)
x = t(x)
x = layers.Dense(10)(x)
x = t(x)
model=tf.keras.Model(inputs, x)

model.summary()
save_model(model,'testmodel.keras')

model2=load_model('testmodel.keras')
model2.summary()

I also found out how to fix it: https://github.com/keras-team/keras/blob/d3671cf276d838599dd8acec9616845ac262d52a/keras/src/models/functional.py#L687C3-L690C56

This ValueError has to be a IndexError (like in the legacy case in the code above).

That way it can be caught here: https://github.com/keras-team/keras/blob/d3671cf276d838599dd8acec9616845ac262d52a/keras/src/models/functional.py#L517C1-L525C36

:)

mehtamansi29 commented 19 hours ago

Hi @K1521 -

Thanks for reporting this issue. Here While creating the model you can reuse the layer weight store in variable(t) t=layers.Dense(10) instead of declaring new layer x = layers.Dense(10)(x). Attached gist here for your reference.