这个部分讲了三种方法
第一种是只保存模型参数
(剧透一下,只有这个成功了)
这个方法只保留参数,
因此导入的时候要先正常把模型先搭建好,compile完了再把参数赋予给模型
第二个方法,使用model.save方法保存整个模型
用这个方法保存的时候发现不可以用,原因是我的这个网络不是Functional model or a Sequential model。可能是因为我的网络里有自定义层?anyway,前面那个方法能用问题就不大了。
第三个方法是保存为saved_model形式。
据说这个形式适合工业化,适合把模型交付给其他的语言使用。
但是我运行的时候也有点问题,我怀疑是用到的signatures方法没有导入还是啥的,报错是这个
同样,因为有第一个方法兜底,以后有需要用到这个第三种方法的时候再去debug吧!
下面照例贴代码
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import datasets, layers, optimizers, Sequential, metrics
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
def preprocess(x, y):
"""
x is a simple image, not a batch
"""
x = tf.cast(x, dtype=tf.float32) / 255.
x = tf.reshape(x, [28 * 28])
y = tf.cast(y, dtype=tf.int32)
y = tf.one_hot(y, depth=10)
return x, y
batchsz = 128
(x, y), (x_val, y_val) = datasets.mnist.load_data()
print('datasets:', x.shape, y.shape, x.min(), x.max())
db = tf.data.Dataset.from_tensor_slices((x, y))
db = db.map(preprocess).shuffle(60000).batch(batchsz)
ds_val = tf.data.Dataset.from_tensor_slices((x_val, y_val))
ds_val = ds_val.map(preprocess).batch(batchsz)
sample = next(iter(db))
print(sample[0].shape, sample[1].shape)
class MyDense(layers.Layer):
def __init__(self, inp_dim, outp_dim):
super(MyDense, self).__init__()
self.kernel = self.add_variable('w', [inp_dim, outp_dim])
self.bias = self.add_variable('b', [outp_dim])
def call(self, inputs, training = None):
out = inputs @ self.kernel + self.bias
return out
class MyModel(keras.Model):
def __init__(self):
super(MyModel, self).__init__()
self.fc1 = MyDense(28*28, 256)
self.fc2 = MyDense(256, 128)
self.fc3 = MyDense(128, 64)
self.fc4 = MyDense(64, 32)
self.fc5 = MyDense(32, 10)
def call(self, inputs, training=None):
x = self.fc1(inputs)
x = tf.nn.relu(x)
x = self.fc2(x)
x = tf.nn.relu(x)
x = self.fc3(x)
x = tf.nn.relu(x)
x = self.fc4(x)
x = tf.nn.relu(x)
x = self.fc5(x)
return x
network = MyModel()
network.build(input_shape=(None, 28 * 28))
network.summary()
network.compile(optimizer=optimizers.Adam(lr=0.01),
loss=tf.losses.CategoricalCrossentropy(from_logits=True),
metrics=['accuracy'] # test
)
network.fit(db, epochs=10, validation_data=ds_val, validation_freq=2)
network.evaluate(ds_val)
sample = next(iter(ds_val))
x = sample[0]
y = sample[1] # one-hot
pred = network.predict(x) # [b, 10]
# convert back to number
y = tf.argmax(y, axis=1)
pred = tf.argmax(pred, axis=1)
print(pred)
print(y)
#第一种方法
#save the weights
network.save_weights('/home/bluecai/pyproject/checkpoints/my_checkpoint')
#restore the weights
reload_model = MyModel()
reload_model.load_weights('/home/bluecai/pyproject/checkpoints/my_checkpoint')
reload_model.compile(optimizer=optimizers.Adam(lr=0.01),
loss=tf.losses.CategoricalCrossentropy(from_logits=True),
metrics=['accuracy'] # test
)
loss, acc = reload_model.evaluate(ds_val)
print("restored model, accuracy: {:5.2f}%".format(100*acc))
#第二种方法
#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`.
# network.save('saved_network.h5')
# print('saved total model.')
#
# print('load model from file')
# reload_model_2 = tf.keras.models.load_model('saved_network.h5')
# loss_2, acc_2 = reload_model_2.evaluate(ds_val)
# print("restored model_2, accuracy: {:5.2f}%".format(100*acc_2))
#第三种方法
# tf.saved_model.save(network, '/home/bluecai/pyproject/tmp/saved_model/')
#
# imported = tf.saved_model.load('/home/bluecai/pyproject/tmp/saved_model/')
# f = imported.signatures["serving_default"]
# print(f(x = tf.ones([1,28,28,3])))