第14章コンピュータビジョン
14.13.1. Obtaining and Organizing the Dataset14.13.1 データセットの取得と整理
The competition dataset is divided into a training set and a test set, which contain 50000 and 300000 images, respectively. In the test set, 10000 images will be used for evaluation, while the remaining 290000 images will not be evaluated: they are included just to make it hard to cheat with manually labeled results of the test set. The images in this dataset are all png color (RGB channels) image files, whose height and width are both 32 pixels. The images cover a total of 10 categories, namely airplanes, cars, birds, cats, deer, dogs, frogs, horses, boats, and trucks. The upper-left corner of Fig. 14.13.1 shows some images of airplanes, cars, and birds in the dataset.
英語のヒント
コンペティションのデータセットは訓練集合とテスト集合に分かれており、それぞれ50000枚と300000枚の画像を含む。テスト集合では、10000枚の画像が評価に使われ、残りの290000枚の画像は評価されない。それらは、テスト集合に手作業でラベルをつけた結果でずるをするのを難しくするためだけに含まれている。このデータセットの画像はすべてpngのカラー(RGBチャネル)画像ファイルで、高さと幅はどちらも32画素である。画像は合計10のカテゴリ、つまり飛行機、車、鳥、猫、鹿、犬、蛙、馬、船、トラックにわたる。図14.13.1の左上の角は、データセットの飛行機、車、鳥の画像のいくつかを示している。
14.13.1.1. Downloading the Dataset14.13.1.1 データセットをダウンロードする
After logging in to Kaggle, we can click the “Data” tab on the CIFAR-10 image classification competition webpage shown in Fig. 14.13.1 and download the dataset by clicking the “Download All” button. After unzipping the downloaded file in
../data, and unzipping train.7z and test.7z inside it, you will find the entire dataset in the following paths:英語のヒント
Kaggleにログインした後、図14.13.1に示したCIFAR-10の画像分類コンペティションのウェブページで「Data」タブをクリックし、「Download All」ボタンをクリックしてデータセットをダウンロードできる。ダウンロードしたファイルを
../dataで解凍し、その中のtrain.7zとtest.7zを解凍すると、次のパスにデータセット全体が見つかる。../data/cifar-10/train/[1-50000].png英語のヒント
../data/cifar-10/train/[1-50000].png../data/cifar-10/test/[1-300000].png英語のヒント
../data/cifar-10/test/[1-300000].png../data/cifar-10/trainLabels.csv英語のヒント
../data/cifar-10/trainLabels.csv../data/cifar-10/sampleSubmission.csv英語のヒント
../data/cifar-10/sampleSubmission.csv
where the
train and test directories contain the training and testing images, respectively, trainLabels.csv provides labels for the training images, and sample_submission.csv is a sample submission file.英語のヒント
ここで、
trainとtestのディレクトリにはそれぞれ訓練画像とテスト画像が入っており、trainLabels.csvは訓練画像のラベルを与え、sample_submission.csvは提出ファイルの見本である。To make it easier to get started, we provide a small-scale sample of the dataset that contains the first 1000 training images and 5 random testing images. To use the full dataset of the Kaggle competition, you need to set the following
demo variable to False.英語のヒント
始めやすくするため、最初の1000枚の訓練画像とランダムな5枚のテスト画像を含む、小規模なデータセットの見本を用意した。Kaggleのコンペティションの完全なデータセットを使うには、次の変数
demoをFalseに設定する必要がある。#@save
d2l.DATA_HUB['cifar10_tiny'] = (d2l.DATA_URL + 'kaggle_cifar10_tiny.zip',
'2068874e4b9a9f0fb07ebe0ad2b29754449ccacd')
# If you use the full dataset downloaded for the Kaggle competition, set
# `demo` to False
demo = True
if demo:
data_dir = d2l.download_extract('cifar10_tiny')
else:
data_dir = '../data/cifar-10/'Downloading ../data/kaggle_cifar10_tiny.zip from http://d2l-data.s3-accelerate.amazonaws.com/kaggle_cifar10_tiny.zip...14.13.1.2. Organizing the Dataset14.13.1.2 データセットを整理する
We need to organize datasets to facilitate model training and testing. Let’s first read the labels from the csv file. The following function returns a dictionary that maps the non-extension part of the filename to its label.
英語のヒント
モデルの訓練とテストをしやすくするため、データセットを整理する必要がある。まず、CSVファイルからラベルを読もう。次の関数は、ファイル名の拡張子でない部分をそのラベルに対応させる辞書を返す。
#@save
def read_csv_labels(fname):
"""Read `fname` to return a filename to label dictionary."""
with open(fname, 'r') as f:
# Skip the file header line (column name)
lines = f.readlines()[1:]
tokens = [l.rstrip().split(',') for l in lines]
return dict(((name, label) for name, label in tokens))
labels = read_csv_labels(os.path.join(data_dir, 'trainLabels.csv'))
print('# training examples:', len(labels))
print('# classes:', len(set(labels.values())))# training examples: 1000
# classes: 10Next, we define the
reorg_train_valid function to split the validation set out of the original training set. The argument valid_ratio in this function is the ratio of the number of examples in the validation set to the number of examples in the original training set. More concretely, let be the number of images of the class with the least examples, and be the ratio. The validation set will split out images for each class. Let’s use valid_ratio=0.1 as an example. Since the original training set has 50000 images, there will be 45000 images used for training in the path train_valid_test/train, while the other 5000 images will be split out as validation set in the path train_valid_test/valid. After organizing the dataset, images of the same class will be placed under the same folder.英語のヒント
次に、元の訓練集合から検証集合を分ける
reorg_train_valid関数を定義する。この関数の引数valid_ratioは、元の訓練集合の事例の数に対する検証集合の事例の数の比である。もっと具体的には、事例が最も少ないクラスの画像の数を、比をとする。検証集合は、各クラスについて枚の画像を分ける。valid_ratio=0.1を例にしよう。元の訓練集合には50000枚の画像があるので、パスtrain_valid_test/trainに訓練に使う45000枚の画像が置かれ、残りの5000枚の画像は検証集合としてパスtrain_valid_test/validに分けられる。データセットを整理した後、同じクラスの画像は同じフォルダの下に置かれる。#@save
def copyfile(filename, target_dir):
"""Copy a file into a target directory."""
os.makedirs(target_dir, exist_ok=True)
shutil.copy(filename, target_dir)
#@save
def reorg_train_valid(data_dir, labels, valid_ratio):
"""Split the validation set out of the original training set."""
# The number of examples of the class that has the fewest examples in the
# training dataset
n = collections.Counter(labels.values()).most_common()[-1][1]
# The number of examples per class for the validation set
n_valid_per_label = max(1, math.floor(n * valid_ratio))
label_count = {}
for train_file in os.listdir(os.path.join(data_dir, 'train')):
label = labels[train_file.split('.')[0]]
fname = os.path.join(data_dir, 'train', train_file)
copyfile(fname, os.path.join(data_dir, 'train_valid_test',
'train_valid', label))
if label not in label_count or label_count[label] < n_valid_per_label:
copyfile(fname, os.path.join(data_dir, 'train_valid_test',
'valid', label))
label_count[label] = label_count.get(label, 0) + 1
else:
copyfile(fname, os.path.join(data_dir, 'train_valid_test',
'train', label))
return n_valid_per_labelThe
reorg_test function below organizes the testing set for data loading during prediction.英語のヒント
下の
reorg_test関数は、予測のときのデータの読み込みのために、テスト集合を整理する。#@save
def reorg_test(data_dir):
"""Organize the testing set for data loading during prediction."""
for test_file in os.listdir(os.path.join(data_dir, 'test')):
copyfile(os.path.join(data_dir, 'test', test_file),
os.path.join(data_dir, 'train_valid_test', 'test',
'unknown'))Finally, we use a function to invoke the
read_csv_labels, reorg_train_valid, and reorg_test functions defined above.英語のヒント
最後に、上で定義した
read_csv_labels、reorg_train_valid、reorg_test関数を呼び出す関数を使う。def reorg_cifar10_data(data_dir, valid_ratio):
labels = read_csv_labels(os.path.join(data_dir, 'trainLabels.csv'))
reorg_train_valid(data_dir, labels, valid_ratio)
reorg_test(data_dir)Here we only set the batch size to 32 for the small-scale sample of the dataset. When training and testing the complete dataset of the Kaggle competition,
batch_size should be set to a larger integer, such as 128. We split out 10% of the training examples as the validation set for tuning hyperparameters.英語のヒント
ここでは、小規模なデータセットの見本のためにバッチの大きさを32に設定するだけである。Kaggleのコンペティションの完全なデータセットで訓練とテストをするときは、
batch_sizeを128のようなもっと大きな整数に設定すべきである。ハイパーパラメータを調整するため、訓練事例の10%を検証集合として分ける。batch_size = 32 if demo else 128
valid_ratio = 0.1
reorg_cifar10_data(data_dir, valid_ratio)