tensorflow模型的保存與加載


模型的保存與加載一般有三種模式: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)

運行效果如下:

 

可以看到保存前后的精度和損失差距不大,這是由於神經網絡的運算過程中會有很多不確定因子,這些不確定因子不會通過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])))

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM