1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
| import os
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow.contrib.layers import flatten
from tensorflow.examples.tutorials.mnist import input_data
from sklearn.utils import shuffle
"""
Data Loading
"""
dataPath='../dataset/MNIST_data/'
mnist = input_data.read_data_sets(dataPath, one_hot=True)
# read the images and reformat the image shape from [img_num,img_height,img_width] to [img_num,img_height,img_width,1]
img_width = 28
img_height = 28
images = mnist.train.images
img_num, _ = images.shape
images = np.reshape(images,(img_num,img_height,img_width))
images = images[...,np.newaxis]
print('(Input to CNN) Images with shape {}'.format(images.shape))
# read the labels
labels1Hot = mnist.train.labels
print('(Input to CNN) labels1Hot.shape = {}'.format(labels1Hot.shape))
labels = np.argmax(labels1Hot,axis=1)
labels = labels[...,np.newaxis]
print('labels.shape = {}'.format(labels.shape))
n_classes = len(np.unique(labels))
# load the validation set
images_valid = mnist.validation.images
img_num_valid = len(images_valid)
images_valid = np.reshape(images_valid,(img_num_valid,img_height,img_width))
images_valid = images_valid[...,np.newaxis]
labels1Hot_valid = mnist.validation.labels
print('Having %d number of validation images' % img_num_valid)
# plotting sample images
plt.figure(figsize=(15,5))
for i in np.arange(2*7):
random_idx = np.random.randint(0,img_num)
plt.subplot(2,7,i+1)
plt.imshow(images[random_idx][...,0],cmap='gray')
plt.title(labels[random_idx][0])
"""
First define the hyper-parameters
"""
# Hyper-parameters
EPOCHS = 30
BATCH_SIZE = 512
rate = 0.01
depth_list = [512, 256, 128]
cNum = 1
"""
Define the input output tensors
"""
# using one-hot decoding
x = tf.placeholder(tf.float32, (None, img_height, img_width, cNum))
one_hot_y = tf.placeholder(tf.int32, (None, n_classes))
#one_hot_y = tf.one_hot(y, n_classes)
"""
Define the graph and construct it
"""
z0 = flatten(x)
w0 = tf.get_variable('w0', shape=[img_width*img_height, depth_list[0]], initializer=tf.random_uniform_initializer(-0.1,0.1))
b0 = tf.get_variable('b0', [depth_list[0]], initializer=tf.zeros_initializer)
y0 = tf.nn.xw_plus_b(z0, w0, b0)
z1 = tf.nn.relu(y0)
w1 = tf.get_variable('w1', shape=[depth_list[0], depth_list[1]], initializer=tf.random_uniform_initializer(-0.1,0.1))
b1 = tf.get_variable('b1', [depth_list[1]], initializer=tf.zeros_initializer)
y1 = tf.nn.xw_plus_b(z1, w1, b1)
z2 = tf.nn.relu(y1)
w2 = tf.get_variable('w2', shape=[depth_list[1], depth_list[2]], initializer=tf.random_uniform_initializer(-0.1,0.1))
b2 = tf.get_variable('b2', [depth_list[2]], initializer=tf.zeros_initializer)
y2 = tf.nn.xw_plus_b(z2, w2, b2)
z3 = tf.nn.relu(y2)
w3 = tf.get_variable('w3', shape=[depth_list[2], n_classes], initializer=tf.random_uniform_initializer(-0.1,0.1))
b3 = tf.get_variable('b3', [n_classes], initializer=tf.zeros_initializer)
logits = tf.nn.xw_plus_b(z3, w3, b3)
cross_entropy = tf.nn.softmax_cross_entropy_with_logits(labels=one_hot_y,logits=logits)
loss = tf.reduce_mean(cross_entropy)
"""
Define gradients
"""
gll = tf.gradients(ys=loss,xs=logits)
gly2 = tf.gradients(ys=logits,xs=y2,grad_ys=gll)
gy2y1 = tf.gradients(ys=y2,xs=y1,grad_ys=gly2)
gy1y0 = tf.gradients(ys=y1,xs=y0,grad_ys=gy2y1)
glw3 = tf.gradients(ys=logits,xs=w3,grad_ys=gll)
glb3 = tf.gradients(ys=logits,xs=b3,grad_ys=gll)
gy2w2 = tf.gradients(ys=y2,xs=w2,grad_ys=gly2)
gy2b2 = tf.gradients(ys=y2,xs=b2,grad_ys=gly2)
gy1w1 = tf.gradients(ys=y1,xs=w1,grad_ys=gy2y1)
gy1b1 = tf.gradients(ys=y1,xs=b1,grad_ys=gy2y1)
gy0w0 = tf.gradients(ys=y0,xs=w0,grad_ys=gy1y0)
gy0b0 = tf.gradients(ys=y0,xs=b0,grad_ys=gy1y0)
update_w3 = tf.assign_add(w3,-rate*glw3[0])
update_b3 = tf.assign_add(b3,-rate*glb3[0])
update_w2 = tf.assign_add(w2,-rate*gy2w2[0])
update_b2 = tf.assign_add(b2,-rate*gy2b2[0])
update_w1 = tf.assign_add(w1,-rate*gy1w1[0])
update_b1 = tf.assign_add(b1,-rate*gy1b1[0])
update_w0 = tf.assign_add(w0,-rate*gy0w0[0])
update_b0 = tf.assign_add(b0,-rate*gy0b0[0])
training_operation = [update_w3, update_b3, update_w2, update_b2, update_w1, update_b1, update_w0, update_b0]
"""
Define accuracy evaluation
"""
# calculate the average accuracy by calling evaluate(X_data, y_data)
correct_prediction = tf.equal(tf.argmax(logits, axis=1), tf.argmax(one_hot_y, axis=1))
accuracy_operation = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
def evaluate(X_data, y_data):
num_examples = len(X_data)
total_accuracy = 0
sess = tf.get_default_session()
for offset in range(0, num_examples, BATCH_SIZE):
batch_x, batch_y = X_data[offset:offset+BATCH_SIZE], y_data[offset:offset+BATCH_SIZE]
accuracy = sess.run(accuracy_operation, feed_dict={x: batch_x, one_hot_y: batch_y})
total_accuracy += (accuracy * len(batch_x))
return total_accuracy / num_examples
"""
Run Session
"""
### Train your model here.
import time
if not os.path.isdir('./models'):
os.makedirs('./models')
#saver = tf.train.Saver()
accumulate_time = 0.0
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
num_examples = img_num
print("Training...")
print()
train_accuracy = np.zeros(EPOCHS)
validation_accuracy = np.zeros(EPOCHS)
for i in range(EPOCHS):
stime = time.time()
acc_train_accuracy = 0
X_train, y_train = shuffle(images, labels1Hot)
for offset in range(0, num_examples, BATCH_SIZE):
end = offset + BATCH_SIZE
batch_x, batch_y = X_train[offset:end], y_train[offset:end]
sess.run(training_operation, feed_dict={x: batch_x, one_hot_y: batch_y})
etime = time.time()
accumulate_time += etime - stime
validation_accuracy[i] = evaluate(images_valid, labels1Hot_valid)
print("EPOCH {} ...".format(i+1))
print("Validation Accuracy = {:.3f}".format(validation_accuracy[i]))
print()
print('Cost time: ' + str(accumulate_time) + ' sec.')
|