Creé un modelo de secuencial. cuando lo guardé, recibí este mensaje de advertencia
home/anaconda3/lib/python3.8/site-packages/tensorflow/python/keras/utils/generic_utils.py:494: CustomMaskWarning: Custom mask layers require a config and must override get_config. When loading, the custom mask layer must be passed to the custom_objects argument. warnings.warn('Custom mask layers require a config and must overrideProbé una imagen y la predicción fue buena, guardé mi modelo cuando lo cargué nuevamente, comenzó a darme valores incorrectos y la predicción fue incorrecta. ¿Cuál es la forma correcta de decir el modelo y cargarlo?
import numpy as np import matplotlib.pyplot as plt import glob import cv2 import os from tensorflow import keras from tensorflow.keras.layers import Conv2D, MaxPooling2D from tensorflow.keras.layers import Input, Dropout, Flatten, Dense from tensorflow.keras.layers import UpSampling2D from tensorflow.keras.models import Model from tensorflow.keras.layers import BatchNormalization from tensorflow.keras.models import Sequential input_shape = (3,1134,1134,3) base_model = tf.keras.applications.ResNet50( include_top=False, weights="imagenet", input_shape=(1134,1134,3), pooling=max, ) for layer in base_model.layers[:-4]: layer.trainable = False model = Sequential() model.add(Conv2D(3,(3,3),activation='relu',padding='same')) model.add(base_model) model.add(Conv2D(3,(3,3),activation='relu',padding='same')) # model.add(Convolution2D(3,(4,4),activation='relu',padding='same')) model.add(UpSampling2D(size =(16,16))) model.add(UpSampling2D()) model.add(BatchNormalization()) model.add(Conv2D(3,(3,3),activation='relu',padding='same')) model.build(input_shape) model.summary()asi lo guardo
model.save("/media/TOSHIBA EXT/trained_model/UAV_01.h5") enter code here model=keras.models.load_model( "/media/TOSHIBA EXT/trained_model/UAV_01.h5")@user123 Estoy de acuerdo con usted en que era un problema con las versiones anteriores (de TF2.5, TF2.6 y TF2.7).
Esto se resolvió en tf-nightly reciente. Aquí hay una esencia como referencia. Si desea utilizar una versión estable, estará disponible en el próximo TF2.8 en un futuro próximo. ¡Gracias!
Otros dos enfoques para probar:
.h5 . Bajo el capó, save hace cosas diferentes si envía una ruta que termina con .h5 . Si envía un directorio, utilizará el formato de modelo guardado más nuevo. A continuación, puede cargar directamente el modelo con: from tensorflow.keras.models import load_model new_model = load_model('<path to directory used in save>')https://www.tensorflow.org/guide/saved_model#the_savedmodel_format_on_disk
model.save_weights('my_model_weights.h5') ... new_model = <build your model with your model building code> new_model.load_weights('my_model_weights.h5')Ref: https://keras.io/getting_started/faq/ . Pesos solo ahorro
En las preguntas frecuentes, también hay varias otras sugerencias sobre cómo manejarlo, pero para su situación, estos dos probablemente lo cubrirán.
Aquí hay un buen fragmento para agregar después de su código de entrenamiento para asegurarse de que la exportación funcione y no sea la causa de un problema de rendimiento en la inferencia:
# From: https://www.tensorflow.org/guide/keras/save_and_serialize#whole-model_saving_loading # Train the model. test_input = np.random.random((128, 32)) test_target = np.random.random((128, 1)) model.fit(test_input, test_target) # Calling `save('my_model')` creates a SavedModel folder `my_model`. model.save("my_model") # It can be used to reconstruct the model identically. reconstructed_model = keras.models.load_model("my_model") # Let's check: np.testing.assert_allclose( model.predict(test_input), reconstructed_model.predict(test_input) ) # The reconstructed model is already compiled and has retained the optimizer # state, so training can resume: reconstructed_model.fit(test_input, test_target)