tensorflow学习笔记之使用tensorflow进行MNIST分类(2)


接着上一篇:http://blog.csdn.net/IEEE_FELLOW/article/details/53012351

本文参考Yann LeCun的LeNet5经典架构,稍加ps得到下面适用于本手写识别的cnn结构,构造一个两层卷积神经网络,神经网络的结构如下图所示:

输入-卷积-pooling-卷积-pooling-全连接层-Dropout-Softmax输出


第一层卷积利用5*5的patch,32个卷积核,可以计算出32个特征。然后进行maxpooling。第二层卷积利用5*5的patch,64个卷积核,可以计算出64个特征。然后进行max pooling。卷积核的个数是我们自己设定,可以增加卷积核数目提高分类精度,但是那样会增加更大参数,提高计算成本。

这样输入是分辨率为28*28的图片。利用5*5的patch进行卷积。我们的卷积使用1步长(stride size),0填充模块(zero padded),这样得到的输出和输入是同一个大小。经过第一层卷积之后,卷积特征大小为28*28。然后通过ReLU函数激活。我们的pooling用简单传统的2x2大小的模板做max pooling,这样pooling后得到14*14大小的特征。经过第二层卷积后,卷积特征大小为14*14,然后通过ReLU函数激活,再经过pooling后得到特征大小为7*7。

现在,图片尺寸减小到7x7,我们加入一个有1024个神经元的全连接层,用于处理整个图片。我们把池化层输出的张量展开成一些向量,乘上权重矩阵,加上偏置,然后对其使用ReLU。

为了避免过拟合,在全连接层输出接上dropout层。Dropout层在训练时屏蔽一半的神经元。


DropOut Network


最后输出端为一个Softmax层用于分类。

以上是本教程的模型整体结构,下面将依次讲解该模型的tensorflow实现流程。

1         程序说明

1.1    加载MNIST数据集

用下面的代码将下载后的数据导入到你的项目里面,也可以直接复制粘贴到你的代码文件里面:

1.	from tensorflow.examples.tutorials.mnist import input_data  
2.	mnist = input_data.read_data_sets("MNIST_data/", one_hot=True) 

这里,mnist是一个轻量级的类。它以Numpy数组的形式存储着训练、校验和测试数据集。

1.2   运行TensorFlow的InteractiveSession

Tensorflow依赖于一个高效的C++后端来进行计算。与后端的这个连接叫做session。一般而言,使用TensorFlow 程序的流程是先创建一个图,然后在session中启动它。

这里,我们使用更加方便的InteractiveSession类。通过它,你可以更加灵活地构建你的代码。它能让你在运行图的时候,插入一些计算图,这些计算图是由某些操作(operations)构成的。这对于工作在交互式环境中的人们来说非常便利,比如使用IPython。如果你没有使用InteractiveSession,那么你需要在启动session之前构建整个计算图,然后启动该计算图。

1.	import tensorflow as tf  
2.	sess = tf.InteractiveSession()  

1.3   构建Softmax 回归模型

占位符

我们通过为输入图像和目标输出类别创建节点,来开始构建计算图。

1.	x = tf.placeholder("float", shape=[None, 784])  
2.	y_ = tf.placeholder("float", shape=[None, 10])  

这里的x和y并不是特定的值,相反,他们都只是一个占位符,可以在TensorFlow运行某一计算时根据该占位符输入具体的值。

输入图片x是一个2维的浮点数张量。这里,分配给它的shape为[None, 784],其中784是一张展平的MNIST图片的维度。None表示其值大小不定,在这里作为第一个维度值,用以指代batch的大小,意即x的数量不定。输出类别值y_也是一个2维张量,其中每一行为一个10维的one-hot向量,用于代表对应某一MNIST图片的类别。

虽然placeholder的shape参数是可选的,但有了它,TensorFlow能够自动捕捉因数据维度不一致导致的错误。

1.4    权重初始化

变量

我们现在为模型定义权重W和偏置b。可以将它们当作额外的输入量,但是TensorFlow有一个更好的处理方式:变量。一个变量代表着TensorFlow计算图中的一个值,能够在计算过程中使用,甚至进行修改。在机器学习的应用过程中,模型参数一般用Variable来表示。

我们在调用tf.Variable的时候传入初始值。

