Advertisement
Guest User

Untitled

a guest
Jun 30th, 2016
155
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.77 KB | None | 0 0
  1. from __future__ import absolute_import
  2. from __future__ import division
  3. from __future__ import print_function
  4.  
  5. import os
  6. import PIL
  7. import PIL.Image
  8. import numpy as np
  9. import time
  10. import datetime
  11.  
  12. width=28
  13. height=28
  14. classCount=2
  15. channels=3
  16.  
  17. width_c2=7
  18. height_c2=7
  19.  
  20. import tensorflow as tf
  21. sess = tf.InteractiveSession()
  22.  
  23. def prepare():
  24.     x=[]
  25.     y=[]
  26.    
  27.     def add(x,y,dir,yy):
  28.         for path in os.listdir(dir):
  29.             xx=np.asarray(PIL.Image.open(dir+u"/"+path).convert('RGB')).reshape(width*height*channels)*1.0/255
  30.            
  31.             x += [ xx ]
  32.             y += [ yy ]
  33.    
  34.     add(x,y,u"images28/0",[1.0,0.0])
  35.     add(x,y,u"images28/1",[0.0,1.0])
  36.    
  37.     return np.array(x), np.array(y)
  38.  
  39. def batch_iter(data, batch_size, num_epochs, shuffle=True):
  40.     data = np.array(data)
  41.     data_size = len(data)
  42.     num_batches_per_epoch = int(len(data)/batch_size) + 1
  43.     for epoch in range(num_epochs):
  44.         # Shuffle the data at each epoch
  45.         if shuffle:
  46.             shuffle_indices = np.random.permutation(np.arange(data_size))
  47.             shuffled_data = data[shuffle_indices]
  48.         else:
  49.             shuffled_data = data
  50.         for batch_num in range(num_batches_per_epoch):
  51.             start_index = batch_num * batch_size
  52.             end_index = min((batch_num + 1) * batch_size, data_size)
  53.             yield shuffled_data[start_index:end_index]
  54.  
  55. x,y=prepare()
  56.  
  57. #np.random.seed(10)
  58. shuffle_indices = np.random.permutation(np.arange(len(y)))
  59. x_shuffled = x[shuffle_indices]
  60. y_shuffled = y[shuffle_indices]
  61. dev_split=500
  62. x_train, x_dev = x_shuffled[:-dev_split], x_shuffled[-dev_split:]
  63. y_train, y_dev = y_shuffled[:-dev_split], y_shuffled[-dev_split:]
  64. print("Train/Dev split: {:d}/{:d}".format(len(y_train), len(y_dev)))
  65.  
  66. def weight_variable(shape):
  67.     initial = tf.truncated_normal(shape, stddev=0.1)
  68.     return tf.Variable(initial)
  69.  
  70. def bias_variable(shape):
  71.     initial = tf.constant(0.1, shape=shape)
  72.     return tf.Variable(initial)
  73.  
  74. def conv2d(x, W):
  75.     return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')
  76.  
  77. def max_pool_2x2(x):
  78.     return tf.nn.max_pool(x, ksize=[1, 2, 2, 1],strides=[1, 2, 2, 1], padding='SAME')
  79.  
  80. px = tf.placeholder(tf.float32, shape=[None, width*height*channels], name="px")
  81. py = tf.placeholder(tf.float32, shape=[None, classCount], name="py")
  82. keep_prob = tf.placeholder(tf.float32, name="keep_prob")
  83. x_image = tf.reshape(px, [-1,width,height,channels])
  84.  
  85. W_conv1 = weight_variable([5, 5, channels, 32])
  86. b_conv1 = bias_variable([32])
  87. h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)
  88. h_pool1 = max_pool_2x2(h_conv1)
  89.  
  90. W_conv2 = weight_variable([5, 5, 32, 64])
  91. b_conv2 = bias_variable([64])
  92. h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)
  93. h_pool2 = max_pool_2x2(h_conv2)
  94.  
  95. W_fc1 = weight_variable([width_c2 * height_c2 * 64, 1024])
  96. b_fc1 = bias_variable([1024])
  97. h_pool2_flat = tf.reshape(h_pool2, [-1, width_c2*height_c2*64])
  98. h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)
  99.  
  100. h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)
  101.  
  102. W_fc2 = weight_variable([1024, classCount])
  103. b_fc2 = bias_variable([classCount])
  104.  
  105. y_conv=tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2)
  106.  
  107. timestamp = str(int(time.time()))
  108. out_dir = os.path.abspath(os.path.join(os.path.curdir, "runs", timestamp))
  109. print("Writing to {}\n".format(out_dir))
  110.  
  111. global_step = tf.Variable(0, name="global_step", trainable=False)
  112.  
  113. cross_entropy = tf.reduce_mean(-tf.reduce_sum(py * tf.log(y_conv), reduction_indices=[1]))
  114. train_step = tf.train.AdamOptimizer(1e-5).minimize(cross_entropy, global_step=global_step)
  115. predictions = tf.argmax(y_conv, 1, name="predictions")
  116. correct_prediction = tf.equal(tf.argmax(y_conv,1), tf.argmax(py,1))
  117. accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
  118. sess.run(tf.initialize_all_variables())
  119.  
  120.  
  121. checkpoint_dir = os.path.abspath(os.path.join(out_dir, "checkpoints"))
  122. checkpoint_prefix = os.path.join(checkpoint_dir, "model")
  123. if not os.path.exists(checkpoint_dir):
  124.     os.makedirs(checkpoint_dir)
  125. saver = tf.train.Saver(tf.all_variables())
  126.  
  127. batches = batch_iter(list(zip(x_train, y_train)), 100, 20000)
  128. i=0
  129. for batch in batches:
  130.     x_batch, y_batch = zip(*batch)
  131.     x_batch=np.array(x_batch)
  132.     y_batch=np.array(y_batch)
  133.     i+=1
  134.    
  135.     train_step.run(feed_dict={px: x_batch, py: y_batch, keep_prob: 0.5})
  136.    
  137.     if i%50 == 0:
  138.         path = saver.save(sess, checkpoint_prefix, global_step=global_step)
  139.         print("\nSaved model checkpoint to {}".format(path))
  140.         print("test accuracy %g\n"%accuracy.eval(feed_dict={px: x_dev, py: y_dev, keep_prob: 1.0}))
  141.  
  142.     if i%10 == 0:
  143.         train_accuracy = accuracy.eval(feed_dict={px: x_batch, py: y_batch, keep_prob: 1.0})
  144.         print("step %d, training accuracy %g"%(i, train_accuracy))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement