之前的文章 TensorFlow的安裝與初步了解,從TensorFlow的安裝到基本的模塊單元進(jìn)行了初步的講解。今天這篇文章我們使用TensorFlow針對于手寫體識別數(shù)據(jù)集MNIST搭建一個softmax的多分類模型。 本文的程序主要分為兩大模塊,一個是對MNIST數(shù)據(jù)集的下載、解壓、重構(gòu)以及數(shù)據(jù)集的構(gòu)建;另一個是構(gòu)建softmax圖及訓(xùn)練圖。本程序主要是想去理解包含在這些代碼里面的設(shè)計思想:TensorFlow工作流程和機(jī)器學(xué)習(xí)的基本概念。本文所使用的數(shù)據(jù)集和Python源代碼都已經(jīng)上傳到我的GitHub(https://github.com/ml365/softmax_mnist),點(diǎn)擊文末閱讀原文直接跳轉(zhuǎn)下載頁面。 MNIST數(shù)據(jù)集的下載與重構(gòu) MNIST是一個入門級的計算機(jī)視覺數(shù)據(jù)集,它包含各種手寫數(shù)字圖片: 它也包含每一張圖片對應(yīng)的標(biāo)簽,告訴我們這個是數(shù)字幾。比如,上面這四張圖片的標(biāo)簽分別是5,0,4,1。 下載下來的數(shù)據(jù)集被分成兩部分:60000行的訓(xùn)練數(shù)據(jù)集(mnist.train)和10000行的測試數(shù)據(jù)集(mnist.test)。正如前面提到的一樣,每一個MNIST數(shù)據(jù)單元有兩部分組成:一張包含手寫數(shù)字的圖片和一個對應(yīng)的標(biāo)簽。我們把這些圖片設(shè)為“xs”,把這些標(biāo)簽設(shè)為“ys”。訓(xùn)練數(shù)據(jù)集和測試數(shù)據(jù)集都包含xs和ys,比如訓(xùn)練數(shù)據(jù)集的圖片是 mnist.train.images ,訓(xùn)練數(shù)據(jù)集的標(biāo)簽是 mnist.train.labels。將上述的圖像按行展開,因此,在MNIST訓(xùn)練數(shù)據(jù)集中,mnist.train.images 是一個形狀為 [60000, 784] 的張量,第一個維度數(shù)字用來索引圖片,第二個維度數(shù)字用來索引每張圖片中的像素點(diǎn)。在此張量里的每一個元素,都表示某張圖片里的某個像素的強(qiáng)度值,值介于0和1之間。如圖所示 數(shù)據(jù)處理的代碼如下所示 '''Functions for downloading and reading MNIST data.''' from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import gzip import collections import numpy from six.moves import xrange SOURCE_URL = 'http://yann./exdb/mnist/' Datasets = collections.namedtuple('Datasets', ['train', 'validation', 'test']) def _read32(bytestream): dt = numpy.dtype(numpy.uint32).newbyteorder('>') return numpy.frombuffer(bytestream.read(4), dtype=dt)[0] def extract_images(f): '''Extract the images into a 4D uint8 numpy array [index, y, x, depth].
Args: f: A file object that can be passed into a gzip reader. Returns: data: A 4D uint8 numpy array [index, y, x, depth]. Raises: ValueError: If the bytestream does not start with 2051. ''' print('Extracting', f.name) with gzip.GzipFile(fileobj=f) as bytestream: magic = _read32(bytestream) if magic != 2051: raise ValueError('Invalid magic number %d in MNIST image file: %s' % (magic, f.name)) 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): '''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(f, one_hot=False, num_classes=10): '''Extract the labels into a 1D uint8 numpy array [index]. Args: f: A file object that can be passed into a gzip reader. one_hot: Does one hot encoding for the result. num_classes: Number of classes for the one hot encoding. Returns: labels: a 1D uint8 numpy array. Raises: ValueError: If the bystream doesn't start with 2049. ''' print('Extracting', f.name) with gzip.GzipFile(fileobj=f) as bytestream: magic = _read32(bytestream) if magic != 2049: raise ValueError('Invalid magic number %d in MNIST label file: %s' % (magic, f.name)) 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, num_classes) return labels class DataSet(object): def __init__(self, images, labels, fake_data=False, one_hot=False, dtype=numpy.float32, reshape=True): '''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 = dtypes.as_dtype(dtype).base_dtype if dtype not in (numpy.uint8, numpy.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) if reshape: assert images.shape[3] == 1 images = images.reshape(images.shape[0], images.shape[1] * images.shape[2]) if dtype == numpy.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 <=>=> end = self._index_in_epoch return self._images[start:end], self._labels[start:end] def maybe_download(filename, work_directory, source_url): '''Download the data from source url, unless it's already here. Args: filename: string, name of the file in the directory. work_directory: string, path to working directory. source_url: url to download from if file doesn't exist. Returns: Path to resulting file. ''' filepath = os.path.join(work_directory, filename) print('filepath:%s' % filepath) return filepath def read_data_sets(train_dir, fake_data=False, one_hot=False, dtype=numpy.float32, reshape=True, validation_size=5000): if fake_data: def fake(): return DataSet([], [], fake_data=True, one_hot=one_hot, dtype=dtype) train = fake() validation = fake() test = fake() return Datasets(train=train, validation=validation, test=test) 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' local_file = maybe_download(TRAIN_IMAGES, train_dir, SOURCE_URL + TRAIN_IMAGES) with open(local_file, 'rb') as f: train_images = extract_images(f) local_file = maybe_download(TRAIN_LABELS, train_dir, SOURCE_URL + TRAIN_LABELS) with open(local_file, 'rb') as f: train_labels = extract_labels(f, one_hot=one_hot) local_file = maybe_download(TEST_IMAGES, train_dir, SOURCE_URL + TEST_IMAGES) with open(local_file, 'rb') as f: test_images = extract_images(f) local_file = maybe_download(TEST_LABELS, train_dir, SOURCE_URL + TEST_LABELS) with open(local_file, 'rb') as f: test_labels = extract_labels(f, one_hot=one_hot) if not 0 <= validation_size="">=><=>=> raise ValueError( 'Validation size should be between 0 and {}. Received: {}.' .format(len(train_images), validation_size)) validation_images = train_images[:validation_size] validation_labels = train_labels[:validation_size] train_images = train_images[validation_size:] train_labels = train_labels[validation_size:] train = DataSet(train_images, train_labels, dtype=dtype, reshape=reshape) validation = DataSet(validation_images, validation_labels, dtype=dtype, reshape=reshape) test = DataSet(test_images, test_labels, dtype=dtype, reshape=reshape) return Datasets(train=train, validation=validation, test=test) def load_mnist(train_dir='MNIST-data'): return read_data_sets(train_dir) softmax多分類算法簡述 softmax模型可以用來給不同的對象分配概率。即使在卷積勝境網(wǎng)絡(luò)中,最后一步也需要用softmax來分配概率。softmax回歸(softmax regression)分兩步: 為了得到一張給定圖片屬于某個特定數(shù)字類的證據(jù)(evidence),我們對圖片像素值進(jìn)行加權(quán)求和。如果這個像素具有很強(qiáng)的證據(jù)說明這張圖片不屬于該類,那么相應(yīng)的權(quán)值為負(fù)數(shù),相反如果這個像素?fù)碛杏欣淖C據(jù)支持這張圖片屬于這個類,那么權(quán)值是正數(shù)。因此對于給定的輸入圖片 x 它代表的是數(shù)字 i 的證據(jù)可以表示為 其中 Wi,j 代表權(quán)重, bi 代表數(shù)字 i 類的偏置量,j 代表給定圖片 x 的像素索引用于像素求和。然后用softmax函數(shù)可以把這些證據(jù)轉(zhuǎn)換成概率 y: 為了訓(xùn)練我們的模型,我們首先需要定義一個指標(biāo)來評估這個模型是好的。一個非常常見的,非常漂亮的成本函數(shù)是“交叉熵”(cross-entropy)。交叉熵產(chǎn)生于信息論里面的信息壓縮編碼技術(shù),但是它后來演變成為從博弈論到機(jī)器學(xué)習(xí)等其他領(lǐng)域里的重要技術(shù)手段。它的定義如下: softmax構(gòu)建與測試程序如下 # -*- coding: utf-8 -*- import tensorflow as tf from mnist import read_data_sets input_data = read_data_sets('/home/gdw/PycharmProjects/projectOne/data', one_hot=True) x = tf.placeholder('float',[None, 784]) W = tf.Variable(tf.zeros([784,10])) b = tf.Variable(tf.zeros([10])) y = tf.nn.softmax(tf.matmul(x, W)+b) y_ = tf.placeholder(tf.float32, [None, 10]) cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ *tf.log(y), reduction_indices=[1])) train_step = tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy) init = tf.initialize_all_variables() sess = tf.Session() sess.run(init) for i in range(10000): batch_xs, batch_ys = input_data.train.next_batch(100) sess.run(train_step, feed_dict={x:batch_xs, y_:batch_ys}) correct_prediction = tf.equal(tf.argmax(y,1), tf.argmax(y_,1)) accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) print sess.run(accuracy, feed_dict={x:input_data.test.images, y_:input_data.test.labels}) |
|