• toc {:toc}

Sequence μ΄μš©ν•΄ Custom Dataset λ§Œλ“€κΈ°

Pytorch 의 Dataset 을 상속받아 Custom Dataset 을 λ§Œλ“œλŠ” 방식과 μœ μ‚¬ν•˜λ‹€.

Tensorflow 2.x 버전뢀터 custom dataset loader λ₯Ό λ§Œλ“œλŠ” 방법이 생겼닀.

tensorflow.keras.utils.Sequence λ₯Ό μ‚¬μš©ν•œλ‹€.

init ν•¨μˆ˜ μ •μ˜

class CustomDataset(Sequence):
	def __init__(self, img, labels, batch_size=BATCH_SIZE, augmentor=None, shuffle=False):
	    self.img = img
	    self.labels = labels
	    self.batch_size = BATCH_SIZE
	    self.augmentor = augmentor
	    self.shuffle = shuffle
			
			if self.shuffle:
				self.on_epoch_end()
  • img : 이미지 파일이 μžˆλŠ” directory 경둜, μ΄μ™Έμ˜ 각 픽셀값을 λ‹΄λŠ” numpy array 의 κ²½μš°μ—λŠ” NonImplmentedError κ°€ λ°œμƒν–ˆλ‹€.
  • labels : 이미지 label 을 λ‹΄λŠ”λ‹€.

len ν•¨μˆ˜ μ •μ˜

def __len__(self):
    return int(np.ceil(len(self.labels)/self.batch_size))
  • step 이 λͺ‡ 번 λ°œμƒν•˜λŠ”μ§€λ₯Ό μ˜λ―Έν•œλ‹€.
  • 즉, 전체데이터가 60000 이고 batch_size κ°€ 600 이라면 100 번 λ™μ•ˆ step 을 진행함을 μ˜λ―Έν•œλ‹€.
  • np.ceil 은 λ§Œμ•½ batch_size κ°€ 599 라면 100.xxxxx 번 ν•˜λŠ” 것이 μ•„λ‹Œ 101 λ²ˆμ„ μ§„ν–‰ν•΄μ•Ό ν•˜κΈ° λ•Œλ¬Έμ— 올림 처리둜 μ‚¬μš©ν•œλ‹€.

getitem ν•¨μˆ˜ μ •μ˜

def __getitem__(self, index):
    img_batch = self.img[index*self.batch_size:(index+1)*self.batch_size]
    if self.labels is not None:
        label_batch = self.labels[index*self.batch_size:(index+1)*self.batch_size]
 
    image_batch = np.zeros((img_batch.shape[0], IMAGE_SIZE, IMAGE_SIZE, 3))
 
    for image_index in range(img_batch.shape[0]):
        image = cv2.cvtColor(cv2.imread(img_batch[image_index]), cv2.COLOR_BGR2RGB)
        image = cv2.resize(image, (IMAGE_SIZE, IMAGE_SIZE))
        if self.augmentor is not None:
            image = self.augmentor(image=image)['image']
    
        img_batch[image_index] = image
   
    return img_batch, label_batch
  • index 에 λ”°λΌμ„œ λ°μ΄ν„°μ—μ„œ batch_size 만큼 데이터λ₯Ό κ°€μ Έμ˜€λŠ” ν•¨μˆ˜μ΄λ‹€.
  • ν…ŒμŠ€νŠΈ μ„ΈνŠΈμ˜ 경우 label 이 μ—†κΈ° λ•Œλ¬Έμ— λ”°λ‘œ label 을 μ²˜λ¦¬ν•΄μ€€λ‹€.
  • img_batch κ°€ κ°€μ§€κ³  μžˆλŠ” 값이 directory path 의 값이기 λ•Œλ¬Έμ— cv2 λ₯Ό 톡해 numpy array 둜 λ³€κ²½ν•΄ resize ν•œλ‹€.
  • augmentor κ°€ μ‘΄μž¬ν•˜λŠ” 경우 이미지 각각에 μ μš©ν•˜κ³  img_batch 에 μ €μž₯ν•œλ‹€.
  • img_batch 와 label_batch λ₯Ό λ°˜ν™˜ν•΄ iteration λ§ˆλ‹€ batch λ₯Ό κ°€μ Έμ˜€κ²Œ ν•œλ‹€.

On_epoch_end ν•¨μˆ˜ μ •μ˜

def on_epoch_end(self):
        if(self.shuffle):
            self.image_filenames, self.labels = sklearn.utils.shuffle(self.image_filenames, self.labels)
        else:
            pass
  • On_epoch_end ν•¨μˆ˜λŠ” 선택사항이닀.
  • shuffle 을 μœ„ν•΄ μ‚¬μš©ν•œλ‹€. sklearn.utils.shuffle 을 μ‚¬μš©ν•΄μ„œ μˆœμ„œμ— 따라 shuffle ν•œλ‹€.
  • sklearn.utils.shuffle() : 데이터λ₯Ό λ™μΌν•œ μˆœμ„œλ‘œ μ„žμ–΄μ€€λ‹€.