プリンキピア

第14章コンピュータビジョン

14.6.2. Reading the Dataset14.6.2 データセットを読む

We are going to read the banana detection dataset in the read_data_bananas function below. The dataset includes a csv file for object class labels and ground-truth bounding box coordinates at the upper-left and lower-right corners.
英語のヒント
下のread_data_bananas関数で、バナナ検出のデータセットを読む。データセットには、物体のクラスのラベルと、左上と右下の角の正解の境界ボックスの座標を記したCSVファイルが含まれる。
#@save
def read_data_bananas(is_train=True):
    """Read the banana detection dataset images and labels."""
    data_dir = d2l.download_extract('banana-detection')
    csv_fname = os.path.join(data_dir, 'bananas_train' if is_train
                             else 'bananas_val', 'label.csv')
    csv_data = pd.read_csv(csv_fname)
    csv_data = csv_data.set_index('img_name')
    images, targets = [], []
    for img_name, target in csv_data.iterrows():
        images.append(torchvision.io.read_image(
            os.path.join(data_dir, 'bananas_train' if is_train else
                         'bananas_val', 'images', f'{img_name}')))
        # Here `target` contains (class, upper-left x, upper-left y,
        # lower-right x, lower-right y), where all the images have the same
        # banana class (index 0)
        targets.append(list(target))
    return images, torch.tensor(targets).unsqueeze(1) / 256
By using the read_data_bananas function to read images and labels, the following BananasDataset class will allow us to create a customized Dataset instance for loading the banana detection dataset.
英語のヒント
read_data_bananas関数を使って画像とラベルを読むことで、次のBananasDatasetクラスは、バナナ検出のデータセットを読み込むためのカスタマイズしたDatasetインスタンスを作れるようにする。
#@save
class BananasDataset(torch.utils.data.Dataset):
    """A customized dataset to load the banana detection dataset."""
    def __init__(self, is_train):
        self.features, self.labels = read_data_bananas(is_train)
        print('read ' + str(len(self.features)) + (f' training examples' if
              is_train else f' validation examples'))

    def __getitem__(self, idx):
        return (self.features[idx].float(), self.labels[idx])

    def __len__(self):
        return len(self.features)
Finally, we define the load_data_bananas function to return two data iterator instances for both the training and test sets. For the test dataset, there is no need to read it in random order.
英語のヒント
最後に、訓練集合とテスト集合の両方について二つのデータイテレータのインスタンスを返すload_data_bananas関数を定義する。テストデータセットについては、ランダムな順序で読む必要はない。
#@save
def load_data_bananas(batch_size):
    """Load the banana detection dataset."""
    train_iter = torch.utils.data.DataLoader(BananasDataset(is_train=True),
                                             batch_size, shuffle=True)
    val_iter = torch.utils.data.DataLoader(BananasDataset(is_train=False),
                                           batch_size)
    return train_iter, val_iter
Let’s read a minibatch and print the shapes of both images and labels in this minibatch. The shape of the image minibatch, (batch size, number of channels, height, width), looks familiar: it is the same as in our earlier image classification tasks. The shape of the label minibatch is (batch size, m, 5), where m is the largest possible number of bounding boxes that any image has in the dataset.
英語のヒント
ミニバッチを読み、このミニバッチの画像とラベルの両方の形状を出力しよう。画像のミニバッチの形状(バッチの大きさ、チャネル数、高さ、幅)は見覚えがある。前の画像分類の課題と同じである。ラベルのミニバッチの形状は(バッチの大きさ、m、5)である。ここでmは、データセットのどの画像についても、ありうる境界ボックスの最大数である。
Although computation in minibatches is more efficient, it requires that all the image examples contain the same number of bounding boxes to form a minibatch via concatenation. In general, images may have a varying number of bounding boxes; thus, images with fewer than m bounding boxes will be padded with illegal bounding boxes until m is reached. Then the label of each bounding box is represented by an array of length 5. The first element in the array is the class of the object in the bounding box, where -1 indicates an illegal bounding box for padding. The remaining four elements of the array are the (x, y)-coordinate values of the upper-left corner and the lower-right corner of the bounding box (the range is between 0 and 1). For the banana dataset, since there is only one bounding box on each image, we have m=1.
英語のヒント
ミニバッチでの計算はもっと効率的だが、連結によってミニバッチを作るには、すべての画像の事例が同じ数の境界ボックスを含む必要がある。一般に、画像の境界ボックスの数はまちまちである。そのため、境界ボックスがm個より少ない画像は、m個に達するまで不正な境界ボックスで埋められる。それから、各境界ボックスのラベルは長さ5の配列で表される。配列の最初の要素は境界ボックスの中の物体のクラスで、−1は埋めるための不正な境界ボックスを示す。配列の残りの四つの要素は、境界ボックスの左上の角と右下の角の(x, y)座標の値である(範囲は0から1)。バナナのデータセットでは、各画像に境界ボックスが一つしかないので、m=1である。
batch_size, edge_size = 32, 256
train_iter, _ = load_data_bananas(batch_size)
batch = next(iter(train_iter))
batch[0].shape, batch[1].shape
Downloading ../data/banana-detection.zip from http://d2l-data.s3-accelerate.amazonaws.com/banana-detection.zip...
read 1000 training examples
read 100 validation examples
(torch.Size([32, 3, 256, 256]), torch.Size([32, 1, 5]))