alexnet.py 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134
  1. '''
  2. AlexNet implementation example using TensorFlow library.
  3. This example is using the MNIST database of handwritten digits (http://yann.lecun.com/exdb/mnist/)
  4. AlexNet Paper (http://papers.nips.cc/paper/4824-imagenet-classification-with-deep-convolutional-neural-networks.pdf)
  5. Author: Aymeric Damien
  6. Project: https://github.com/aymericdamien/TensorFlow-Examples/
  7. '''
  8. # Import MINST data
  9. import input_data
  10. mnist = input_data.read_data_sets("/tmp/data/", one_hot=True)
  11. import tensorflow as tf
  12. # Parameters
  13. learning_rate = 0.001
  14. training_iters = 200000
  15. batch_size = 64
  16. display_step = 20
  17. # Network Parameters
  18. n_input = 784 # MNIST data input (img shape: 28*28)
  19. n_classes = 10 # MNIST total classes (0-9 digits)
  20. dropout = 0.8 # Dropout, probability to keep units
  21. # tf Graph input
  22. x = tf.placeholder(tf.float32, [None, n_input])
  23. y = tf.placeholder(tf.float32, [None, n_classes])
  24. keep_prob = tf.placeholder(tf.float32) # dropout (keep probability)
  25. # Create AlexNet model
  26. def conv2d(name, l_input, w, b):
  27. return tf.nn.relu(tf.nn.bias_add(tf.nn.conv2d(l_input, w, strides=[1, 1, 1, 1], padding='SAME'),b), name=name)
  28. def max_pool(name, l_input, k):
  29. return tf.nn.max_pool(l_input, ksize=[1, k, k, 1], strides=[1, k, k, 1], padding='SAME', name=name)
  30. def norm(name, l_input, lsize=4):
  31. return tf.nn.lrn(l_input, lsize, bias=1.0, alpha=0.001 / 9.0, beta=0.75, name=name)
  32. def alex_net(_X, _weights, _biases, _dropout):
  33. # Reshape input picture
  34. _X = tf.reshape(_X, shape=[-1, 28, 28, 1])
  35. # Convolution Layer
  36. conv1 = conv2d('conv1', _X, _weights['wc1'], _biases['bc1'])
  37. # Max Pooling (down-sampling)
  38. pool1 = max_pool('pool1', conv1, k=2)
  39. # Apply Normalization
  40. norm1 = norm('norm1', pool1, lsize=4)
  41. # Apply Dropout
  42. norm1 = tf.nn.dropout(norm1, _dropout)
  43. # Convolution Layer
  44. conv2 = conv2d('conv2', norm1, _weights['wc2'], _biases['bc2'])
  45. # Max Pooling (down-sampling)
  46. pool2 = max_pool('pool2', conv2, k=2)
  47. # Apply Normalization
  48. norm2 = norm('norm2', pool2, lsize=4)
  49. # Apply Dropout
  50. norm2 = tf.nn.dropout(norm2, _dropout)
  51. # Convolution Layer
  52. conv3 = conv2d('conv3', norm2, _weights['wc3'], _biases['bc3'])
  53. # Max Pooling (down-sampling)
  54. pool3 = max_pool('pool3', conv3, k=2)
  55. # Apply Normalization
  56. norm3 = norm('norm3', pool3, lsize=4)
  57. # Apply Dropout
  58. norm3 = tf.nn.dropout(norm3, _dropout)
  59. # Fully connected layer
  60. dense1 = tf.reshape(norm3, [-1, _weights['wd1'].get_shape().as_list()[0]]) # Reshape conv3 output to fit dense layer input
  61. dense1 = tf.nn.relu(tf.matmul(dense1, _weights['wd1']) + _biases['bd1'], name='fc1') # Relu activation
  62. dense2 = tf.nn.relu(tf.matmul(dense1, _weights['wd2']) + _biases['bd2'], name='fc2') # Relu activation
  63. # Output, class prediction
  64. out = tf.matmul(dense2, _weights['out']) + _biases['out']
  65. return out
  66. # Store layers weight & bias
  67. weights = {
  68. 'wc1': tf.Variable(tf.random_normal([3, 3, 1, 64])),
  69. 'wc2': tf.Variable(tf.random_normal([3, 3, 64, 128])),
  70. 'wc3': tf.Variable(tf.random_normal([3, 3, 128, 256])),
  71. 'wd1': tf.Variable(tf.random_normal([4*4*256, 1024])),
  72. 'wd2': tf.Variable(tf.random_normal([1024, 1024])),
  73. 'out': tf.Variable(tf.random_normal([1024, 10]))
  74. }
  75. biases = {
  76. 'bc1': tf.Variable(tf.random_normal([64])),
  77. 'bc2': tf.Variable(tf.random_normal([128])),
  78. 'bc3': tf.Variable(tf.random_normal([256])),
  79. 'bd1': tf.Variable(tf.random_normal([1024])),
  80. 'bd2': tf.Variable(tf.random_normal([1024])),
  81. 'out': tf.Variable(tf.random_normal([n_classes]))
  82. }
  83. # Construct model
  84. pred = alex_net(x, weights, biases, keep_prob)
  85. # Define loss and optimizer
  86. cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(pred, y))
  87. optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost)
  88. # Evaluate model
  89. correct_pred = tf.equal(tf.argmax(pred,1), tf.argmax(y,1))
  90. accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))
  91. # Initializing the variables
  92. init = tf.initialize_all_variables()
  93. # Launch the graph
  94. with tf.Session() as sess:
  95. sess.run(init)
  96. step = 1
  97. # Keep training until reach max iterations
  98. while step * batch_size < training_iters:
  99. batch_xs, batch_ys = mnist.train.next_batch(batch_size)
  100. # Fit training using batch data
  101. sess.run(optimizer, feed_dict={x: batch_xs, y: batch_ys, keep_prob: dropout})
  102. if step % display_step == 0:
  103. # Calculate batch accuracy
  104. acc = sess.run(accuracy, feed_dict={x: batch_xs, y: batch_ys, keep_prob: 1.})
  105. # Calculate batch loss
  106. loss = sess.run(cost, feed_dict={x: batch_xs, y: batch_ys, keep_prob: 1.})
  107. print "Iter " + str(step*batch_size) + ", Minibatch Loss= " + "{:.6f}".format(loss) + ", Training Accuracy= " + "{:.5f}".format(acc)
  108. step += 1
  109. print "Optimization Finished!"
  110. # Calculate accuracy for 256 mnist test images
  111. print "Testing Accuracy:", sess.run(accuracy, feed_dict={x: mnist.test.images[:256], y: mnist.test.labels[:256], keep_prob: 1.})