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









發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章