TensorFlow 训练好模型参数的保存和恢复代码,之前就在想模型不应该每次要个结果都要重新训练一遍吧,应该训练一次就可以一直使用吧。

TensorFlow 提供了 Saver 类,可以进行保存和恢复。下面是 TensorFlow-Examples 项目中提供的保存和恢复代码。


'''Save and Restore a model using TensorFlow.This example is using the MNIST data  of handwritten digits(http://yann.lecun.com/exdb/mnist/)Author: Aymeric DamienProject: https://github.com/aymericdamien/TensorFlow-Examples/'''from __future__ import print_function# Import MNIST datafrom tensorflow.examples.tutorials.mnist import input_datamnist = input_data.read_data_sets("MNIST_data/", one_hot=True)import tensorflow as tf# Parameterslearning_rate = 0.001batch_size = 100display_step = 1model_path = "/tmp/model.ckpt"# Network Parametersn_hidden_1 = 256 # 1st   number of featuresn_hidden_2 = 256 # 2nd   number of featuresn_input = 784 # MNIST data input (img shape: 28*28)n_classes = 10 # MNIST total classes (0-9 digits)# tf Graph inputx = tf.placeholder("float", [None, n_input])y = tf.placeholder("float", [None, n_classes])# Create modeldef mult _perceptron(x, weights, biases):    # Hidden   with RELU activation     _1 = tf.add(tf.matmul(x, weights['h1']), biases['b1'])     _1 = tf.nn.relu( _1)    # Hidden   with RELU activation     _2 = tf.add(tf.matmul( _1, weights['h2']), biases['b2'])     _2 = tf.nn.relu( _2)    # Output   with linear activation    out_  = tf.matmul( _2, weights['out']) + biases['out']    return out_ # Store  s weight & biasweights = {    '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 modelpred = mult _perceptron(x, weights, biases)# Define loss and optimizercost = 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 variablesinit = tf.global_variables_initializer()# 'Saver' op to save and restore all the variablessaver = tf.train.Saver()# Running first sessionprint("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 sessionprint("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}))

原文链接:http://www.tensorflownews.com/
收藏 打印