Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from __future__ import absolute_import
- from __future__ import division
- from __future__ import print_function
- import os
- import PIL
- import PIL.Image
- import numpy as np
- import time
- import datetime
- width=28
- height=28
- classCount=2
- channels=3
- width_c2=7
- height_c2=7
- import tensorflow as tf
- sess = tf.InteractiveSession()
- def prepare():
- x=[]
- y=[]
- def add(x,y,dir,yy):
- for path in os.listdir(dir):
- xx=np.asarray(PIL.Image.open(dir+u"/"+path).convert('RGB')).reshape(width*height*channels)*1.0/255
- x += [ xx ]
- y += [ yy ]
- add(x,y,u"images28/0",[1.0,0.0])
- add(x,y,u"images28/1",[0.0,1.0])
- return np.array(x), np.array(y)
- def batch_iter(data, batch_size, num_epochs, shuffle=True):
- data = np.array(data)
- data_size = len(data)
- num_batches_per_epoch = int(len(data)/batch_size) + 1
- for epoch in range(num_epochs):
- # Shuffle the data at each epoch
- if shuffle:
- shuffle_indices = np.random.permutation(np.arange(data_size))
- shuffled_data = data[shuffle_indices]
- else:
- shuffled_data = data
- for batch_num in range(num_batches_per_epoch):
- start_index = batch_num * batch_size
- end_index = min((batch_num + 1) * batch_size, data_size)
- yield shuffled_data[start_index:end_index]
- x,y=prepare()
- #np.random.seed(10)
- shuffle_indices = np.random.permutation(np.arange(len(y)))
- x_shuffled = x[shuffle_indices]
- y_shuffled = y[shuffle_indices]
- dev_split=500
- x_train, x_dev = x_shuffled[:-dev_split], x_shuffled[-dev_split:]
- y_train, y_dev = y_shuffled[:-dev_split], y_shuffled[-dev_split:]
- print("Train/Dev split: {:d}/{:d}".format(len(y_train), len(y_dev)))
- def weight_variable(shape):
- initial = tf.truncated_normal(shape, stddev=0.1)
- return tf.Variable(initial)
- def bias_variable(shape):
- initial = tf.constant(0.1, shape=shape)
- return tf.Variable(initial)
- def conv2d(x, W):
- return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')
- def max_pool_2x2(x):
- return tf.nn.max_pool(x, ksize=[1, 2, 2, 1],strides=[1, 2, 2, 1], padding='SAME')
- px = tf.placeholder(tf.float32, shape=[None, width*height*channels], name="px")
- py = tf.placeholder(tf.float32, shape=[None, classCount], name="py")
- keep_prob = tf.placeholder(tf.float32, name="keep_prob")
- x_image = tf.reshape(px, [-1,width,height,channels])
- W_conv1 = weight_variable([5, 5, channels, 32])
- b_conv1 = bias_variable([32])
- h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)
- h_pool1 = max_pool_2x2(h_conv1)
- 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)
- h_pool2 = max_pool_2x2(h_conv2)
- W_fc1 = weight_variable([width_c2 * height_c2 * 64, 1024])
- b_fc1 = bias_variable([1024])
- h_pool2_flat = tf.reshape(h_pool2, [-1, width_c2*height_c2*64])
- h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)
- h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)
- W_fc2 = weight_variable([1024, classCount])
- b_fc2 = bias_variable([classCount])
- y_conv=tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2)
- timestamp = str(int(time.time()))
- out_dir = os.path.abspath(os.path.join(os.path.curdir, "runs", timestamp))
- print("Writing to {}\n".format(out_dir))
- global_step = tf.Variable(0, name="global_step", trainable=False)
- cross_entropy = tf.reduce_mean(-tf.reduce_sum(py * tf.log(y_conv), reduction_indices=[1]))
- train_step = tf.train.AdamOptimizer(1e-5).minimize(cross_entropy, global_step=global_step)
- predictions = tf.argmax(y_conv, 1, name="predictions")
- correct_prediction = tf.equal(tf.argmax(y_conv,1), tf.argmax(py,1))
- accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
- sess.run(tf.initialize_all_variables())
- checkpoint_dir = os.path.abspath(os.path.join(out_dir, "checkpoints"))
- checkpoint_prefix = os.path.join(checkpoint_dir, "model")
- if not os.path.exists(checkpoint_dir):
- os.makedirs(checkpoint_dir)
- saver = tf.train.Saver(tf.all_variables())
- batches = batch_iter(list(zip(x_train, y_train)), 100, 20000)
- i=0
- for batch in batches:
- x_batch, y_batch = zip(*batch)
- x_batch=np.array(x_batch)
- y_batch=np.array(y_batch)
- i+=1
- train_step.run(feed_dict={px: x_batch, py: y_batch, keep_prob: 0.5})
- if i%50 == 0:
- path = saver.save(sess, checkpoint_prefix, global_step=global_step)
- print("\nSaved model checkpoint to {}".format(path))
- print("test accuracy %g\n"%accuracy.eval(feed_dict={px: x_dev, py: y_dev, keep_prob: 1.0}))
- if i%10 == 0:
- train_accuracy = accuracy.eval(feed_dict={px: x_batch, py: y_batch, keep_prob: 1.0})
- print("step %d, training accuracy %g"%(i, train_accuracy))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement