Advertisement
Guest User

Untitled

a guest
Mar 30th, 2016
316
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 8.21 KB | None | 0 0
  1. from datetime import datetime
  2. import math
  3. import time
  4. import tensorflow as tf
  5. import numpy as np
  6. import scipy as sci
  7. import cv2
  8. import input_data_conv
  9. import skimage.transform
  10. from skimage import color
  11.  
  12. import tensorflow.python.platform
  13. import tensorflow as tf
  14.  
  15. FLAGS = tf.app.flags.FLAGS
  16. # Parameters
  17. learning_rate = 0.001
  18. training_iters = 200000
  19. batch_size = 64
  20. display_step = 20
  21. n_classes=101 # number of classes
  22.  
  23. #Input data and classes
  24. global train_data,train_class,test_data,test_classs,train_i,test_i
  25. test_i, train_i = 0,0
  26. train_data=input_data_conv.train_single_frames
  27. train_class=input_data_conv.train_single_classes
  28. test_data=input_data_conv.test_single_frames
  29. test_classs=input_data_conv.test_single_classes
  30.  
  31.  
  32. # Network Parameters
  33. n_input = [227, 227, 3 ]# MNIST data input (img shape: 227*227*3)
  34. dropout = 0.5 # Dropout, probability to keep units
  35.  
  36.  
  37.  
  38. # TODO: why is batch size 64 going OOM?
  39. tf.app.flags.DEFINE_integer('batch_size', 64,
  40. """Batch size.""")
  41. tf.app.flags.DEFINE_integer('num_batches', 100,
  42. """Number of batches to run.""")
  43. tf.app.flags.DEFINE_boolean('forward_only', False,
  44. """Only run the forward pass.""")
  45. tf.app.flags.DEFINE_boolean('forward_backward_only', False,
  46. """Only run the forward-forward pass.""")
  47. tf.app.flags.DEFINE_string('data_format', 'NHWC',
  48. """The data format for Convnet operations.
  49. Can be either NHWC or NCHW.
  50. """)
  51.  
  52. parameters = []
  53.  
  54. conv_counter = 1
  55. pool_counter = 1
  56. affine_counter = 1
  57.  
  58. def _conv(inpOp, nIn, nOut, kH, kW, dH, dW, padType):
  59. global conv_counter
  60. global parameters
  61. name = 'conv' + str(conv_counter)
  62. conv_counter += 1
  63. with tf.name_scope(name) as scope:
  64. kernel = tf.Variable(tf.truncated_normal([kH, kW, nIn, nOut],
  65. dtype=tf.float32,
  66. stddev=1e-1), name='weights')
  67. if FLAGS.data_format == 'NCHW':
  68. strides = [1, 1, dH, dW]
  69. else:
  70. strides = [1, dH, dW, 1]
  71. conv = tf.nn.conv2d(inpOp, kernel, strides, padding=padType)
  72. biases = tf.Variable(tf.constant(0.0, shape=[nOut], dtype=tf.float32),
  73. trainable=True, name='biases')
  74. #bias = tf.reshape(tf.nn.bias_add(conv, biases, conv.get_shape()))
  75. bias = tf.nn.bias_add(conv, biases)
  76. conv1 = tf.nn.relu(bias, name=scope)
  77. parameters += [kernel, biases]# saved to global var
  78. return conv1
  79.  
  80. def _affine(inpOp, nIn, nOut): #Dense Layers defined
  81. global affine_counter
  82. global parameters
  83. name = 'affine' + str(affine_counter)
  84. affine_counter += 1
  85. with tf.name_scope(name) as scope:
  86. kernel = tf.Variable(tf.truncated_normal([nIn, nOut],
  87. dtype=tf.float32,
  88. stddev=1e-1), name='weights')
  89. biases = tf.Variable(tf.constant(0.0, shape=[nOut], dtype=tf.float32),
  90. trainable=True, name='biases')
  91. affine1 = tf.nn.relu_layer(inpOp, kernel, biases, name=name)
  92. parameters += [kernel, biases]
  93. return affine1
  94.  
  95. def norm(name, l_input, lsize):
  96. return tf.nn.lrn(l_input, lsize, bias=1.0, alpha=0.0001 / 9.0, beta=0.75, name=name)
  97.  
  98. def _mpool(inpOp, kH, kW, dH, dW): # Max pooling
  99. global pool_counter
  100. global parameters
  101. name = 'pool' + str(pool_counter)
  102. pool_counter += 1
  103. if FLAGS.data_format == 'NCHW':
  104. ksize = [1, 1, kH, kW]
  105. strides = [1, 1, dH, dW]
  106. else:
  107. ksize = [1, kH, kW, 1]
  108. strides = [1, dH, dW, 1]
  109. return tf.nn.max_pool(inpOp,
  110. ksize=ksize,
  111. strides=strides,
  112. padding='VALID',
  113. name=name)
  114.  
  115. def loss(logits, labels): # loss function
  116. batch_size = tf.size(labels)
  117. labels = tf.expand_dims(labels, 1)
  118. indices = tf.expand_dims(tf.range(0, batch_size, 1), 1)
  119. concated = tf.concat(1, [indices, labels])
  120. onehot_labels = tf.sparse_to_dense(
  121. concated, tf.pack([batch_size, 1000]), 1.0, 0.0)
  122. cross_entropy = tf.nn.softmax_cross_entropy_with_logits(logits,
  123. onehot_labels,
  124. name='xentropy')
  125. loss = tf.reduce_mean(cross_entropy, name='xentropy_mean')
  126.  
  127. def resize_im(im, nh, nw):
  128. im=np.copy(im)
  129. h, w, _ = im.shape
  130. im = skimage.transform.resize(im, (nh, nw), preserve_range=True)
  131. return im
  132.  
  133. def create_class_vec(val,nuoclasses):
  134. x=np.zeros(nuoclasses)
  135. x[val]=1
  136. return x
  137.  
  138.  
  139. def Vgg_single_frame(_X,_dropout): # Network definiton
  140. #_X = tf.reshape(_X, shape=[-1, 227, 227, 3])
  141. conv1 = _conv (_X, 3, 96, 7, 7, 2, 2, 'SAME')# _conv(inpOp, nIn, nOut, kH, kW, dH, dW, padType)
  142. pool1 = _mpool(conv1, 3, 3, 2, 2)#_mpool(inpOp, kH, kW, dH, dW)
  143. norm1 = norm('norm1', pool1, lsize=5)
  144. conv2 = _conv (norm1, 96, 384, 5, 5, 2, 2, 'SAME')
  145. pool2 = _mpool(conv2, 3, 3, 2, 2)
  146. norm2 = norm('norm2', pool2, lsize=5)
  147. conv3 = _conv (norm2, 384, 512, 3, 3, 1, 1, 'VALID')
  148. conv4 = _conv (conv3, 512, 512, 3, 3, 1, 1, 'VALID')
  149. conv5 = _conv (conv4, 512, 384, 3, 3, 1, 1, 'VALID')
  150. pool5 = _mpool(conv5, 3, 3, 2, 2)
  151. resh1 = tf.reshape(pool5, [-1, 3*3*384])
  152. dense1 = _affine(resh1, 3*3*384, 4096)
  153. drop1= tf.nn.dropout(dense1, _dropout)
  154. dense2= _affine(drop1, 4096, 4096)
  155. drop2= tf.nn.dropout(dense2, _dropout)
  156. affn3 = _affine(drop2, 4096, 101)
  157.  
  158. return affn3
  159.  
  160. def train_next_batch(batch_size):
  161. temp_data=np.ndarray(shape=(batch_size,227,227,3),dtype=float)
  162. temp_class=np.ndarray(shape=(batch_size,n_classes),dtype=float)
  163. for idx,x in enumerate(train_data[train_i:train_i+batch_size]):
  164. temp_data[idx,:,:,:]=resize_im(cv2.imread(x,1),227,227)
  165. temp_class[idx,:]=create_class_vec(train_class[train_i+idx],101)
  166. return temp_data,temp_class
  167.  
  168. def test_next_batch(batch_size):
  169. temp_data=np.ndarray(shape=(batch_size,227,227,3),dtype=float)
  170. temp_class=np.ndarray(shape=(batch_size,n_classes),dtype=float)
  171. for idx,x in enumerate(test_data[test_i:test_i+batch_size]):
  172. temp_data[idx,:,:,:]=resize_im(cv2.imread(x,1),227,227)
  173. temp_class[idx,:]=create_class_vec(test_classs[train_i+idx],101)
  174. return temp_data,temp_class
  175.  
  176.  
  177.  
  178. # tf Graph input
  179. x = tf.placeholder(tf.float32, [None, 227,227,3])
  180. y = tf.placeholder(tf.float32, [None, n_classes])
  181. keep_prob = tf.placeholder(tf.float32) # dropout (keep probability)
  182. pred = Vgg_single_frame(x, keep_prob)
  183. cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(pred, y))
  184. optimizer = tf.train.GradientDescentOptimizer(learning_rate=learning_rate).minimize(cost)
  185. correct_pred = tf.equal(tf.argmax(pred,1), tf.argmax(y,1))
  186. accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))
  187.  
  188. init = tf.initialize_all_variables()
  189.  
  190. with tf.Session() as sess:
  191. sess.run(init)
  192. step = 1
  193. # Keep training until reach max iterations
  194. while step * batch_size < training_iters:
  195. batch_xs, batch_ys = train_next_batch(batch_size)
  196. train_i=train_i+batch_size
  197. # Fit training using batch data
  198. sess.run(optimizer, feed_dict={x: batch_xs, y: batch_ys, keep_prob: 0.5})
  199.  
  200. if step % display_step == 0:
  201. # Calculate batch accuracy
  202. acc = sess.run(accuracy, feed_dict={x: batch_xs, y: batch_ys, keep_prob: 0.5})
  203. # Calculate batch loss
  204. loss = sess.run(cost, feed_dict={x: batch_xs, y: batch_ys, keep_prob: 0.5})
  205. print "Iter " + str(step*batch_size) + ", Minibatch Loss= " + "{:.6f}".format(loss) + ", Training Accuracy= " + "{:.5f}".format(acc)
  206. test_xs,test_ys = test_next_batch(batch_size)
  207. test_i=test_i+batch_size
  208. print "Testing Accuracy:", sess.run(accuracy, feed_dict={x: test_xs, y:test_ys, keep_prob: 0.0})
  209. step += 1
  210. print "Optimization Finished!"
  211. # Calculate accuracy for 256 mnist test images
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement