tensorflow模型的保存与加载

louishao 2020-01-31

模型的保存与加载一般有三种模式:save/load weights(最干净、最轻量级的方式,只保存网络参数,不保存网络状态),save/load entire model(最简单粗暴的方式,把网络所有的状态都保存起来),saved_model(更通用的方式,以固定模型格式保存,该格式是各种语言通用的)

具体使用方法如下:

# 保存模型
        model.save_weights(‘./checkpoints/my_checkpoint‘)
        # 加载模型
        model = keras.create_model()
        model.load_weights(‘./checkpoints/my_checkpoint‘)

示例:

import tensorflow as tf
from tensorflow.keras import datasets, layers, optimizers, Sequential, metrics


def preprocess(x, y):
    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)

network = Sequential([layers.Dense(256, activation=‘relu‘),
                      layers.Dense(128, activation=‘relu‘),
                      layers.Dense(64, activation=‘relu‘),
                      layers.Dense(32, activation=‘relu‘),
                      layers.Dense(10)])
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‘]
                )

network.fit(db, epochs=3, validation_data=ds_val, validation_freq=2)

network.evaluate(ds_val)

network.save_weights(‘weights.ckpt‘)
print(‘saved weights.‘)
del network

network = Sequential([layers.Dense(256, activation=‘relu‘),
                      layers.Dense(128, activation=‘relu‘),
                      layers.Dense(64, activation=‘relu‘),
                      layers.Dense(32, activation=‘relu‘),
                      layers.Dense(10)])
network.compile(optimizer=optimizers.Adam(lr=0.01),
                loss=tf.losses.CategoricalCrossentropy(from_logits=True),
                metrics=[‘accuracy‘]
                )
network.load_weights(‘weights.ckpt‘)
print(‘loaded weights!‘)
network.evaluate(ds_val)

运行效果如下:

tensorflow模型的保存与加载

可以看到保存前后的精度和损失差距不大,这是由于神经网络的运算过程中会有很多不确定因子,这些不确定因子不会通过save_weights方法保存,要想保存前后运行结果一致,就需要完整的保存网络模型。即model.save方法

使用方法如下:

# 模型保存
network.save(‘model.h5‘)
print(‘saved total model.‘)
# 模型加载
print(‘load model from file‘)
network = tf.keras.models.load_model(‘model.h5‘)
# 评估
network.evaluate(x_val,y_val)

除了这种方法之外,tensorflow还支持保存为标准的可以给其他语言使用的模型,使用saved_model即可

使用方法如下:

tf.saved_model.save(m,‘/tmp/saved_model/‘)
imported = tf.saved_model.load(path)
f = imported.signatures["serving_default"]
print(f(x=tf.ones([1,28,28,3])))

相关推荐