欧美三区_成人在线免费观看视频_欧美极品少妇xxxxⅹ免费视频_a级毛片免费播放_鲁一鲁中文字幕久久_亚洲一级特黄

TensorFlow實戰:SoftMax手寫體MNIST識別(Python完整

系統 1928 0

今天這篇文章我們使用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之間。如圖所示

?

TensorFlow實戰:SoftMax手寫體MNIST識別(Python完整源碼)_第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.lecun.com/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 <= self._num_examples
  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 <= len(train_images):
  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構建與測試程序如下

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

想跟著大家一起學習的朋友可以加下群主,表明來意: 想加入【訓練營】免費學習+打卡

整個過程不收取任何費用! 只是帶領大家堅持學習的一種方式。如果學習過程中堅持不下來,中途放棄的同學將會被移出群聊哦。

大家有興趣的話可以加好友

TensorFlow實戰:SoftMax手寫體MNIST識別(Python完整源碼)_第2張圖片

?

更多文章、技術交流、商務合作、聯系博主

微信掃碼或搜索:z360901061

微信掃一掃加我為好友

QQ號聯系: 360901061

您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。

【本文對您有幫助就好】

您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描上面二維碼支持博主2元、5元、10元、自定義金額等您想捐的金額吧,站長會非常 感謝您的哦!!!

發表我的評論
最新評論 總共0條評論
主站蜘蛛池模板: 成人在线日韩 | 欧美综合自拍亚洲综合网 | 伊人色综合97 | 九九在线精品视频播放 | 久久96国产精品 | 91精品国产亚洲爽啪在线观看 | 二区在线观看 | 一区二区三区在线观看视频 | 日韩精品久久 | 羞羞操 | 日韩精品不卡 | 国产小视频福利 | 欧美精品一区二区在线电影 | 91久操| 国产精品久久久久久久一区探花 | 久草观看 | 色免费看| 五月天激激婷婷大综合丁香 | 九色在线 | 91视频视频 | 魔法骑士在线观看免费完整版高清 | 大色综合色综合资源站 | 天堂av资源 | 久久99国产综合精品 | 欧美三级视频在线观看 | 久久99精品久久久久久噜噜 | 亚洲精品乱码久久久久久蜜桃 | 久久青 | 2021国产精品自产拍在线观看 | 日日天天| 久久久久久全国免费观看 | 黄视频免费在线观看 | 亚洲精品免费在线观看 | 日韩精品一区二区在线观看 | 亚洲精品国产一区 | www.人人干 | 久久一区二区精品综合 | 黄色av.com| 日本爽爽爽爽爽爽免费 | 国产精品国产精品国产专区不卡 | 欧美精品黄页免费高清在线 |