为了创建这个模型,我们需要创建大量的权重和偏置项。这个模型中的权重在初始化时应该加入少量的噪声来打破对称性以及避免0梯度。由于我们使用的是ReLU神经元,因此比较好的做法是用一个较小的正数来初始化偏置项,以避免神经元节点输出恒为0的问题(deadneurons)。为了不在建立模型的时候反复做初始化操作,我们定义两个函数用于初始化。

1.	def weight_variable(shape):  
2.	  initial = tf.truncated_normal(shape, stddev=0.1)  
3.	  return tf.Variable(initial)  
4.	  
5.	def bias_variable(shape):  
6.	  initial = tf.constant(0.1, shape=shape)  
7.	  return tf.Variable(initial)  

变量需要通过seesion初始化后,才能在session中使用。这一初始化步骤为,为初始值指定具体值(本例当中是全为零),并将其分配给每个变量,可以一次性为所有变量完成此操作。

1.	sess.run(tf.initialize_all_variables()) 

1.5    卷积和Pooling

 

TensorFlow在卷积和Pooling上有很强的灵活性。我们怎么处理边界?步长应该设多大?在这个实例里,我们的卷积使用1步长(stride size),0填充模块(zero padded),保证输出和输入是同一个大小。我们的pooling用简单传统的2x2大小的模板做maxpooling。为了代码更简洁,我们把这部分抽象成一个函数。

1.	def conv2d(x, W):  
2.	  return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')  
3.	  
4.	def max_pool_2x2(x):  
5.	  return tf.nn.max_pool(x, ksize=[1, 2, 2, 1],  
6.	                        strides=[1, 2, 2, 1], padding='SAME')  

1.6    第一层卷积

现在我们可以开始实现第一层了。它由一个卷积接一个max pooling完成。卷积在每个5x5的patch中算出32个特征。卷积的权重张量形状是[5, 5, 1, 32],前两个维度是patch的大小,接着是输入的通道数目,最后是输出的通道数目。 而对于每一个输出通道都有一个对应的偏置量。

1.	W_conv1 = weight_variable([5, 5, 1, 32])  
2.	b_conv1 = bias_variable([32]) 

为了用这一层,我们把x变成一个4d向量,其第2、第3维对应图片的宽、高,最后一维代表图片的颜色通道数(因为是灰度图所以这里的通道数为1,如果是rgb彩色图,则为3)。

1.	x_image = tf.reshape(x, [-1,28,28,1])  

我们把x_image和权值向量进行卷积,加上偏置项,然后应用ReLU激活函数,最后进行maxpooling。

1.	h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)  
2.	h_pool1 = max_pool_2x2(h_conv1)  

1.7    第二层卷积

 

为了构建一个更深的网络,我们会把几个类似的层堆叠起来。第二层中,每个5x5的patch会得到64个特征。

1.	W_conv2 = weight_variable([5, 5, 32, 64])  
2.	b_conv2 = bias_variable([64])  
3.	  
4.	h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)  
5.	h_pool2 = max_pool_2x2(h_conv2)  

1.8   全连接层(fully-connectedlayer)

 

现在,图片尺寸减小到7x7,我们加入一个有1024个神经元的全连接层,用于处理整个图片。我们把池化层输出的张量reshape成一些向量,乘上权重矩阵,加上偏置,然后对其使用ReLU。

1.	W_fc1 = weight_variable([7 * 7 * 64, 1024])  
2.	b_fc1 = bias_variable([1024])  
3.	  
4.	h_pool2_flat = tf.reshape(h_pool2, [-1, 7*7*64])  
5.	h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)  

1.9    Dropout

 

为了减少过拟合,我们在输出层之前加入dropout。我们用一个placeholder来代表一个神经元的输出在dropout中保持不变的概率。这样我们可以在训练过程中启用dropout,在测试过程中关闭dropout。 TensorFlow的tf.nn.dropout操作除了可以屏蔽神经元的输出外,还会自动处理神经元输出值的scale。所以用dropout的时候可以不用考虑scale。

1.	keep_prob = tf.placeholder("float")  
2.	h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob) 

对于本教程所搭建的小型卷积网络,实际上有没有dropout层性能几乎相同。dropout通常能够很好的减少过拟合,特别适用于训练非常大型的神经网络。

1.10    输出层

 

最后,我们添加一个softmax层,就像前面的单层softmax regression一样。

