首先利用modelcheckpoint保存模型:
from tensorflow.keras.callbacks import TensorBoard
logdir = './graph_def_and_weights'
if not os.path.exists(logdir):
os.mkdir(logdir)
output_model_file = os.path.join(logdir,"fashion_mnist_model.h5")
callbackslist=[keras.callbacks.TensorBoard(logdir),
keras.callbacks.ModelCheckpoint(output_model_file,
ave_best_only=True,
save_weights_only=False
#False代表模型参数和结构都保存
),
keras.callbacks.EarlyStopping(patience=5, min_delta=1e-3),
]
保存后载入模型
output_model_file = "./graph_def_and_weights/fashion_mnist_model.h5"
loaded_model = keras.models.load_model(output_model_file)
loaded_model.evaluate(x_test_scaled,y_test)
当 save_weights_only=True的时候,同样的载入模型就会报错
说明只有参数值,并没有保存的参数,所以要预定义好模型
from tensorflow.keras.callbacks import TensorBoard
logdir = './graph_def_and_weights'
if not os.path.exists(logdir):
os.mkdir(logdir)
output_model_file = os.path.join(logdir,"fashion_mnist_weights.h5")
# 加载参数
model.load_weights(output_model_file)
另一种特别简单:
model.save_weights(os.path.join(logdir, "fashion_mnist_weights_2.h5"))
下面!!!!!!!
把kears模型和迁移学习模型转化成savedmodel并且调用
# 保存模型(自己生成路径?)
tf.saved_model.save(model,"./keras_saved_graph")
# 查看测试模型
# saved_model_cli show --dir ./keras_saved_graph --all
loaded_saved_model = tf.saved_model.load('./keras_saved_graph')
inference = loaded_saved_model.signatures['serving_default']
results = inference(tf.constant(x_test_scaled[0:1]))
print(results['dense_2'])