阅读 160

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

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

 

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

In [1]:

import tensorflow as tffrom tensorflow import kerasfrom 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') / 255x_test = x_test.reshape(10000, 784).astype('float32') / 255model.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>


文章分类
后端
版权声明:本站是系统测试站点,无实际运营。本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 XXXXXXo@163.com 举报,一经查实,本站将立刻删除。
相关推荐