1.	W_fc2 = weight_variable([1024, 10])  
2.	b_fc2 = bias_variable([10])  
3.	  
4.	y_conv=tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2)

1.11    训练和评估模型

为了进行训练和评估,我们用更加复杂的ADAM进行优化,在feed_dict中加入额外的参数keep_prob来控制dropout比例。然后每100次迭代输出一次日志。

1.	cross_entropy = -tf.reduce_sum(y_*tf.log(y_conv))  
2.	train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)  
3.	correct_prediction = tf.equal(tf.argmax(y_conv,1), tf.argmax(y_,1))  
4.	accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))  
5.	sess.run(tf.initialize_all_variables())  
6.	for i in range(20000):  
7.	  batch = mnist.train.next_batch(50)  
8.	  if i%100 == 0:  
9.	    train_accuracy = accuracy.eval(feed_dict={  
10.	        x:batch[0], y_: batch[1], keep_prob: 1.0})  
11.	    print "step %d, training accuracy %g"%(i, train_accuracy)  
12.	  train_step.run(feed_dict={x: batch[0], y_: batch[1], keep_prob: 0.5})  
13.	  
14.	print "test accuracy %g"%accuracy.eval(feed_dict={  
15.	    x: mnist.test.images, y_: mnist.test.labels, keep_prob: 1.0}) 
注意15行因为测试样本太大,可能会出现内存溢出:


那么将测试集进行划分成batch,然后进行测试:

1.	for i in xrange(10):  
2.	    testSet = mnist.test.next_batch(1000)  
3.	    print("test accuracy %g"%accuracy.eval(feed_dict={ x: testSet[0], y_: testSet[1], keep_prob: 1.0}))  
4.	  
5.	#print "test accuracy %g" % accuracy.eval(feed_dict={x:mnist.test.images, y_:mnist.test.labels, keep_prob:1.0})  

上述流程,在最终测试集上的准确率大概是99.22%。




  参考资料:

http://download.tensorflow.org/paper/whitepaper2015.pdf

https://www.tensorflow.org/versions/r0.11/get_started/basic_usage.html#basic-usage


附上完整代码:

MLP_CNN.py

1.	# load MNIST data  
2.	import input_data  
3.	mnist = input_data.read_data_sets("MNIST_data", one_hot=True)  
4.	  
5.	# start tensorflow interactiveSession  
6.	import tensorflow as tf  
7.	sess = tf.InteractiveSession()  
8.	  
9.	# weight initialization  
10.	def weight_variable(shape):  
11.	    initial = tf.truncated_normal(shape, stddev=0.1)  
12.	    return tf.Variable(initial)  
13.	  
14.	def bias_variable(shape):  
15.	    initial = tf.constant(0.1, shape = shape)  
16.	    return tf.Variable(initial)  
17.	  
18.	# convolution  
19.	def conv2d(x, W):  
20.	    return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')  
21.	# pooling  
22.	def max_pool_2x2(x):  
23.	    return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')  
24.	  
25.	# Create the model  
26.	# placeholder  
27.	x = tf.placeholder("float", [None, 784])  
28.	y_ = tf.placeholder("float", [None, 10])  
29.	  
30.	# first convolutinal layer  
31.	w_conv1 = weight_variable([5, 5, 1, 32])  
32.	b_conv1 = bias_variable([32])  
33.	  
34.	x_image = tf.reshape(x, [-1, 28, 28, 1])  
35.	  
36.	h_conv1 = tf.nn.relu(conv2d(x_image, w_conv1) + b_conv1)  
37.	h_pool1 = max_pool_2x2(h_conv1)  
38.	  
39.	# second convolutional layer  
40.	w_conv2 = weight_variable([5, 5, 32, 64])  
41.	b_conv2 = bias_variable([64])  
42.	  
43.	h_conv2 = tf.nn.relu(conv2d(h_pool1, w_conv2) + b_conv2)  
44.	h_pool2 = max_pool_2x2(h_conv2)  
45.	  
46.	# densely connected layer  
47.	w_fc1 = weight_variable([7*7*64, 1024])  
48.	b_fc1 = bias_variable([1024])  
49.	  
50.	h_pool2_flat = tf.reshape(h_pool2, [-1, 7*7*64])  
51.	h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, w_fc1) + b_fc1)  
52.	  
53.	# dropout  
54.	keep_prob = tf.placeholder("float")  
55.	h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)  
56.	  
57.	# readout layer  
58.	w_fc2 = weight_variable([1024, 10])  
59.	b_fc2 = bias_variable([10])  
60.	  
61.	y_conv = tf.nn.softmax(tf.matmul(h_fc1_drop, w_fc2) + b_fc2)  
62.	  
63.	# train and evaluate the model  
64.	cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(y_conv, y_))  
65.	train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)  
66.	correct_prediction = tf.equal(tf.argmax(y_conv,1), tf.argmax(y_,1))  
67.	accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))  
68.	sess.run(tf.initialize_all_variables())  
69.	for i in range(20000):  
70.	  batch = mnist.train.next_batch(50)  
71.	  if i%100 == 0:  
72.	    train_accuracy = accuracy.eval(feed_dict={  
73.	        x:batch[0], y_: batch[1], keep_prob: 1.0})  
74.	    print("step %d, training accuracy %g"%(i, train_accuracy))  
75.	  train_step.run(feed_dict={x: batch[0], y_: batch[1], keep_prob: 0.5})  
76.	for i in xrange(10):  
77.	    testSet = mnist.test.next_batch(1000)  
78.	    print("test accuracy %g"%accuracy.eval(feed_dict={ x: testSet[0], y_: testSet[1], keep_prob: 1.0}))  
79.	  
80.	#print "test accuracy %g" % accuracy.eval(feed_dict={x:mnist.test.images, y_:mnist.test.labels, keep_prob:1.0}) 

