保存和恢复模型, 分为两个部分: 1.模型的结构(即创建模型的代码), 2.模型的训练权重(即参数), 所以, 不能总只是记着参数而没有结构. 另, 保存TF代码中的模型有很多方法(取决于API), 本文中使用的是tf.keras
, 是TF中的”高阶API”. (这会区别于TF中”原始”的保存和加载代码) P.S. 看官方的东西, 踏实的有点过分.
此演示DEMO的大致步骤 |
---|
1.加载MNIST数据集, 并定义好一个用于演示的模型; |
2.定义好一个cp_callback 回调, 并作为model.fit() 中的callbacks 参数; (告诉KERAS/PY在每个epoch结束时保存一次) 此步, 会在training_1/cp.ckpt 所在的文件夹下生成一系列相关的”保存文件”; |
3.在需要使用原模型的参数时, 恢复模型, 如: model.load_weights(cp_path) , 这一步, 模型的参数是训练过的参数了; |
其它内容 |
1.回调选项(设置), 2.手动保存权重, 3.保存整个模型(.h5 文件形式(HDF5标准), 或saved_model 形式). |
下面附上代码: (无代码 => 空谈空谈)
1 | # 这坑爹的, 从'.ipynb'中转出来的代码居然设置了这个, 难怪每次都会莫名其妙的少模块: 原来它使用了默认的环境; |
1 | # 此代码块关于检查点回调的一些configuration演示; |
至此, 模型的权重保存和加载演示完毕, 但上述演示只是权重(weights)的保存和加载, 下面介绍整个模型的保存和加载, 以及保存文件的格式的介绍.
关于检查点文件 The above code stores the weights to a collection of checkpoint-formatted files that contain only the trained weights in a binary format. Checkpoints contain: 1.One or more shards(分片) that contain your model’s weight, 2.An index file(索引文件) that indicates which weights are stored in a which shard. If you are only training a model on a single machine, you’ll have one shard with the suffix: ‘.data-00000-of-00001’.
以下介绍手动保存权重(manually save weights):
1 | # Manually saving the weights is just as simple, use the `Model.save_weights` method. |
以下, 介绍保存整个模型(save the entire model): 整个模型可以保存到一个文件中, 其中包含权重值, 模型配置乃至优化器配置. 这样可以为模型设置检查点, 并稍后从完全相同的状态继续训练, 而无需访问原始(original)代码.1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21# 保存整个模型1/2: 保存成HDF5文件;
# Keras provides a basic save format using the HDF5 standard. For our purposes, the saved model can be treated as a single binary blob(二进制blob).
# Ref: https://en.wikipedia.org/wiki/Hierarchical_Data_Format;
model = create_model()
model.fit(train_images, train_labels, epochs=5)
# Save entire model to a HDF5 file;
model.save('my_model.h5')
# 从该文件重新创建一模一样的模型: 包括weights和optimizer;
new_model = keras.models.load_model('my_model.h5')
new_model.summary()
# Check its accuracy:
loss, acc = new_model.evaluate(test_images, test_labels)
print("Restored model, accuracy: {:5.2f}%".format(100*acc))
# 1000/1000 [==============================] - 0s 258us/sample - loss: 0.4280 - acc: 0.8670
# Restored model, accuracy: 86.70%
#
# 以上技术(technique)保存所有的东西:
# * The weight values, 权重值;
# * The model's configuration(architecture), 模型配置(架构);
# * The optimizer configuration, 优化器配置;
# Keras通过检查架构来保存模型, 但它无法保存TensorFlow优化器(来自tf.train). 使用此类优化器时, 需要在加载模型后对其进行重新编译(因为没保存优化器的状态信息);
1 | # 保存整个模型2/2: 保存成'saved_model'; |
后记
其实模型保存也不是什么大聪明才智的事情, 关键是我们说的概念仅仅是”保存模型”这个蓝图, 而这个概念的具体实在是: 1.保存时那些生成的文件是什么格式的(如二进制块, blob), 2.保存时API的参数设置可以是怎么样的, 等等. 如此的问题都会具体影响到”保存模型”这个概念: 绝知此事要躬行.
Reference
- 保存和恢复模型, Learn and use ML, [tensorflow.google.cn].