mnist.py 2.2 KB
Newer Older
Y
Yi Wang 已提交
1 2
import paddle.v2.dataset.common
import subprocess
Y
Yu Yang 已提交
3 4
import numpy

Y
Yi Wang 已提交
5
URL_PREFIX = 'http://yann.lecun.com/exdb/mnist/'
Y
Yu Yang 已提交
6

Y
Yi Wang 已提交
7 8
TEST_IMAGE_URL = URL_PREFIX + 't10k-images-idx3-ubyte.gz'
TEST_IMAGE_MD5 = '25e3cc63507ef6e98d5dc541e8672bb6'
Y
Yu Yang 已提交
9

Y
Yi Wang 已提交
10 11 12 13 14
TEST_LABEL_URL = URL_PREFIX + 't10k-labels-idx1-ubyte.gz'
TEST_LABEL_MD5 = '4e9511fe019b2189026bd0421ba7b688'

TRAIN_IMAGE_URL = URL_PREFIX + 'train-images-idx3-ubyte.gz'
TRAIN_IMAGE_MD5 = 'f68b3c2dcbeaaa9fbdd348bbdeb94873'
Y
Yu Yang 已提交
15

Y
Yi Wang 已提交
16 17
TRAIN_LABEL_URL = URL_PREFIX + 'train-labels-idx1-ubyte.gz'
TRAIN_LABEL_MD5 = 'd53e105ee54ea40749a09fcbcd1e9432'
Y
Yu Yang 已提交
18 19


Y
Yi Wang 已提交
20 21 22 23 24
def reader_creator(image_filename, label_filename, buffer_size):
    def reader():
        # According to http://stackoverflow.com/a/38061619/724872, we
        # cannot use standard package gzip here.
        m = subprocess.Popen(["zcat", image_filename], stdout=subprocess.PIPE)
Y
Yi Wang 已提交
25
        m.stdout.read(16)  # skip some magic bytes
Y
Yi Wang 已提交
26 27

        l = subprocess.Popen(["zcat", label_filename], stdout=subprocess.PIPE)
Y
Yi Wang 已提交
28
        l.stdout.read(8)  # skip some magic bytes
Y
Yu Yang 已提交
29

Y
Yi Wang 已提交
30 31
        while True:
            labels = numpy.fromfile(
Y
Yi Wang 已提交
32
                l.stdout, 'ubyte', count=buffer_size).astype("int")
Y
Yu Yang 已提交
33

Y
Yi Wang 已提交
34
            if labels.size != buffer_size:
Y
Yi Wang 已提交
35
                break  # numpy.fromfile returns empty slice after EOF.
Y
Yu Yang 已提交
36

Y
Yi Wang 已提交
37
            images = numpy.fromfile(
Y
Yi Wang 已提交
38 39
                m.stdout, 'ubyte', count=buffer_size * 28 * 28).reshape(
                    (buffer_size, 28 * 28)).astype('float32')
Y
Yu Yang 已提交
40

Y
Yi Wang 已提交
41
            images = images / 255.0 * 2.0 - 1.0
Y
Yu Yang 已提交
42

Y
Yi Wang 已提交
43 44
            for i in xrange(buffer_size):
                yield images[i, :], labels[i]
Y
Yu Yang 已提交
45

Y
Yi Wang 已提交
46 47
        m.terminate()
        l.terminate()
Y
Yu Yang 已提交
48

Y
Yi Wang 已提交
49
    return reader()
Y
Yu Yang 已提交
50

Y
Yi Wang 已提交
51

Y
Yi Wang 已提交
52 53
def train():
    return reader_creator(
Y
Yi Wang 已提交
54 55 56 57 58
        paddle.v2.dataset.common.download(TRAIN_IMAGE_URL, 'mnist',
                                          TRAIN_IMAGE_MD5),
        paddle.v2.dataset.common.download(TRAIN_LABEL_URL, 'mnist',
                                          TRAIN_LABEL_MD5), 100)

Y
Yu Yang 已提交
59

Y
Yi Wang 已提交
60 61
def test():
    return reader_creator(
Y
Yi Wang 已提交
62 63 64 65
        paddle.v2.dataset.common.download(TEST_IMAGE_URL, 'mnist',
                                          TEST_IMAGE_MD5),
        paddle.v2.dataset.common.download(TEST_LABEL_URL, 'mnist',
                                          TEST_LABEL_MD5), 100)