input_data.py

# Copyright 2015 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Functions for downloading and reading MNIST data."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import gzip
import os
import tensorflow.python.platform
import numpy
from six.moves import urllib
from six.moves import xrange  # pylint: disable=redefined-builtin
import tensorflow as tf
SOURCE_URL = 'http://yann.lecun.com/exdb/mnist/'
def maybe_download(filename, work_directory):
  """Download the data from Yann's website, unless it's already here."""
  if not os.path.exists(work_directory):
    os.mkdir(work_directory)
  filepath = os.path.join(work_directory, filename)
  if not os.path.exists(filepath):
    filepath, _ = urllib.request.urlretrieve(SOURCE_URL + filename, filepath)
    statinfo = os.stat(filepath)
    print('Successfully downloaded', filename, statinfo.st_size, 'bytes.')
  return filepath
def _read32(bytestream):
  dt = numpy.dtype(numpy.uint32).newbyteorder('>')
  return numpy.frombuffer(bytestream.read(4), dtype=dt)[0]
def extract_images(filename):
  """Extract the images into a 4D uint8 numpy array [index, y, x, depth]."""
  print('Extracting', filename)
  with gzip.open(filename) as bytestream:
    magic = _read32(bytestream)
    if magic != 2051:
      raise ValueError(
          'Invalid magic number %d in MNIST image file: %s' %
          (magic, filename))
    num_images = _read32(bytestream)
    rows = _read32(bytestream)
    cols = _read32(bytestream)
    buf = bytestream.read(rows * cols * num_images)
    data = numpy.frombuffer(buf, dtype=numpy.uint8)
    data = data.reshape(num_images, rows, cols, 1)
    return data
def dense_to_one_hot(labels_dense, num_classes=10):
  """Convert class labels from scalars to one-hot vectors."""
  num_labels = labels_dense.shape[0]
  index_offset = numpy.arange(num_labels) * num_classes
  labels_one_hot = numpy.zeros((num_labels, num_classes))
  labels_one_hot.flat[index_offset + labels_dense.ravel()] = 1
  return labels_one_hot
def extract_labels(filename, one_hot=False):
  """Extract the labels into a 1D uint8 numpy array [index]."""
  print('Extracting', filename)
  with gzip.open(filename) as bytestream:
    magic = _read32(bytestream)
    if magic != 2049:
      raise ValueError(
          'Invalid magic number %d in MNIST label file: %s' %
          (magic, filename))
    num_items = _read32(bytestream)
    buf = bytestream.read(num_items)
    labels = numpy.frombuffer(buf, dtype=numpy.uint8)
    if one_hot:
      return dense_to_one_hot(labels)
    return labels
