• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Copyright 2020 Huawei Technologies Co., Ltd
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14# ==============================================================================
15"""
16Test Mnist dataset operators
17"""
18import os
19import pytest
20import numpy as np
21import matplotlib.pyplot as plt
22import mindspore.dataset as ds
23import mindspore.dataset.vision.c_transforms as vision
24from mindspore import log as logger
25
26DATA_DIR = "../data/dataset/testMnistData"
27
28
29def load_mnist(path):
30    """
31    load Mnist data
32    """
33    labels_path = os.path.join(path, 't10k-labels-idx1-ubyte')
34    images_path = os.path.join(path, 't10k-images-idx3-ubyte')
35    with open(labels_path, 'rb') as lbpath:
36        lbpath.read(8)
37        labels = np.fromfile(lbpath, dtype=np.uint8)
38    with open(images_path, 'rb') as imgpath:
39        imgpath.read(16)
40        images = np.fromfile(imgpath, dtype=np.uint8)
41        images = images.reshape(-1, 28, 28, 1)
42        images[images > 0] = 255  # Perform binarization to maintain consistency with our API
43    return images, labels
44
45
46def visualize_dataset(images, labels):
47    """
48    Helper function to visualize the dataset samples
49    """
50    num_samples = len(images)
51    for i in range(num_samples):
52        plt.subplot(1, num_samples, i + 1)
53        plt.imshow(images[i].squeeze(), cmap=plt.cm.gray)
54        plt.title(labels[i])
55    plt.show()
56
57
58def test_mnist_content_check():
59    """
60    Validate MnistDataset image readings
61    """
62    logger.info("Test MnistDataset Op with content check")
63    data1 = ds.MnistDataset(DATA_DIR, num_samples=100, shuffle=False)
64    images, labels = load_mnist(DATA_DIR)
65    num_iter = 0
66    # in this example, each dictionary has keys "image" and "label"
67    image_list, label_list = [], []
68    for i, data in enumerate(data1.create_dict_iterator(num_epochs=1, output_numpy=True)):
69        image_list.append(data["image"])
70        label_list.append("label {}".format(data["label"]))
71        np.testing.assert_array_equal(data["image"], images[i])
72        np.testing.assert_array_equal(data["label"], labels[i])
73        num_iter += 1
74    assert num_iter == 100
75
76
77def test_mnist_basic():
78    """
79    Validate MnistDataset
80    """
81    logger.info("Test MnistDataset Op")
82
83    # case 1: test loading whole dataset
84    data1 = ds.MnistDataset(DATA_DIR)
85    num_iter1 = 0
86    for _ in data1.create_dict_iterator(num_epochs=1):
87        num_iter1 += 1
88    assert num_iter1 == 10000
89
90    # case 2: test num_samples
91    data2 = ds.MnistDataset(DATA_DIR, num_samples=500)
92    num_iter2 = 0
93    for _ in data2.create_dict_iterator(num_epochs=1):
94        num_iter2 += 1
95    assert num_iter2 == 500
96
97    # case 3: test repeat
98    data3 = ds.MnistDataset(DATA_DIR, num_samples=200)
99    data3 = data3.repeat(5)
100    num_iter3 = 0
101    for _ in data3.create_dict_iterator(num_epochs=1):
102        num_iter3 += 1
103    assert num_iter3 == 1000
104
105    # case 4: test batch with drop_remainder=False
106    data4 = ds.MnistDataset(DATA_DIR, num_samples=100)
107    assert data4.get_dataset_size() == 100
108    assert data4.get_batch_size() == 1
109    data4 = data4.batch(batch_size=7)  # drop_remainder is default to be False
110    assert data4.get_dataset_size() == 15
111    assert data4.get_batch_size() == 7
112    num_iter4 = 0
113    for _ in data4.create_dict_iterator(num_epochs=1):
114        num_iter4 += 1
115    assert num_iter4 == 15
116
117    # case 5: test batch with drop_remainder=True
118    data5 = ds.MnistDataset(DATA_DIR, num_samples=100)
119    assert data5.get_dataset_size() == 100
120    assert data5.get_batch_size() == 1
121    data5 = data5.batch(batch_size=7, drop_remainder=True)  # the rest of incomplete batch will be dropped
122    assert data5.get_dataset_size() == 14
123    assert data5.get_batch_size() == 7
124    num_iter5 = 0
125    for _ in data5.create_dict_iterator(num_epochs=1):
126        num_iter5 += 1
127    assert num_iter5 == 14
128
129
130def test_mnist_pk_sampler():
131    """
132    Test MnistDataset with PKSampler
133    """
134    logger.info("Test MnistDataset Op with PKSampler")
135    golden = [0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4,
136              5, 5, 5, 6, 6, 6, 7, 7, 7, 8, 8, 8, 9, 9, 9]
137    sampler = ds.PKSampler(3)
138    data = ds.MnistDataset(DATA_DIR, sampler=sampler)
139    num_iter = 0
140    label_list = []
141    for item in data.create_dict_iterator(num_epochs=1, output_numpy=True):
142        label_list.append(item["label"])
143        num_iter += 1
144    np.testing.assert_array_equal(golden, label_list)
145    assert num_iter == 30
146
147
148def test_mnist_sequential_sampler():
149    """
150    Test MnistDataset with SequentialSampler
151    """
152    logger.info("Test MnistDataset Op with SequentialSampler")
153    num_samples = 50
154    sampler = ds.SequentialSampler(num_samples=num_samples)
155    data1 = ds.MnistDataset(DATA_DIR, sampler=sampler)
156    data2 = ds.MnistDataset(DATA_DIR, shuffle=False, num_samples=num_samples)
157    label_list1, label_list2 = [], []
158    num_iter = 0
159    for item1, item2 in zip(data1.create_dict_iterator(num_epochs=1), data2.create_dict_iterator(num_epochs=1)):
160        label_list1.append(item1["label"].asnumpy())
161        label_list2.append(item2["label"].asnumpy())
162        num_iter += 1
163    np.testing.assert_array_equal(label_list1, label_list2)
164    assert num_iter == num_samples
165
166
167def test_mnist_exception():
168    """
169    Test error cases for MnistDataset
170    """
171    logger.info("Test error cases for MnistDataset")
172    error_msg_1 = "sampler and shuffle cannot be specified at the same time"
173    with pytest.raises(RuntimeError, match=error_msg_1):
174        ds.MnistDataset(DATA_DIR, shuffle=False, sampler=ds.PKSampler(3))
175
176    error_msg_2 = "sampler and sharding cannot be specified at the same time"
177    with pytest.raises(RuntimeError, match=error_msg_2):
178        ds.MnistDataset(DATA_DIR, sampler=ds.PKSampler(3), num_shards=2, shard_id=0)
179
180    error_msg_3 = "num_shards is specified and currently requires shard_id as well"
181    with pytest.raises(RuntimeError, match=error_msg_3):
182        ds.MnistDataset(DATA_DIR, num_shards=10)
183
184    error_msg_4 = "shard_id is specified but num_shards is not"
185    with pytest.raises(RuntimeError, match=error_msg_4):
186        ds.MnistDataset(DATA_DIR, shard_id=0)
187
188    error_msg_5 = "Input shard_id is not within the required interval"
189    with pytest.raises(ValueError, match=error_msg_5):
190        ds.MnistDataset(DATA_DIR, num_shards=5, shard_id=-1)
191    with pytest.raises(ValueError, match=error_msg_5):
192        ds.MnistDataset(DATA_DIR, num_shards=5, shard_id=5)
193    with pytest.raises(ValueError, match=error_msg_5):
194        ds.MnistDataset(DATA_DIR, num_shards=2, shard_id=5)
195
196    error_msg_6 = "num_parallel_workers exceeds"
197    with pytest.raises(ValueError, match=error_msg_6):
198        ds.MnistDataset(DATA_DIR, shuffle=False, num_parallel_workers=0)
199    with pytest.raises(ValueError, match=error_msg_6):
200        ds.MnistDataset(DATA_DIR, shuffle=False, num_parallel_workers=256)
201    with pytest.raises(ValueError, match=error_msg_6):
202        ds.MnistDataset(DATA_DIR, shuffle=False, num_parallel_workers=-2)
203
204    error_msg_7 = "Argument shard_id"
205    with pytest.raises(TypeError, match=error_msg_7):
206        ds.MnistDataset(DATA_DIR, num_shards=2, shard_id="0")
207
208    def exception_func(item):
209        raise Exception("Error occur!")
210
211    error_msg_8 = "The corresponding data files"
212    with pytest.raises(RuntimeError, match=error_msg_8):
213        data = ds.MnistDataset(DATA_DIR)
214        data = data.map(operations=exception_func, input_columns=["image"], num_parallel_workers=1)
215        for _ in data.__iter__():
216            pass
217    with pytest.raises(RuntimeError, match=error_msg_8):
218        data = ds.MnistDataset(DATA_DIR)
219        data = data.map(operations=vision.Decode(), input_columns=["image"], num_parallel_workers=1)
220        data = data.map(operations=exception_func, input_columns=["image"], num_parallel_workers=1)
221        for _ in data.__iter__():
222            pass
223    with pytest.raises(RuntimeError, match=error_msg_8):
224        data = ds.MnistDataset(DATA_DIR)
225        data = data.map(operations=exception_func, input_columns=["label"], num_parallel_workers=1)
226        for _ in data.__iter__():
227            pass
228
229
230def test_mnist_visualize(plot=False):
231    """
232    Visualize MnistDataset results
233    """
234    logger.info("Test MnistDataset visualization")
235
236    data1 = ds.MnistDataset(DATA_DIR, num_samples=10, shuffle=False)
237    num_iter = 0
238    image_list, label_list = [], []
239    for item in data1.create_dict_iterator(num_epochs=1, output_numpy=True):
240        image = item["image"]
241        label = item["label"]
242        image_list.append(image)
243        label_list.append("label {}".format(label))
244        assert isinstance(image, np.ndarray)
245        assert image.shape == (28, 28, 1)
246        assert image.dtype == np.uint8
247        assert label.dtype == np.uint32
248        num_iter += 1
249    assert num_iter == 10
250    if plot:
251        visualize_dataset(image_list, label_list)
252
253
254def test_mnist_usage():
255    """
256    Validate MnistDataset image readings
257    """
258    logger.info("Test MnistDataset usage flag")
259
260    def test_config(usage, mnist_path=None):
261        mnist_path = DATA_DIR if mnist_path is None else mnist_path
262        try:
263            data = ds.MnistDataset(mnist_path, usage=usage, shuffle=False)
264            num_rows = 0
265            for _ in data.create_dict_iterator(num_epochs=1, output_numpy=True):
266                num_rows += 1
267        except (ValueError, TypeError, RuntimeError) as e:
268            return str(e)
269        return num_rows
270
271    assert test_config("test") == 10000
272    assert test_config("all") == 10000
273    assert "MnistDataset API can't read the data file (interface mismatch or no data found)" in test_config("train")
274    assert "usage is not within the valid set of ['train', 'test', 'all']" in test_config("invalid")
275    assert "Argument usage with value ['list'] is not of type [<class 'str'>]" in test_config(["list"])
276
277    # change this directory to the folder that contains all mnist files
278    all_files_path = None
279    # the following tests on the entire datasets
280    if all_files_path is not None:
281        assert test_config("train", all_files_path) == 60000
282        assert test_config("test", all_files_path) == 10000
283        assert test_config("all", all_files_path) == 70000
284        assert ds.MnistDataset(all_files_path, usage="train").get_dataset_size() == 60000
285        assert ds.MnistDataset(all_files_path, usage="test").get_dataset_size() == 10000
286        assert ds.MnistDataset(all_files_path, usage="all").get_dataset_size() == 70000
287
288
289if __name__ == '__main__':
290    test_mnist_content_check()
291    test_mnist_basic()
292    test_mnist_pk_sampler()
293    test_mnist_sequential_sampler()
294    test_mnist_exception()
295    test_mnist_visualize(plot=True)
296    test_mnist_usage()
297