前言
首先,我们从一个直观的例子,讲解如何实现Tensorflow模型参数的保存以及保存后模型的读取。
然后,我们在之前多层感知机的基础上进行模型的参数保存,以及参数的读取。该项技术可以用于Tensorflow分段训练模型以及对经典模型进行fine tuning
(微调)
Tensorflow 模型的保存与读取(直观)
模型参数存储
1 | import tensorflow as tf |
V1: [[1.2366687 0.4373563]]
V2: [[-0.9465265 -0.7147392 -2.421146 ]
[-0.48401725 0.40536404 0.21300188]]
Model saved in file: ./save/model.ckpt
模型存储的文件格式如下图所示:
模型参数读取
1 | import tensorflow as tf |
INFO:tensorflow:Restoring parameters from ./save/model.ckpt
V1: [[1.2366687 0.4373563]]
V2: [[-0.9465265 -0.7147392 -2.421146 ]
[-0.48401725 0.40536404 0.21300188]]
Model restored
Tensorflow 模型的保存与读取(多层感知机)
导入数据集
1 | from __future__ import print_function |
Extracting ./data/train-images-idx3-ubyte.gz
Extracting ./data/train-labels-idx1-ubyte.gz
Extracting ./data/t10k-images-idx3-ubyte.gz
Extracting ./data/t10k-labels-idx1-ubyte.gz
创建多层感知机模型
1 | # 训练参数设置 |
调用Saver方法
1 | # 'Saver' 操作用于保存与读取所有的变量 |
第一次训练(训练完成保存参数)
1 | # Running first session |
Starting 1st session...
Epoch: 0001 cost= 172.468734065
Epoch: 0002 cost= 43.036823805
Epoch: 0003 cost= 26.978232009
First Optimization Finished!
Accuracy: 0.9084
Model saved in file: ./save/model.ckpt
第二次训练(加载第一次参数)
1 | # Running a new session |
Starting 2nd session...
INFO:tensorflow:Restoring parameters from ./save/model.ckpt
Model restored from file: ./save/model.ckpt
Epoch: 0001 cost= 18.712020244
Epoch: 0002 cost= 13.624892972
Epoch: 0003 cost= 10.156988694
Epoch: 0004 cost= 7.652410518
Epoch: 0005 cost= 5.658380691
Epoch: 0006 cost= 4.276506317
Epoch: 0007 cost= 3.249772967
Second Optimization Finished!
Accuracy: 0.9381