TensorFlow2.0(12):模型保存与序列化

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

TensorFlow2.0(12):模型保存与序列化

奥辰   2019-12-24 我要评论

 

注:本系列所有博客将持续更新并发布在github上,您可以通过github下载本系列所有文章笔记文件。

 

模型训练好之后,我们就要想办法将其持久化保存下来,不然关机或者程序退出后模型就不复存在了。本文介绍两种持久化保存模型的方法:

 

在介绍这两种方法之前,我们得先创建并训练好一个模型,还是以mnist手写数字识别数据集训练模型为例:

In [1]:
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers, optimizers, Sequential
In [2]:
model = Sequential([  # 创建模型
    layers.Dense(256, activation=tf.nn.relu),
    layers.Dense(128, activation=tf.nn.relu),
    layers.Dense(64, activation=tf.nn.relu),
    layers.Dense(32, activation=tf.nn.relu),
    layers.Dense(10)
    ]
)
(x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data()
x_train = x_train.reshape(60000, 784).astype('float32') / 255
x_test = x_test.reshape(10000, 784).astype('float32') / 255

model.compile(loss='sparse_categorical_crossentropy',
              optimizer=keras.optimizers.RMSprop())
history = model.fit(x_train, y_train,  # 进行简单的1次迭代训练
                    batch_size=64,
                    epochs=1)
 
Train on 60000 samples
60000/60000 [==============================] - 3s 46us/sample - loss: 2.3700
 

方法一:model.save()¶

 

通过模型自带的save()方法可以将模型保存到一个指定文件中,保存的内容包括:

  • 模型的结构
  • 模型的权重参数
  • 通过compile()方法配置的模型训练参数
  • 优化器及其状态
In [3]:
model.save('mymodels/mnist.h5')
 

使用save()方法保存后,在mymodels目录下就会有一个mnist.h5文件。需要使用模型时,通过keras.models.load_model()方法从文件中再次加载即可。

In [4]:
new_model = keras.models.load_model('mymodels/mnist.h5')
 
WARNING:tensorflow:Sequential models without an `input_shape` passed to the first layer cannot reload their optimizer state. As a result, your model isstarting with a freshly initialized optimizer.
 

新加载出来的new_model在结构、功能、参数各方面与model是一样的。

 

通过save()方法,也可以将模型保存为SavedModel 格式。SavedModel格式是TensorFlow所特有的一种序列化文件格式,其他编程语言实现的TensorFlow中同样支持:

In [5]:
model.save('mymodels/mnist_model', save_format='tf')  # 将模型保存为SaveModel格式
 
WARNING:tensorflow:From /home/chb/anaconda3/envs/study_python/lib/python3.7/site-packages/tensorflow_core/python/ops/resource_variable_ops.py:1781: calling BaseResourceVariable.__init__ (from tensorflow.python.ops.resource_variable_ops) with constraint is deprecated and will be removed in a future version.
Instructions for updating:
If using Keras pass *_constraint arguments to layers.
INFO:tensorflow:Assets written to: mymodels/mnist_model/assets
In [6]:
new_model = keras.models.load_model('mymodels/mnist_model')  # 加载模型
 

方法二:model.save_weights()¶

 

save()方法会保留模型的所有信息,但有时候,我们仅对部分信息感兴趣,例如仅对模型的权重参数感兴趣,那么就可以通过save_weights()方法进行保存。

In [14]:
model.save_weights('mymodels/mnits_weights')  # 保存模型权重信息
In [15]:
new_model = Sequential([  # 创建新的模型
    layers.Dense(256, activation=tf.nn.relu),
    layers.Dense(128, activation=tf.nn.relu),
    layers.Dense(64, activation=tf.nn.relu),
    layers.Dense(32, activation=tf.nn.relu),
    layers.Dense(10)
    ]
)
new_model.compile(loss='sparse_categorical_crossentropy',
              optimizer=keras.optimizers.RMSprop())
new_model.load_weights('mymodels/mnits_weights')  # 将保存好的权重信息加载的新的模型中
Out[15]:
<tensorflow.python.training.tracking.util.CheckpointLoadStatus at 0x7f49c42b87d0>

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们