【深度学习】【python】下载和读取MINIS数据集 中文注释版
【深度学习】【python】下载和读取MINIS数据集 中文注释版环境要求- python3.5- tensorflow 1.4- pytorch 0.2.0这次的只需要python3.5即可程序如下:#!/usr/bin/env python# -*- coding: utf-8 -*-"""下载和读取 MNIST 数据集."""fro
·
【深度学习】【python】下载和读取MINIS数据集 中文注释版
环境要求
- python3.5
- tensorflow 1.4
- pytorch 0.2.0
这次的只需要python3.5即可
程序如下:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""下载和读取 MNIST 数据集."""
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):
"""检查是否下载数据集;否则下载;"""
#如果没有这个文件夹则创建;
if not os.path.exists(work_directory):
os.mkdir(work_directory)
#将这个文件夹名加上数据集文件名:如'./MINIST/minist-1.gz';
filepath = os.path.join(work_directory, filename)
#如果不存在则用urllib下载;
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):
"""将读入的字节流转化为numpy格式;"""
#设置dtype型变量dt;
dt = numpy.dtype(numpy.uint32).newbyteorder('>')
#按数据格式dt转换数据;注意read方式会“取出”bytestream内的数据;
return numpy.frombuffer(bytestream.read(4), dtype=dt)[0]
def extract_images(filename):
"""将所有图片转化为一个 4D uint8 的 numpy 矩阵[index, y, x, depth]."""
#转化gzip格式的文件
print('Extracting', filename)
with gzip.open(filename) as bytestream:
#magic变量存储了图像头信息;
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;
buf = bytestream.read(rows * cols * num_images)
#转化为numpy格式;
data = numpy.frombuffer(buf, dtype=numpy.uint8)
#rashape为4D uint8 的 numpy 矩阵;
data = data.reshape(num_images, rows, cols, 1)
return data
def dense_to_one_hot(labels_dense, num_classes=10):
"""将类别标签从标量转化为one-hot向量."""
#此乃label数目;
num_labels = labels_dense.shape[0]
#生成一个数组,等价于2D one-hot矩阵展开为1D后1的位置;
index_offset = numpy.arange(num_labels) * num_classes
#生成一个存储了num_labels个one-hot向量(num_classes维)的2D零矩阵;
labels_one_hot = numpy.zeros((num_labels, num_classes))
#将对应类别的位置的0设为1;
labels_one_hot.flat[index_offset + labels_dense.ravel()] = 1
return labels_one_hot
def extract_labels(filename, one_hot=False):
"""将标签输出为 1D uint8 的 numpy 数组 [index]."""
#转化gzip格式的文件
print('Extracting', filename)
with gzip.open(filename) as bytestream:
#magic变量存储了图像头信息;
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)
#转化为numpy格式;
labels = numpy.frombuffer(buf, dtype=numpy.uint8)
#如果要求转换为one-hot则调用dense_to_one_hot()转换;
if one_hot:
return dense_to_one_hot(labels)
return labels
class DataSet(object):
"""封装一个DataSet类方便管理数据"""
def __init__(self, images, labels, fake_data=False):
if fake_data:
self._num_examples = 10000
else:
#断言;要求images数目等于labels数目;
assert images.shape[0] == labels.shape[0], (
"images.shape: %s labels.shape: %s" % (images.shape,
labels.shape))
#设置图像数目;
self._num_examples = images.shape[0]
# reshape:将[num examples, rows, columns, depth] 转化为 [num examples, rows*columns] (assuming depth == 1)
assert images.shape[3] == 1
images = images.reshape(images.shape[0],
images.shape[1] * images.shape[2])
# 归一化: 转换 [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):
"""从当前数据集返回下一批次`batch_size`的样本."""
#生成伪数据
if fake_data:
#伪图像fake_image_1*784;
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)]
#当前epoch返回样本的开始位置;
start = self._index_in_epoch
#设置下一次epoch返回样本的开始位置;
self._index_in_epoch += batch_size
#本次epoch返回样本的结束位置超出了当前样本数;解决方式:又回到开始;
if self._index_in_epoch > self._num_examples:
#结束epoch
self._epochs_completed += 1
#先打乱整个数据
perm = numpy.arange(self._num_examples)
numpy.random.shuffle(perm)
self._images = self._images[perm]
self._labels = self._labels[perm]
#从头又来一次;
start = 0
self._index_in_epoch = batch_size
#断言,batch_size不超出样本数;
assert batch_size <= self._num_examples
#设置结束位置;
end = self._index_in_epoch
#返回start:end位置的images+labels;
return self._images[start:end], self._labels[start:end]
def read_data_sets(train_dir, fake_data=False, one_hot=False):
"""相当于本文件的主函数"""
#最终要返回的多个DataSet的抽象DataSets;
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
更多推荐
已为社区贡献14条内容
所有评论(0)