Tensorflow 笔记 - 使用MNIST

通过一个比较熟悉的任务(MNIST分类任务),熟悉Tensorflow的一些基本操作。

学习任务

  1. 使用CNN训练一个MNIST分类器
  2. 输出Feature Map

Tensorboard的使用下次再说……

首先下载数据并载入查看。MNIST的csv数据可以在kaggle下载到。然后将10%的数据作为验证集。

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
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import tensorflow as tf
import random
train = pd.read_csv('./data/train.csv')
label = np.asarray(pd.get_dummies(train['label']))
train = np.asarray(train)
train = train[:,1:]
train = train / 255 # normalize input to 1
VALID_SIZE = round(np.shape(train)[0] * 0.1)
train_x = train[:-VALID_SIZE]
train_y = label[:-VALID_SIZE]
valid_x = train[-VALID_SIZE:]
valid_y = label[-VALID_SIZE:]
print('training set: %d\nvalidation set: %d'%(np.shape(train)[0], VALID_SIZE))
%matplotlib inline
f, axarr = plt.subplots(3, 5)
for i in range(3):
for j in range(5):
idx = random.randint(0, 10000)
arr = np.reshape(train[idx], (28, 28))
axarr[i, j].imshow(arr, cmap='gray')
f.subplots_adjust(hspace = 0.5, wspace = 0.5)
plt.show()

1
2
training set: 42000
validation set: 4200

预览数据

构建CNN,为了方便,我们需要创建几个帮助函数

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
sess = tf.InteractiveSession()
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')
def GetLeNet5():
x = tf.placeholder('float')
y_ = tf.placeholder('float')
with tf.name_scope('conv1'):
W_conv1 = weight_variable([5, 5, 1, 32])
b_conv1 = bias_variable([32])
x_image = tf.reshape(x, [-1, 28, 28, 1])
h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1, name='h_conv1')
h_pool1 = max_pool_2x2(h_conv1)
with tf.name_scope('conv2'):
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, name='h_conv2')
h_pool2 = max_pool_2x2(h_conv2)
with tf.name_scope('fc1'):
W_fc1 = weight_variable([7 * 7 * 64, 1024])
b_fc1 = bias_variable([1024])
h_pool2_flat = tf.reshape(h_pool2, [-1, 7 * 7 * 64])
h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1, name='h_fc1')
with tf.name_scope('fc2'):
keep_prob = tf.placeholder('float')
h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)
W_fc2 = weight_variable([1024, 10])
b_fc2 = bias_variable([10])
y_conv = tf.matmul(h_fc1_drop, W_fc2) + b_fc2
weights = {
'W_conv1': W_conv1, 'h_conv1': h_conv1,
'W_conv2': W_conv2, 'h_conv2': h_conv2
}
ends = {
'h_conv1': h_conv1, 'h_pool1': h_pool1,
'h_conv2': h_conv2, 'h_pool2': h_pool2
}
cross_entropy = tf.nn.softmax_cross_entropy_with_logits(logits=y_conv, labels=y_)
train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)
correct_prediction = tf.equal(tf.argmax(y_conv, 1), tf.argmax(y_, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, 'float'))
sess.run(tf.global_variables_initializer())
return x, y_, y_conv, train_step, correct_prediction, accuracy, keep_prob, weights, ends

下面我们训练模型。训练10个epoch,并查看模型在验证集上的结果:

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
x, y_, y_conv, train_step, correct_prediction, accuracy, keep_prob, \
weights, ends \
= GetLeNet5()
epoches = 10
batch_size = 50
total_step = 0
for epoch in range(epoches):
print('epoch %3d: '%(epoch + 1))
t = 0
while t < np.shape(train_x)[0]:
tt = t + batch_size
if tt > np.shape(train_x)[0]:
tt = np.shape(train_x)[0]
batch = (train_x[t:tt], train_y[t:tt])
if t%10000 == 0:
train_accuracy = accuracy.eval(feed_dict={
x:batch[0], y_: batch[1], keep_prob: 1.0})
print("step %5d, training accuracy %g"%(t, train_accuracy))
train_step.run(feed_dict={x: batch[0], y_: batch[1], keep_prob: 0.5})
t = tt
valid_acc = accuracy.eval(feed_dict={
x: valid_x, y_: valid_y, keep_prob: 1.0
})
print('validation accuarcy %g'%(valid_acc))

1
validation accuarcy 0.987143

最后查看卷积核激活情况:

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
# visualize kernel activation
# step 1: randomly choose a test case
idx = random.randint(0, 42000)
test = train[idx]
plt.matshow(np.reshape(test, (28, 28)), cmap='gray')
plt.show()
# step 2: feed & test
fmap1, fmap2, y_pred = \
sess.run([ends['h_conv1'], ends['h_conv2'], y_conv], \
feed_dict={x: test, keep_prob: 1.0})
fmap1 = np.reshape(np.asarray(fmap1), (28, 28, 32))
fmap2 = np.reshape(np.asarray(fmap2), (14, 14, 64))
print('predicted label: %d'%(np.argmax(y_pred[0])))
# step 3: output activated feature map
f, axarr = plt.subplots(4, 8)
for i in range(4):
for j in range(8):
arr = np.reshape(fmap1[:, :, i * 8 + j], (28, 28))
axarr[i, j].imshow(arr, cmap='gray')
axarr[i, j].set_xticks([])
axarr[i, j].set_yticks([])
plt.show()
f, axarr = plt.subplots(4, 16)
for i in range(4):
for j in range(16):
arr = np.reshape(fmap2[:, :, i * 8 + j], (14, 14))
axarr[i, j].imshow(arr, cmap='gray')
axarr[i, j].set_xticks([])
axarr[i, j].set_yticks([])
f.subplots_adjust(hspace = 0.1)
plt.show()

结果:

1
predicted label: 8

测试数据
卷积核预览
卷积核预览