본문 바로가기
머신러닝

[Dataset] Tiny ImageNet

by weareyoung24 2022. 10. 1.

Tiny ImageNet

Tiny ImageNet은 ImageNet의 미니어쳐 버전이다.

 

Image shape (64, 64, 3)
Num classes 200
Training set size 500 per class(100,000)
Validation set size 50 per class(10,000)

Downloading Tiny ImageNet

Linux

wget http://cs231n.stanford.edu/tiny-imagenet-200.zip

Windows / Mac

여기서는 wget을 사용하려면 WSL을 쓰는 등 추가 절차가 필요하다.

간단하게 아래 주소를 크롬 주소창에 넣어서 다운로드하자.

http://cs231n.stanford.edu/tiny-imagenet-200.zip

데이터셋 나누기

TensorFlow에서 ImageDataGenerator를 사용하려면 데이터셋 구조를 살짝 바꿔줘야 한다.

개인적으로 데이터를 디렉토리에서 가져오는것을 선호하기에 학습을 위해 데이터를 나눠준다.

다운로드한 데이터셋의 압축을 풀고 동일 디렉토리에서 아래 파이썬 코드를 실행하면 데이터를 나눌 수 있다.

tiny-imagenet-200 디렉토리 안에 train_preprocess, valid_preprocess 디렉토리가 생기고 그 안에 데이터가 복사된다.

import os
import shutil
import pandas as pd

def main():
	# 디렉토리 생성 및 초기화
    BASE = './tiny-imagenet-200'
    tr_target = os.path.join(BASE, 'train')
    val_target = os.path.join(BASE, 'val')
    if not os.path.isdir(os.path.join(BASE, 'train_preprocess')):
        os.mkdir(os.path.join(BASE, 'train_preprocess'))
    if not os.path.isdir(os.path.join(BASE, 'valid_preprocess')):
        os.mkdir(os.path.join(BASE, 'valid_preprocess'))
    tr_destination = os.path.join(BASE, 'train_preprocess')
    val_destination = os.path.join(BASE, 'valid_preprocess')

    tr_target_list = os.listdir(tr_target)
	
    # Training data 복사
    for dir_ in tr_target_list:
        img_list = os.listdir(os.path.join(tr_target, dir_, 'images'))
        if not os.path.isdir(os.path.join(tr_destination, dir_)):
            os.mkdir(os.path.join(tr_destination, dir_))
        if not os.path.isdir(os.path.join(val_destination, dir_)):
            os.mkdir(os.path.join(val_destination, dir_))
        for img in img_list:
            img = os.path.join(tr_target, dir_, 'images', img)
            dest = os.path.join(tr_destination, dir_)
            if not os.path.isdir(os.path.join(dest, dir_, img)):
                shutil.copy(img, dest)
	
    # Validation data 복사
    with open(os.path.join(val_target, "val_annotations.txt"), 'r') as val_info:
        lines = val_info.readlines()

    val_info = pd.read_csv(os.path.join(val_target, "val_annotations.txt"),
                           sep = "\t",
                           names=['img', 'label', 'bx1', 'bx2','bx3', 'bx4'],
                           header=None)

    val_img = list(val_info['img'])
    val_label = list(val_info['label'])
    assert len(val_img) == len(val_label)

    for img, label in zip(val_img, val_label):
        img = os.path.join(val_target, 'images', img)
        dest = os.path.join(val_destination, label)
        shutil.copy(img, dest)

if __name__ == "__main__":
    main()

실행 후 데이터가 나눠져있음을 볼 수 있다.

아래 코드는 TensorFlow ImageDataGenerator API로 데이터를 불러오는 과정이다.

train_dir = './tiny-imagenet-200/train_preprocess'
valid_dir = './tiny-imagenet-200/valid_preprocess'

train_datagen = ImageDataGenerator(rescale=1/255) 
validation_datagen = ImageDataGenerator(rescale=1/255)

train_generator = train_datagen.flow_from_directory(train_dir,
                                                    batch_size = BATCH_SIZE,
                                                    target_size = IMG_SIZE,
                                                    class_mode='categorical',
                                                    seed=SEED,
                                                    shuffle=True)

validation_generator = validation_datagen.flow_from_directory(valid_dir,
                                                              batch_size = BATCH_SIZE,
                                                              target_size = IMG_SIZE,
                                                              class_mode = 'categorical',
                                                              seed=SEED,
                                                              shuffle=True)

그럼 오늘도 다들 해피한 코딩하시길 :)

댓글