在Tensorflow2中保存权重和模型的方法有三种
第一种为仅保存weights与bias的方式
#1.保存权重和偏移量参数值 save_weights / load_weights
path = "./checkpoints/mycheck"
#保存weights & bias
model.save_weights(path)
#重新读取训练好的权重,在模型中使用的时候,需要重新构建模型
model.load_weights("weights.ckpt")
del model
model = tf.keras.Sequential([
tf.keras.layers.Dense(256,activation=tf.nn.leaky_relu),
tf.keras.layers.Dense(128,activation=tf.nn.leaky_relu),
tf.keras.layers.Dense(64,activation=tf.nn.leaky_relu),
tf.keras.layers.Dense(32,activation=tf.nn.leaky_relu),
tf.keras.layers.Dense(10),
])
model.build(input_shape=[None,784])
model.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=0.001),loss=tf.keras.losses.CategoricalCrossentropy(from_logits=True),metrics=['accuracy'])
model.fit(data_train,validation_data=data_test,validation_freq=2,epochs=10)
model.evaluate(data_test)
model.evaluate()
第二种为保存整个模型的方式
#2.保存整个模型 save / load_model
model.save("model.h5")
del model
model = tf.keras.models.load_model("model.h5")
model.evaluate()
第三种为工业级部署方式
#3.保存整个模型(工业级部署) saved_model
tf.saved_model.save(model,"./log/models")
model = tf.saved_model.load("./log/models")
f = model.signatures["serving_default"]
# model.build()
# model.compile()
# model.fit()
# model.evaluate()
# model.signatures()
print(f)