dataset.py 4.7 KB
Newer Older
W
wandongdong 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
# Copyright 2020 Huawei Technologies Co., Ltd
#
# 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.
# ============================================================================
"""
create train or eval dataset.
"""
import os
P
Payne 已提交
19 20 21 22 23
from tqdm import tqdm
import numpy as np

from mindspore import Tensor
from mindspore.train.model import Model
W
wandongdong 已提交
24 25
import mindspore.common.dtype as mstype
import mindspore.dataset.engine as de
E
Eric 已提交
26
import mindspore.dataset.vision.c_transforms as C
W
wandongdong 已提交
27 28
import mindspore.dataset.transforms.c_transforms as C2

N
nhussain 已提交
29

P
Payne 已提交
30
def create_dataset(dataset_path, do_train, config, repeat_num=1):
W
wandongdong 已提交
31 32 33 34 35 36
    """
    create a train or eval dataset

    Args:
        dataset_path(string): the path of dataset.
        do_train(bool): whether dataset is used for train or eval.
P
Payne 已提交
37
        config(struct): the config of train and eval in diffirent platform.
C
chenzomi 已提交
38
        repeat_num(int): the repeat times of dataset. Default: 1.
P
Payne 已提交
39

W
wandongdong 已提交
40 41 42 43

    Returns:
        dataset
    """
P
Payne 已提交
44
    if config.platform == "Ascend":
45 46
        rank_size = int(os.getenv("RANK_SIZE", '1'))
        rank_id = int(os.getenv("RANK_ID", '0'))
C
chenzomi 已提交
47
        if rank_size == 1:
N
nhussain 已提交
48
            ds = de.ImageFolderDataset(dataset_path, num_parallel_workers=8, shuffle=True)
C
chenzomi 已提交
49
        else:
N
nhussain 已提交
50 51
            ds = de.ImageFolderDataset(dataset_path, num_parallel_workers=8, shuffle=True,
                                       num_shards=rank_size, shard_id=rank_id)
P
Payne 已提交
52
    elif config.platform == "GPU":
C
chenzomi 已提交
53 54
        if do_train:
            from mindspore.communication.management import get_rank, get_group_size
N
nhussain 已提交
55 56
            ds = de.ImageFolderDataset(dataset_path, num_parallel_workers=8, shuffle=True,
                                       num_shards=get_group_size(), shard_id=get_rank())
C
chenzomi 已提交
57
        else:
N
nhussain 已提交
58
            ds = de.ImageFolderDataset(dataset_path, num_parallel_workers=8, shuffle=True)
P
Payne 已提交
59
    elif config.platform == "CPU":
N
nhussain 已提交
60
        ds = de.ImageFolderDataset(dataset_path, num_parallel_workers=8, shuffle=True)
W
wandongdong 已提交
61 62 63 64 65 66 67

    resize_height = config.image_height
    resize_width = config.image_width
    buffer_size = 1000

    # define map operations
    decode_op = C.Decode()
W
wandongdong 已提交
68
    resize_crop_op = C.RandomCropDecodeResize(resize_height, scale=(0.08, 1.0), ratio=(0.75, 1.333))
69
    horizontal_flip_op = C.RandomHorizontalFlip(prob=0.5)
W
wandongdong 已提交
70 71 72

    resize_op = C.Resize((256, 256))
    center_crop = C.CenterCrop(resize_width)
W
wandongdong 已提交
73
    rescale_op = C.RandomColorAdjust(brightness=0.4, contrast=0.4, saturation=0.4)
N
nhussain 已提交
74 75
    normalize_op = C.Normalize(mean=[0.485 * 255, 0.456 * 255, 0.406 * 255],
                               std=[0.229 * 255, 0.224 * 255, 0.225 * 255])
W
wandongdong 已提交
76 77 78
    change_swap_op = C.HWC2CHW()

    if do_train:
W
wandongdong 已提交
79
        trans = [resize_crop_op, horizontal_flip_op, rescale_op, normalize_op, change_swap_op]
W
wandongdong 已提交
80
    else:
81
        trans = [decode_op, resize_op, center_crop, normalize_op, change_swap_op]
W
wandongdong 已提交
82 83 84

    type_cast_op = C2.TypeCast(mstype.int32)

W
wandongdong 已提交
85 86
    ds = ds.map(input_columns="image", operations=trans, num_parallel_workers=8)
    ds = ds.map(input_columns="label", operations=type_cast_op, num_parallel_workers=8)
W
wandongdong 已提交
87 88 89 90 91

    # apply shuffle operations
    ds = ds.shuffle(buffer_size=buffer_size)

    # apply batch operations
P
Payne 已提交
92
    ds = ds.batch(config.batch_size, drop_remainder=True)
W
wandongdong 已提交
93 94 95 96 97

    # apply dataset repeat operation
    ds = ds.repeat(repeat_num)

    return ds
P
Payne 已提交
98

N
nhussain 已提交
99

P
Payne 已提交
100 101 102 103 104 105 106 107 108 109 110 111 112 113 114
def extract_features(net, dataset_path, config):
    features_folder = dataset_path + '_features'
    if not os.path.exists(features_folder):
        os.makedirs(features_folder)
    dataset = create_dataset(dataset_path=dataset_path,
                             do_train=False,
                             config=config,
                             repeat_num=1)
    step_size = dataset.get_dataset_size()
    pbar = tqdm(list(dataset.create_dict_iterator()))
    model = Model(net)
    i = 0
    for data in pbar:
        features_path = os.path.join(features_folder, f"feature_{i}.npy")
        label_path = os.path.join(features_folder, f"label_{i}.npy")
N
nhussain 已提交
115
        if not (os.path.exists(features_path) and os.path.exists(label_path)):
P
Payne 已提交
116 117 118 119 120
            image = data["image"]
            label = data["label"]
            features = model.predict(Tensor(image))
            np.save(features_path, features.asnumpy())
            np.save(label_path, label)
N
nhussain 已提交
121
        pbar.set_description("Process dataset batch: %d" % (i + 1))
P
Payne 已提交
122 123 124
        i += 1

    return step_size