TensorFlow 1.x のグラフモードでは、tf.train.Saver を使って現在のセッション内の変数を checkpoint として保存し、新しいセッションでそれらの変数を復元できます。この仕組みは、学習が中断された場合、段階的に学習したい場合、あるいは学習済みモデルのパラメータを保存してからデバッグを続けたい場合に適しています。
以下の例では、MNIST データセットを使って 2 層の全結合ネットワークを学習します。最初のセッションで 3 epoch 学習してモデルを保存し、2 回目のセッションではグラフ変数を再初期化したあと、checkpoint から重みを復元してさらに 7 epoch 学習を続けます。
注意点として、このコードは tf.Session()、tf.placeholder()、tensorflow.examples.tutorials.mnist.input_data などを含む TensorFlow 1.x API を使用しています。TensorFlow 2.x 環境で実行する場合は、eager execution を無効にし、tf.compat.v1 経由で対応するインターフェイスを呼び出すなど、互換モードを使う必要があります。具体的な利用可否は、ローカルにインストールされているバージョンを基準にしてください。
'''
Save and Restore a model using TensorFlow.
This example is using the MNIST database of handwritten digits
(http://yann.lecun.com/exdb/mnist/)
Author: Aymeric Damien
Project: https://github.com/aymericdamien/TensorFlow-Examples/
'''
from __future__ import print_function
# Import MNIST data
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
import tensorflow as tf
# Parameters
learning_rate = 0.001
batch_size = 100
display_step = 1
model_path = "/tmp/model.ckpt"
# Network Parameters
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(logits=pred, labels=y))
optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost)
# Initializing the variables
init = tf.global_variables_initializer()
# 'Saver' op to save and restore all the variables
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 model weights to disk
save_path = saver.save(sess, model_path)
print("Model saved in file: %s" % save_path)
# 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
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}))
基本的な流れは、次の 3 ステップにまとめられます。
- グラフの構築が完了したあとに、
saver = tf.train.Saver()を作成する。 - 学習セッション内で
saver.save(sess, model_path)を呼び出し、変数を保存する。 - 新しいセッションで同じグラフを先に構築し、その後
saver.restore(sess, model_path)を呼び出して変数を復元する。
Saver が保存するのはグラフ内の変数の値であり、Python の学習ループそのものではありません。そのため、特定の学習ステップに正確に復元したい場合は、現在の epoch、global step、学習率スケジュールの状態などの学習メタデータも別途保存する必要があります。一般的な方法は、global_step = tf.Variable(0, trainable=False) を定義し、optimizer の minimize() に global_step=global_step を渡すことです。これにより、checkpoint に学習ステップ数も含まれるようになります。
実行後、通常は /tmp/model.ckpt の周辺に一連の checkpoint ファイルが生成されます。復元時にこれらのファイルを手動で読み込む必要はなく、model_path が保存時に使用したパスを指していれば十分です。
