Tensorflow2.1入门(基于API)实战5——模型的保存

在之前的实战中,我们实现了基本的操作,对神经网络的训练也有了一些基本了解。为了我们训练出的模型可以反复利用,更灵活方便的迁移,我们需要了解如何保存模型,加载已经学习的模型。官网的API中介绍了几种方法。在这里我删减了实用性不强的方法,忽略了官网中说以后可能有删改的方法。同样把传送门留给大家。传送门
在本篇中,只介绍实用性最强的两种方法:Checkpoint(只保存权重)和保存模型

数据与文件格式准备:

from __future__ import absolute_import, division, print_function, unicode_literals
import os
import tensorflow as tf
from tensorflow import keras

!pip install -q pyyaml h5py

(train_images, train_labels), (test_images, test_labels) = tf.keras.datasets.mnist.load_data()
train_labels = train_labels[:1000]
test_labels = test_labels[:1000]
train_images=train_images[:1000].reshape(-1,28*28)/255.0
test_images=test_images[:1000].reshape(-1,28*28)/255.0

上述代码中install准备了H5文件格式。
这里值得一提的是对图片的处理:
这里的数据集中,每张图片都是2828的形式,将每张图片转化一行含有2828个元素的向量直接作为图片的特征。每一个元素都归一化为0~1之间的数。reshape(-1,2828)表示转化后的形状行数未知,但是要求列数为2828。
同理,现有5*6的矩阵image,则image.reshape(-1,10)表示转化为10列的含有未知行数的矩阵。就是转化为3行10列的矩阵。

Checkpoint方法:

def create_model():
    model=tf.keras.models.Sequential([
        keras.layers.Dense(512,activation='relu',input_shape=(784,)),
        keras.layers.Dropout(0.2),
        keras.layers.Dense(10,activation='softmax')
    ])
    model.compile(optimizer='adam',
                 loss='sparse_categorical_crossentropy',
                  metrics=['accuracy']
                 )
    return model

model=create_model()
model.summary()

在Checkpoint方法中,会被保存的只是模型中的权重,并不保留结构,优化器等部分,因此在使用权重时,只能运用在相同结构的模型上。

checkpoint_path="training_2/cp-{epoch:04d}.ckpt"
checkpoint_dir=os.path.dirname(checkpoint_path)
cp_callback=tf.keras.callbacks.ModelCheckpoint(
    filepath=checkpoint_path,
    verbose=1,
    save_weights_only=True,
    period=5)
model=create_model()

model.save_weights(checkpoint_path.format(epoch=0))
model.fit(train_images,
          train_labels,
          epochs=50,
          callbacks=[cp_callback],
         validation_data=(test_images,test_labels),
         verbose=0)

回调结构:cp_callback=tf.keras.callbacks.ModelCheckpoint(filepath,verbose,save_weights_only=True,period)
参数解释:
filepath:存储权重的地址。
verbose:个人感觉是一个不是很重要的参数,跟fit中的verbos差不多,控制输出内容。
save_weight_only:只保留权重,设置为True。
period:多少个epoch保存一次权重,这里我们设置为5。

运行结果如图:
Tensorflow2.1入门(基于API)实战5——模型的保存_第1张图片
我们获取最新保存的权重,尝试再次加载:

latest=tf.train.latest_checkpoint(checkpoint_dir)
model=create_model()
model.load_weights(latest)
loss,acc=model.evaluate(test_images,test_labels,verbose=2)
print("Restore model,accuracy: {:5.2f}%.format(100*acc)")

我们先读取了之前最新的权重,然后构建了一个相同结构的模型,权重导入模型,然后评估。
这里得到的准确率大致在87%左右,以上便是只保留权重的过程。

保留整个模型:

model=create_model()
model.fit(train_images,train_labels,epochs=5)
model.save('my_model.h5')

以上的语句保存了模型的权重,结构,以及优化器的配置。

new_model=keras.models.load_model('my_model.h5')
new_model.summary()
loss , acc=new_model.evaluate(test_images,test_labels,verbose=2)
print("Restored model, accuracy: {:5.2f}%.format(100*acc)")

这里的语句一目了然:就是导入之前保存的模型,然后再拿出来测试用。

总结:

以上就是这次实战的内容了,简单实用,个人认为Checkpoint保留权重更为灵活,而model.save()保存可以留下更完整的模型。

留疑:

如果我们想保存模型,然后再在这个模型的基础上进行训练,应该怎么办呢?
在使用两种方法(导入权重或导入模型)后,得到的新模型直接使用model.fit函数就能继续在原模型的基础上进行训练了。在这里我们以Checkpoint方法为例:

new_model.load_weights(latest)
new_model.fit(train_images,
          train_labels,
          epochs=8,
         validation_data=(test_images,test_labels),
         verbose=2)

结果如下:
Tensorflow2.1入门(基于API)实战5——模型的保存_第2张图片

你可能感兴趣的:(Tensorflow实战入门)