久久国产成人av_抖音国产毛片_a片网站免费观看_A片无码播放手机在线观看,色五月在线观看,亚洲精品m在线观看,女人自慰的免费网址,悠悠在线观看精品视频,一级日本片免费的,亚洲精品久,国产精品成人久久久久久久

分享

TensorFlow實戰(zhàn):SoftMax手寫體MNIST識別(Python完整源碼)

 LibraryPKU 2018-10-09

之前的文章 TensorFlow的安裝與初步了解,,從TensorFlow的安裝到基本的模塊單元進行了初步的講解,。今天這篇文章我們使用TensorFlow針對于手寫體識別數據集MNIST搭建一個softmax的多分類模型,。


本文的程序主要分為兩大模塊,,一個是對MNIST數據集的下載,、解壓,、重構以及數據集的構建;另一個是構建softmax圖及訓練圖。本程序主要是想去理解包含在這些代碼里面的設計思想:TensorFlow工作流程和機器學習的基本概念,。本文所使用的數據集和Python源代碼都已經上傳到我的GitHub(https://github.com/ml365/softmax_mnist),,點擊文末閱讀原文直接跳轉下載頁面。


MNIST數據集的下載與重構

MNIST是一個入門級的計算機視覺數據集,,它包含各種手寫數字圖片:

它也包含每一張圖片對應的標簽,,告訴我們這個是數字幾。比如,,上面這四張圖片的標簽分別是5,,0,4,,1,。


下載下來的數據集被分成兩部分:60000行的訓練數據集(mnist.train)和10000行的測試數據集(mnist.test)。正如前面提到的一樣,,每一個MNIST數據單元有兩部分組成:一張包含手寫數字的圖片和一個對應的標簽,。我們把這些圖片設為“xs”,把這些標簽設為“ys”,。訓練數據集和測試數據集都包含xs和ys,,比如訓練數據集的圖片是 mnist.train.images ,訓練數據集的標簽是 mnist.train.labels,。將上述的圖像按行展開,,因此,在MNIST訓練數據集中,,mnist.train.images 是一個形狀為 [60000, 784] 的張量,,第一個維度數字用來索引圖片,第二個維度數字用來索引每張圖片中的像素點,。在此張量里的每一個元素,,都表示某張圖片里的某個像素的強度值,值介于0和1之間,。如圖所示

數據處理的代碼如下所示


'''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模型可以用來給不同的對象分配概率,。即使在卷積勝境網絡中,最后一步也需要用softmax來分配概率,。softmax回歸(softmax regression)分兩步:


為了得到一張給定圖片屬于某個特定數字類的證據(evidence),,我們對圖片像素值進行加權求和。如果這個像素具有很強的證據說明這張圖片不屬于該類,,那么相應的權值為負數,,相反如果這個像素擁有有利的證據支持這張圖片屬于這個類,那么權值是正數,。因此對于給定的輸入圖片 x 它代表的是數字 i 的證據可以表示為

其中 Wi,j 代表權重,, bi 代表數字 i 類的偏置量,,j 代表給定圖片 x 的像素索引用于像素求和。然后用softmax函數可以把這些證據轉換成概率 y:

為了訓練我們的模型,,我們首先需要定義一個指標來評估這個模型是好的,。一個非常常見的,非常漂亮的成本函數是“交叉熵”(cross-entropy),。交叉熵產生于信息論里面的信息壓縮編碼技術,,但是它后來演變成為從博弈論到機器學習等其他領域里的重要技術手段。它的定義如下:


softmax構建與測試程序如下


# -*- 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})




    本站是提供個人知識管理的網絡存儲空間,,所有內容均由用戶發(fā)布,,不代表本站觀點。請注意甄別內容中的聯(lián)系方式,、誘導購買等信息,,謹防詐騙。如發(fā)現有害或侵權內容,,請點擊一鍵舉報,。
    轉藏 分享 獻花(0

    0條評論

    發(fā)表

    請遵守用戶 評論公約

    類似文章 更多