Tensorflow的卷积神经网络

网络的设计基于tensorflow官网的教程,结合了吴恩达的课程的一些内容进行了改进
tensorflow官方卷积神经网络教程
代码如下

"""A deep MNIST classifier using convolutional layers.

See extensive documentation at
https://www.tensorflow.org/get_started/mnist/pros
"""
# Disable linter warnings to maintain consistency with tutorial.
# pylint: disable=invalid-name
# pylint: disable=g-bad-import-order

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import matplotlib.pyplot as plt
import numpy as np

import argparse
import sys
import tempfile
import os

os.environ["CUDA_VISIBLE_DEVICES"] = '0'

from tensorflow.examples.tutorials.mnist import input_data

import tensorflow as tf

FLAGS = None


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])

  # First convolutional layer - maps one grayscale image to 32 feature maps.
  with tf.name_scope('conv1'):
    W_conv1 = tf.get_variable("W1",[5,5,1,32],initializer = tf.contrib.layers.xavier_initializer())
    Z_conv1 = tf.nn.conv2d(x_image,W_conv1,strides= [1,1,1,1],padding='SAME')
    h_conv1 = tf.nn.relu(Z_conv1)

  # Pooling layer - downsamples by 2X.
  with tf.name_scope('pool1'):
    h_pool1 = tf.nn.max_pool(h_conv1,ksize= [1,2,2,1],strides=[1,2,2,1],padding='SAME')

  # Second convolutional layer -- maps 32 feature maps to 64.
  with tf.name_scope('conv2'):
    W_conv2 = tf.get_variable("W2",[5,5,32,64],initializer = tf.contrib.layers.xavier_initializer())

    Z_conv2 = tf.nn.conv2d(h_pool1,W_conv2,strides=[1,1,1,1],padding='SAME')
    h_conv2 = tf.nn.relu(Z_conv2)

  # Second pooling layer.
  with tf.name_scope('pool2'):
    h_pool2 = tf.nn.max_pool(h_conv2,ksize=[1,2,2,1],strides=[1,2,2,1],padding='SAME')

  # 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'):
    h_pool2_flat = tf.contrib.layers.flatten(h_pool2)

    h_fc1 = tf.contrib.layers.fully_connected(h_pool2_flat,num_outputs = 1024,activation_fn = tf.nn.relu)

  # Dropout - controls the complexity of the model, prevents co-adaptation of
  # features.
  with tf.name_scope('dropout'):
    keep_prob = tf.placeholder(tf.float32)
    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'):
    h_fc2 = tf.contrib.layers.fully_connected(h_fc1_drop, num_outputs=10, activation_fn = None)

    y_conv = h_fc2
  return y_conv, keep_prob


def main(_):
  # Import data
  mnist = input_data.read_data_sets(FLAGS.data_dir, one_hot=True)

  # Create the model
  x = tf.placeholder(tf.float32, [None, 784])

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

  # 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))
    correct_prediction = tf.cast(correct_prediction, tf.float32)
  accuracy = tf.reduce_mean(correct_prediction)

  graph_location = tempfile.mkdtemp()
  print('Saving graph to: %s' % graph_location)
  train_writer = tf.summary.FileWriter(graph_location)
  train_writer.add_graph(tf.get_default_graph())
  costs = []
  with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())

    for i in range(1001):
      batch = mnist.train.next_batch(50)
      _, tmp_cost = sess.run([train_step, cross_entropy], feed_dict={x: batch[0], y_: batch[1], keep_prob: 0.5})
      minibatch_cost = tmp_cost;
      costs.append(minibatch_cost)
      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,cost %g' % (i, train_accuracy,tmp_cost))

      print
    print(mnist.test.images.shape)

    plt.plot(np.squeeze(costs))
    plt.show()


    print('test accuracy %g' % accuracy.eval(feed_dict={
       x: mnist.test.images[1:100], y_: mnist.test.labels[1:100], keep_prob: 1.0}))

if __name__ == '__main__':
  parser = argparse.ArgumentParser()
  parser.add_argument('--data_dir', type=str,
                      default='/tmp/tensorflow/mnist/input_data',
                      help='Directory for storing input data')
  FLAGS, unparsed = parser.parse_known_args()
  tf.app.run(main=main, argv=[sys.argv[0]] + unparsed)

你可能感兴趣的:(Tensorflow的卷积神经网络)