class DataSet(object):
  def __init__(self, images, labels, fake_data=False, one_hot=False,
               dtype=tf.float32):
    """Construct a DataSet.
    one_hot arg is used only if fake_data is true.  `dtype` can be either
    `uint8` to leave the input as `[0, 255]`, or `float32` to rescale into
    `[0, 1]`.
    """
    dtype = tf.as_dtype(dtype).base_dtype
    if dtype not in (tf.uint8, tf.float32):
      raise TypeError('Invalid image dtype %r, expected uint8 or float32' %
                      dtype)
    if fake_data:
      self._num_examples = 10000
      self.one_hot = one_hot
    else:
      assert images.shape[0] == labels.shape[0], (
          'images.shape: %s labels.shape: %s' % (images.shape,
                                                 labels.shape))
      self._num_examples = images.shape[0]
      # Convert shape from [num examples, rows, columns, depth]
      # to [num examples, rows*columns] (assuming depth == 1)
      assert images.shape[3] == 1
      images = images.reshape(images.shape[0],
                              images.shape[1] * images.shape[2])
      if dtype == tf.float32:
        # Convert from [0, 255] -> [0.0, 1.0].
        images = images.astype(numpy.float32)
        images = numpy.multiply(images, 1.0 / 255.0)
    self._images = images
    self._labels = labels
    self._epochs_completed = 0
    self._index_in_epoch = 0
  @property
  def images(self):
    return self._images
  @property
  def labels(self):
    return self._labels
  @property
  def num_examples(self):
    return self._num_examples
  @property
  def epochs_completed(self):
    return self._epochs_completed
  def next_batch(self, batch_size, fake_data=False):
    """Return the next `batch_size` examples from this data set."""
    if fake_data:
      fake_image = [1] * 784
      if self.one_hot:
        fake_label = [1] + [0] * 9
      else:
        fake_label = 0
      return [fake_image for _ in xrange(batch_size)], [
          fake_label for _ in xrange(batch_size)]
    start = self._index_in_epoch
    self._index_in_epoch += batch_size
    if self._index_in_epoch > self._num_examples:
      # Finished epoch
      self._epochs_completed += 1
      # Shuffle the data
      perm = numpy.arange(self._num_examples)
      numpy.random.shuffle(perm)
      self._images = self._images[perm]
      self._labels = self._labels[perm]
      # Start next epoch
      start = 0
      self._index_in_epoch = batch_size
      assert batch_size <= self._num_examples
    end = self._index_in_epoch
    return self._images[start:end], self._labels[start:end]
def read_data_sets(train_dir, fake_data=False, one_hot=False, dtype=tf.float32):
  class DataSets(object):
    pass
  data_sets = DataSets()
  if fake_data:
    def fake():
      return DataSet([], [], fake_data=True, one_hot=one_hot, dtype=dtype)
    data_sets.train = fake()
    data_sets.validation = fake()
    data_sets.test = fake()
    return data_sets
  TRAIN_IMAGES = 'train-images-idx3-ubyte.gz'
  TRAIN_LABELS = 'train-labels-idx1-ubyte.gz'
  TEST_IMAGES = 't10k-images-idx3-ubyte.gz'
  TEST_LABELS = 't10k-labels-idx1-ubyte.gz'
  VALIDATION_SIZE = 5000
  local_file = maybe_download(TRAIN_IMAGES, train_dir)
  train_images = extract_images(local_file)
  local_file = maybe_download(TRAIN_LABELS, train_dir)
  train_labels = extract_labels(local_file, one_hot=one_hot)
  local_file = maybe_download(TEST_IMAGES, train_dir)
  test_images = extract_images(local_file)
  local_file = maybe_download(TEST_LABELS, train_dir)
  test_labels = extract_labels(local_file, one_hot=one_hot)
  validation_images = train_images[:VALIDATION_SIZE]
  validation_labels = train_labels[:VALIDATION_SIZE]
  train_images = train_images[VALIDATION_SIZE:]
  train_labels = train_labels[VALIDATION_SIZE:]
  data_sets.train = DataSet(train_images, train_labels, dtype=dtype)
  data_sets.validation = DataSet(validation_images, validation_labels,
                                 dtype=dtype)
  data_sets.test = DataSet(test_images, test_labels, dtype=dtype)
  return data_sets









Guess you like

Origin blog.csdn.net/IEEE_FELLOW/article/details/53011932