TensorFlow_MNIST 保存、恢复模型及参数

内容:使用TensorFlow跑MNIST,并保存模型。之后恢复模型并进行测试
配置:win7x64/PyCharm/Python3.5/tensorflow-1.2.1/dataSet-MNIST
原程序:https://github.com/tensorflow/tensorflow/tree/master/tensorflow/examples/tutorials/mnist
这里写图片描述

1.网络定义

def deepnn(x):
  """deepnn builds the graph for a deep net for classifying digits.

  Args:
    x: an input tensor with the dimensions (N_examples, 784), where 784 is the
    number of pixels in a standard MNIST image.

  Returns:
    A tuple (y, keep_prob). y is a tensor of shape (N_examples, 10), with values
    equal to the logits of classifying the digit into one of 10 classes (the
    digits 0-9). keep_prob is a scalar placeholder for the probability of
    dropout.
  """
  # Reshape to use within a convolutional neural net.
  # Last dimension is for "features" - there is only one here, since images are
  # grayscale -- it would be 3 for an RGB image, 4 for RGBA, etc.
  with tf.name_scope('reshape'):
    x_image = tf.reshape(x, [-1, 28, 28, 1])   # [batch,height,width,channels]

  # First convolutional layer - maps one grayscale image to 32 feature maps.
  with tf.name_scope('conv1'):
    W_conv1 = weight_variable([5, 5, 1, 32])   # shape of weight  [conv_W,conv_H,channal_before_conv,channal_after_conv]
    b_conv1 = bias_variable([32])
    h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)

  # Pooling layer - downsamples by 2X.
  with tf.name_scope('pool1'):
    h_pool1 = max_pool_2x2(h_conv1)

  # Second convolutional layer -- maps 32 feature maps to 64.
  with tf.name_scope('conv2'):
    W_conv2 = weight_variable([5, 5, 32, 64])
    b_conv2 = bias_variable([64])
    h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)

  # Second pooling layer.
  with tf.name_scope('pool2'):
    h_pool2 = max_pool_2x2(h_conv2)

  # Fully connected layer 1 -- after 2 round of downsampling, our 28x28 image
  # is down to 7x7x64 feature maps -- maps this to 1024 features.
  with tf.name_scope('fc1'):
    W_fc1 = weight_variable([7 * 7 * 64, 1024])
    b_fc1 = bias_variable([1024])

    h_pool2_flat = tf.reshape(h_pool2, [-1, 7*7*64])
    h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)

  # Dropout - controls the complexity of the model, prevents co-adaptation of
  # features.
  with tf.name_scope('dropout'):
    keep_prob = tf.placeholder(tf.float32,name='keep_prob')
    h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)

  # Map the 1024 features to 10 classes, one for each digit
  with tf.name_scope('fc2'):
    W_fc2 = weight_variable([1024, 10])
    b_fc2 = bias_variable([10])

    y_conv = tf.add(tf.matmul(h_fc1_drop, W_fc2), b_fc2, name='output')
  return y_conv, keep_prob


def conv2d(x, W):
  """conv2d returns a 2d convolution layer with full stride."""
  return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')


def max_pool_2x2(x):
  """max_pool_2x2 downsamples a feature map by 2X."""
  return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')


def weight_variable(shape):
  """weight_variable generates a weight variable of a given shape."""
  initial = tf.truncated_normal(shape, stddev=0.1)
  return tf.Variable(initial)


def bias_variable(shape):
  """bias_variable generates a bias variable of a given shape."""
  initial = tf.constant(0.1, shape=shape)
  return tf.Variable(initial)

2.训练,保存模型及参数

 # Import data
  mnist = input_data.read_data_sets(FLAGS.data_dir, one_hot=True)
 # Create the model
  x = tf.placeholder(tf.float32, [None, 784], name='input_x')

  # Define loss and optimizer
  y_ = tf.placeholder(tf.float32, [None, 10], name='input_y_')

  # Build the graph for the deep net
  y_conv, keep_prob = deepnn(x)

  with tf.name_scope('loss'):
    cross_entropy = tf.nn.softmax_cross_entropy_with_logits(labels=y_,
                                                            logits=y_conv)
    cross_entropy = tf.reduce_mean(cross_entropy)

  with tf.name_scope('adam_optimizer'):
    train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)

  with tf.name_scope('accuracy'):
    correct_prediction = tf.equal(tf.argmax(y_conv, 1), tf.argmax(y_, 1))
    # argmax: return the index with max value among 10 values
    correct_prediction = tf.cast(correct_prediction, tf.float32)
    accuracy = tf.reduce_mean(correct_prediction)


  graph_location = tempfile.mkdtemp() # temp file
  print('Saving graph to: %s' % graph_location)
  train_writer = tf.summary.FileWriter(graph_location)
  train_writer.add_graph(tf.get_default_graph())
  saver=tf.train.Saver(tf.global_variables())


  with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    # train
    for i in range(300):  #20000
      batch = mnist.train.next_batch(50)
      if i % 100 == 0:
        train_accuracy = accuracy.eval(feed_dict={
            x: batch[0], y_: batch[1], keep_prob: 1.0})
        print('step %d, training accuracy %g' % (i, train_accuracy))

        #save variables
        save_path ='G:/tf_model/model_'+'%d'%i
        print('%s' % save_path)
        saver.save(sess, save_path)
        # #save model
        # save_path = 'G:/tf_model'
        # save_name = 'test_' + '%d' % i + '.pb'
        # tf.train.write_graph(sess.graph_def, save_path, save_name, False) #save graph
        # saver.save(sess, save_path+'/checkpoint.data')  #save data
      train_step.run(feed_dict={x: batch[0], y_: batch[1], keep_prob: 0.5})

保存的文件:
保存的文件

3.恢复模型及参数,测试

 # test 1 <using graph> -> load saved graph and variables
  sess1 = tf.Session()
  saver1 = tf.train.import_meta_graph('G:/tf_model/model_200.meta')  # load graph
  saver1.restore(sess1, 'G:/tf_model/model_200')  # load variables (remember no extension of file)
  # saver1.restore(sess1, tf.train.latest_checkpoint('G:/tf_model/')) # or this
  graph = tf.get_default_graph()  # get graph

  # get tensor by name, the name is named when define the network
  x = graph.get_tensor_by_name('input_x:0')    # input image
  y_ = graph.get_tensor_by_name('input_y_:0')  # input label
  y_conv = graph.get_tensor_by_name('fc2/output:0')  # output result from deepNN (predict label)
  keep_prob_ = graph.get_tensor_by_name('dropout/keep_prob:0')  # keep probability

  # accuracy calculation
  correct_prediction = tf.equal(tf.argmax(y_conv, 1), tf.argmax(y_, 1))  # compare predict result and label
  correct_prediction = tf.cast(correct_prediction, tf.float32)  # convert bool to float
  accuracy1 = tf.reduce_mean(correct_prediction)  # calculate mean accuracy

  for j in range(10):
    testSample_start = j * 50      # start num of test sample of one batch
    testSample_end = (j + 1) * 50  # end num of test sample of one batch <use batch as the capacity of GPU is limited>
    print('test %d accuracy %g' % (j, accuracy1.eval(session=sess1, feed_dict={
      x: mnist.test.images[testSample_start:testSample_end],
      y_: mnist.test.labels[testSample_start:testSample_end], keep_prob_: 1.0})))  # feed data for test

测试结果(训练次数较少,测试结果准确性不高)

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值