I’m having an issue when I try to load a model I just saved, let me show you the code.
I loaded a pretrained model
pretrained = tf.keras.applications.ResNet50(include_top = False,
input_shape = (224,224,3),
pooling = 'avg',
classes = 525,
weights = 'imagenet'
)
for layer in pretrained.layers: #configurar capas para no entrenar
layer.trainable = False
I creat my model based on the pretrained model
model = keras.Sequential()
model.add(pretrained)
model.add(keras.layers.Dense(512, activation = 'relu', name = 'capa_1'))
model.add(keras.layers.Dense(525, activation = 'softmax', name = 'capa_de_salida'))
I train the model and get a 90% accuracy
opt = keras.optimizers.Adam(learning_rate = 5.5e-05)
model.compile(optimizer = opt, loss = 'categorical_crossentropy', metrics = ['accuracy'])
history = model.fit(train_dataset,
epochs = 10,
validation_data = val_dor)
but once I save it and try to load it, it wont work
path_model = './ResNet50_trans_learning_final.keras'
model.save(path_model)
modelo2 = tf.keras.models.load_model(path_model, compile=False)
I get this
--------------------------------------------------------------------------
ValueError Traceback (most recent call last)
Cell In[102], line 5
1 model.save('ResNet50_trans_learning_final.keras')
3 path_model = './ResNet50_trans_learning_final.keras'
----> 5 modelo2 = tf.keras.models.load_model(path_model, compile=False)
6 # hay un problema causado por la capa flaten y nose pude leer
File /usr/local/lib/python3.11/dist-packages/keras/src/saving/saving_api.py:176, in load_model(filepath, custom_objects, compile, safe_mode)
173 is_keras_zip = True
175 if is_keras_zip:
--> 176 return saving_lib.load_model(
177 filepath,
178 custom_objects=custom_objects,
179 compile=compile,
180 safe_mode=safe_mode,
181 )
182 if str(filepath).endswith((".h5", ".hdf5")):
183 return legacy_h5_format.load_model_from_hdf5(filepath)
File /usr/local/lib/python3.11/dist-packages/keras/src/saving/saving_lib.py:155, in load_model(filepath, custom_objects, compile, safe_mode)
153 # Construct the model from the configuration file in the archive.
154 with ObjectSharingScope():
--> 155 model = deserialize_keras_object(
156 config_dict, custom_objects, safe_mode=safe_mode
157 )
159 all_filenames = zf.namelist()
160 if _VARS_FNAME + ".h5" in all_filenames:
File /usr/local/lib/python3.11/dist-packages/keras/src/saving/serialization_lib.py:711, in deserialize_keras_object(config, custom_objects, safe_mode, **kwargs)
709 with custom_obj_scope, safe_mode_scope:
710 try:
--> 711 instance = cls.from_config(inner_config)
712 except TypeError as e:
713 raise TypeError(
714 f"{cls} could not be deserialized properly. Please"
715 " ensure that components that are Python object"
(...)
719 f"nnconfig={config}.nnException encountered: {e}"
720 )
File /usr/local/lib/python3.11/dist-packages/keras/src/models/sequential.py:336, in Sequential.from_config(cls, config, custom_objects)
331 else:
332 layer = serialization_lib.deserialize_keras_object(
333 layer_config,
334 custom_objects=custom_objects,
335 )
--> 336 model.add(layer)
337 if (
338 not model._functional
339 and build_input_shape
340 and isinstance(build_input_shape, (tuple, list))
341 ):
342 model.build(build_input_shape)
File /usr/local/lib/python3.11/dist-packages/keras/src/models/sequential.py:117, in Sequential.add(self, layer, rebuild)
115 self._layers.append(layer)
116 if rebuild:
--> 117 self._maybe_rebuild()
118 else:
119 self.built = False
File /usr/local/lib/python3.11/dist-packages/keras/src/models/sequential.py:136, in Sequential._maybe_rebuild(self)
134 if isinstance(self._layers[0], InputLayer) and len(self._layers) > 1:
135 input_shape = self._layers[0].batch_shape
--> 136 self.build(input_shape)
File /usr/local/lib/python3.11/dist-packages/keras/src/layers/layer.py:224, in Layer.__new__.<locals>.build_wrapper(*args, **kwargs)
221 @wraps(original_build_method)
222 def build_wrapper(*args, **kwargs):
223 with backend.name_scope(obj.name, caller=obj):
--> 224 original_build_method(*args, **kwargs)
225 # Record build config.
226 signature = inspect.signature(original_build_method)
File /usr/local/lib/python3.11/dist-packages/keras/src/models/sequential.py:177, in Sequential.build(self, input_shape)
175 for layer in self._layers[1:]:
176 try:
--> 177 x = layer(x)
178 except NotImplementedError:
179 # Can happen if shape inference is not implemented.
180 # TODO: consider reverting inbound nodes on layers processed.
181 return
File /usr/local/lib/python3.11/dist-packages/keras/src/utils/traceback_utils.py:123, in filter_traceback.<locals>.error_handler(*args, **kwargs)
120 filtered_tb = _process_traceback_frames(e.__traceback__)
121 # To get the full stack trace, call:
122 # `keras.config.disable_traceback_filtering()`
--> 123 raise e.with_traceback(filtered_tb) from None
124 finally:
125 del filtered_tb
File /usr/local/lib/python3.11/dist-packages/keras/src/layers/input_spec.py:202, in assert_input_compatibility(input_spec, inputs, layer_name)
200 if spec.min_ndim is not None:
201 if ndim is not None and ndim < spec.min_ndim:
--> 202 raise ValueError(
203 f'Input {input_index} of layer "{layer_name}" '
204 "is incompatible with the layer: "
205 f"expected min_ndim={spec.min_ndim}, "
206 f"found ndim={ndim}. "
207 f"Full shape received: {shape}"
208 )
209 # Check dtype.
210 if spec.dtype is not None:
ValueError: Input 0 of layer "capa_de_salida" is incompatible with the layer: expected min_ndim=2, found ndim=1. Full shape received: (512,)```
I'm using this docker container, which comes with tensorflow 2.16.1
sudo docker run -it –rm -v ./:/tf/notebooks -p 8888:8888 –runtime=nvidia tensorflow/tensorflow:latest-gpu-jupyter
New contributor
Lesim Use is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.