mnist_provider.py 1.5 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
# Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from paddle.trainer.PyDataProvider2 import *
D
dayhaha 已提交
16 17
import numpy as np
import struct
18 19 20 21 22


# Define a py data provider
@provider(
    input_types={'pixel': dense_vector(28 * 28),
D
dayhaha 已提交
23
                 'label': integer_value(10)})
24
def process(settings, filename):  # settings is not used currently.
D
dayhaha 已提交
25 26 27 28 29 30
    with open(filename + "-images-idx3-ubyte", "rb") as f:  # open picture file
        magic, n, rows, cols = struct.unpack(">IIII", f.read(16))
        images = np.fromfile(
            f, 'ubyte',
            count=n * rows * cols).reshape(n, rows, cols).astype('float32')
        images = images / 255.0 * 2.0 - 1.0  # normalized to [-1,1]
31

D
dayhaha 已提交
32 33 34
    with open(filename + "-labels-idx1-ubyte", "rb") as l:  # open label file
        magic, n = struct.unpack(">II", l.read(8))
        labels = np.fromfile(l, 'ubyte', count=n).astype("int")
35 36 37

    for i in xrange(n):
        yield {"pixel": images[i, :], 'label': labels[i]}