mnist

转载 2015年11月18日 18:17:57
"""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 numpy
from six.moves import urllib
from six.moves import xrange  # pylint: disable=redefined-builtin
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('Succesfully 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)
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):
    if fake_data:
      self._num_examples = 10000
    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])
      # 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.0 for _ in xrange(784)]
      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):
  class DataSets(object):
    pass
  data_sets = DataSets()
  if fake_data:
    data_sets.train = DataSet([], [], fake_data=True)
    data_sets.validation = DataSet([], [], fake_data=True)
    data_sets.test = DataSet([], [], fake_data=True)
    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)
  data_sets.validation = DataSet(validation_images, validation_labels)
  data_sets.test = DataSet(test_images, test_labels)
  return data_sets

TensorFlow官方教程学习笔记(四)——MNIST数据集的读取

本文主要讲如何将MNIST数据文件中的images和labels分别提取出来的过程,与TensorFlow和deeplearning无关,但是我觉得对于MNIST数据集的了解,以及后面的一些才做还是很...
  • wspba
  • wspba
  • 2017年01月12日 07:44
  • 2499

mnist数据集

  • 2017年09月09日 09:33
  • 21.22MB
  • 下载

自动下载和安装 MNIST 到 TensorFlow 的 python 源码

由于这份代码存在 googlesource 上,因为众所周知的原因没有有办法直接下载。转载过来 # Copyright 2015 Google Inc. All Rights Reserve...
  • fdbptha
  • fdbptha
  • 2016年04月27日 23:43
  • 3891

TensorsFlow学习笔记3----面向机器学习初学者的MNIST教程(MNIST For ML Beginners)

原文教程:tensorflow官方教程 翻译教程:极客学院记录关键内容与学习感受。未完待续。。面向机器初学者的MNIST教程(MNIST For ML Beginners)—–适用于对机器学习和te...
  • liuxiao214
  • liuxiao214
  • 2017年04月27日 11:44
  • 698

使用C++和OpenCV读取MNIST文件

一.MNIST手写字体文件说明     MNIST手写字体数据库下载地址http://yann.lecun.com/exdb/mnist/ 。     MNIST手写字体的数据库说明在下载网站的下面也...
  • shengno1
  • shengno1
  • 2014年04月09日 14:37
  • 4896

卷积神经网络(CNN)的简单实现(MNIST)

卷积神经网络(CNN)的简单实现(MNIST)
  • fengbingchun
  • fengbingchun
  • 2016年03月06日 19:20
  • 22547

学习笔记:MNIST数据集

数据预览sklearn中内置了从开放数据库中取得数据集的方法,在线导入MNIST数据集。from sklearn.datasets import fetch_mldata mnist = fetch_...
  • qq_31823267
  • qq_31823267
  • 2017年11月21日 14:04
  • 494

mnist训练与测试自己手写数字

一、训练 1、从http://yann.lecun.com/exdb/mnist/下载的数据集 这需要进行数据结构转化,转化为lmdb格式。 解压到caffe->data->mnist文件夹...
  • swj110119
  • swj110119
  • 2016年12月01日 17:23
  • 7302

mnist手写字符转图片

mnist是一个专门用于手写字符识别训练的数据集,格式是2进制格式,由于一些需要,这里将其转化为jpg图片格式。 数据集下载地址,http://yann.lecun.com/exdb/mnist/ ...
  • qq_14845119
  • qq_14845119
  • 2017年02月06日 17:39
  • 2670

识别MNIST数据集之(一):读取数据

MINIST读数据
  • superCally
  • superCally
  • 2017年01月08日 20:43
  • 8717
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:mnist
举报原因:
原因补充:

(最多只允许输入30个字)