Sequential模式
from tensorflow import keras
sequential_model = keras.Sequential(
[
keras.Input(shape=(784,), name="digits"),
keras.layers.Dense(64, activation="relu", name="dense_1"),
keras.layers.Dense(64, activation="relu", name="dense_2"),
keras.layers.Dense(10, name="predictions"),
]
)
sequential_model.save_weights("weights.h5")
# sequential_model.load_weights("weights.h5")
Netron显示的
改为sequential_model.save("weights.h5")
显示拓扑如下
子类模式
import tensorflow as tf
from tensorflow import keras
class CustomModel(keras.Model):
def __init__(self, hidden_units):
super(CustomModel, self).__init__()
self.dense_layers = [keras.layers.Dense(u) for u in hidden_units]
self._set_inputs(
tf.TensorSpec([None, 5], tf.float32, name="inputs"))
def call(self, inputs):
x = inputs
for layer in self.dense_layers:
x = layer(x)
return x
model = CustomModel([16, 16, 10])
# Build the model by calling it
input_arr = tf.random.uniform((1, 5))
outputs = model(input_arr)
model.save("my_model")
//model.save("my_model.ckpt")
pb文件:The model architecture, and training configuration (including the optimizer, losses, and metrics) are stored in saved_model.pb. The weights are saved in the variables/ directory.
index:
子类模型无法序列化,无法转出tf1版本的pb模型,否则出问题
NotImplementedError: Saving the model to HDF5 format requires the model to be a Functional model or a Sequential model. It does not work for subclassed models, because such models are defined via the body of a Python method, which isn't safely serializable. Consider saving to the Tensorflow SavedModel format (by setting save_format="tf") or using `save_weights`.
Keras.Model
class MyModel(Model):
def __init__(self):
super(MyModel, self).__init__()
self.conv1 = Conv2D(32, 3, activation='relu')
self.conv2 = Conv2D(64, 3, activation='relu')
self.conv3 = Conv2D(128, 3, activation='relu')
self.flatten = Flatten()
self.d1 = Dense(128, activation='relu')
self.d2 = Dense(10, activation='softmax')
self._set_inputs(
tf.TensorSpec([None, 28, 28, 1], tf.float32, name="inputs"))
@tf.function
def call(self, x):
x = self.conv1(x)
x = self.conv2(x)
x = self.conv3(x)
# x = self.conv4(x)
x = self.flatten(x)
x = self.d1(x)
return self.d2(x)
# Create an instance of the model
model = MyModel()
model.save('sdsd1',save_format='tf')
model.save_weights('sdsd1',save_format='tf')
(2)
inputs = keras.Input(shape=(784,), name="digits")
x = keras.layers.Dense(64, activation="relu", name="dense_1")(inputs)
x = keras.layers.Dense(64, activation="relu", name="dense_2")(x)
outputs = keras.layers.Dense(10, name="predictions")(x)
functional_model = keras.Model(inputs=inputs, outputs=outputs, name="3_layer_mlp")
该模型只能保存为tf格式,无法保存为H5格式。