Tensorflow模型的保存與讀取

前言

首先,我們從一個直觀的例子,講解如何實現Tensorflow模型參數的保存以及保存後模型的讀取。
然後,我們在之前多層感知機的基礎上進行模型的參數保存,以及參數的讀取。該項技術可以用於Tensorflow分段訓練模型以及對經典模型進行fine tuning(微調)

Tensorflow 模型的保存與讀取(直觀)

模型參數存儲

import tensorflow as tf

# 隨機生成v1與v2變量
v1 = tf.Variable(tf.random_normal([1,2]), name="v1")
v2 = tf.Variable(tf.random_normal([2,3]), name="v2")
# 全局初始化
init_op = tf.global_variables_initializer()
# 調用Saver方法(重要)
saver = tf.train.Saver()
with tf.Session() as sess:
    sess.run(init_op)
    print ("V1:",sess.run(v1))
    print ("V2:",sess.run(v2))
    # 存儲Session工作空間
    saver_path = saver.save(sess, "./save/model.ckpt")
    print ("Model saved in file: ", saver_path)
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

模型存儲的文件格式如下圖所示:
模型存儲文件

模型參數讀取

import tensorflow as tf
v1 = tf.Variable(tf.random_normal([1,2]), name="v1")
v2 = tf.Variable(tf.random_normal([2,3]), name="v2")
saver = tf.train.Saver()

with tf.Session() as sess:
    saver.restore(sess, "./save/model.ckpt")
    print ("V1:",sess.run(v1))
    print ("V2:",sess.run(v2))
    print ("Model restored")

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 模型的保存與讀取(多層感知機)

導入數據集

from __future__ import print_function

# Import MINST data
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("./data/", one_hot=True)

import tensorflow as tf

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

創建多層感知機模型

# 訓練參數設置
learning_rate = 0.001
batch_size = 100
display_step = 1
model_path = "./save/model.ckpt" #模型存儲路徑

# 網絡參數設置
n_hidden_1 = 256 # 1st layer number of features
n_hidden_2 = 256 # 2nd layer number of features
n_input = 784 # MNIST data input (img shape: 28*28)
n_classes = 10 # MNIST total classes (0-9 digits)

# tf Graph input
x = tf.placeholder("float", [None, n_input])
y = tf.placeholder("float", [None, n_classes])


# Create model
def multilayer_perceptron(x, weights, biases):
    # Hidden layer with RELU activation
    layer_1 = tf.add(tf.matmul(x, weights['h1']), biases['b1'])
    layer_1 = tf.nn.relu(layer_1)
    # Hidden layer with RELU activation
    layer_2 = tf.add(tf.matmul(layer_1, weights['h2']), biases['b2'])
    layer_2 = tf.nn.relu(layer_2)
    # Output layer with linear activation
    out_layer = tf.matmul(layer_2, weights['out']) + biases['out']
    return out_layer

# Store layers weight & bias
weights = {
    'h1': tf.Variable(tf.random_normal([n_input, n_hidden_1])),
    'h2': tf.Variable(tf.random_normal([n_hidden_1, n_hidden_2])),
    'out': tf.Variable(tf.random_normal([n_hidden_2, n_classes]))
}
biases = {
    'b1': tf.Variable(tf.random_normal([n_hidden_1])),
    'b2': tf.Variable(tf.random_normal([n_hidden_2])),
    'out': tf.Variable(tf.random_normal([n_classes]))
}

# Construct model
pred = multilayer_perceptron(x, weights, biases)

# Define loss and optimizer
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(logits=pred, labels=y))
optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost)

# Initializing the variables
init = tf.global_variables_initializer()

調用Saver方法

# 'Saver' 操作用於保存與讀取所有的變量
saver = tf.train.Saver()

第一次訓練(訓練完成保存參數)

# Running first session
print("Starting 1st session...")
with tf.Session() as sess:
    # Initialize variables
    sess.run(init)

    # Training cycle(迭代三次)
    for epoch in range(3):
        avg_cost = 0.
        total_batch = int(mnist.train.num_examples/batch_size)
        # Loop over all batches
        for i in range(total_batch):
            batch_x, batch_y = mnist.train.next_batch(batch_size)
            # Run optimization op (backprop) and cost op (to get loss value)
            _, c = sess.run([optimizer, cost], feed_dict={x: batch_x,
                                                          y: batch_y})
            # Compute average loss
            avg_cost += c / total_batch
        # Display logs per epoch step
        if epoch % display_step == 0:
            print ("Epoch:", '%04d' % (epoch+1), "cost=", \
                "{:.9f}".format(avg_cost))
    print("First Optimization Finished!")

    # Test model
    correct_prediction = tf.equal(tf.argmax(pred, 1), tf.argmax(y, 1))
    # Calculate accuracy
    accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))
    print("Accuracy:", accuracy.eval({x: mnist.test.images, y: mnist.test.labels}))

    # 保存模型參數到硬盤上
    save_path = saver.save(sess, model_path)
    print("Model saved in file: %s" % save_path)

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

第二次訓練(加載第一次參數)

# Running a new session
print("Starting 2nd session...")
with tf.Session() as sess:
    # Initialize variables
    sess.run(init)

    # Restore model weights from previously saved model
    load_path = saver.restore(sess, model_path)
    print("Model restored from file: %s" % save_path)

    # Resume training
    for epoch in range(7):
        avg_cost = 0.
        total_batch = int(mnist.train.num_examples / batch_size)
        # Loop over all batches
        for i in range(total_batch):
            batch_x, batch_y = mnist.train.next_batch(batch_size)
            # Run optimization op (backprop) and cost op (to get loss value)
            _, c = sess.run([optimizer, cost], feed_dict={x: batch_x,
                                                          y: batch_y})
            # Compute average loss
            avg_cost += c / total_batch
        # Display logs per epoch step
        if epoch % display_step == 0:
            print("Epoch:", '%04d' % (epoch + 1), "cost=", \
                "{:.9f}".format(avg_cost))
    print("Second Optimization Finished!")

    # Test model
    correct_prediction = tf.equal(tf.argmax(pred, 1), tf.argmax(y, 1))
    # Calculate accuracy
    accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))
    print("Accuracy:", accuracy.eval(
        {x: mnist.test.images, y: mnist.test.labels}))

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

參考

TensorFlow-Examples


更多內容,關注公衆號AI異構

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章