train_datagen = ImageDataGenerator(rescale = 1 / 255.0, rotation_range = 30, width_shift_range = 0.2, height_shift_range = 0.2, shear_range = 0.2, zoom_range = 0.2, horizontal_flip = True)

rotation_range is a value in degrees (0–180), a range within which to randomly rotate pictures.
width_shift and height_shift are ranges (as a fraction of total width or height) within which to randomly translate pictures vertically or horizontally.
shear_range is for randomly applying shearing transformations.
zoom_range is for randomly zooming inside pictures.
horizontal_flip is for randomly flipping half of the images horizontally. This is relevant when there are no assumptions of horizontal assymmetry (e.g. real-world pictures).
위 설명들을 참조해서 ImageDataGenerator의 파라미터에 대입해 주면 이미지 데이터 증강이 된다.

from tensorflow.keras.preprocessing.image import ImageDataGenerator

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

train_generator = train_datagen.flow_from_directory('/tmp/horse-or-human', target_size = (300, 300), class_mode = 'binary')
validation_generator = validation_datagen.flow_from_directory('/tmp/validation-horse-or-human', target_size = (300,300), class_mode = 'binary')

epoch_history = model.fit(train_generator, epochs = 20, validation_data = (validation_generator))

학습시킬 데이터는 넘파이 어레이 인데, 현재 우리는 png 파일로만 준비가 되어있다. 따라서 이미지파일을 넘파이로 바꿔주는 라이브러리를, 텐서플로우가 제공해준다.

 

ImageDataGenerator를 import 하고 rescale 에다 1 / 255.0을 대입한다. 0 ~ 255 로 표현된 rgb값을 0 ~ 1로 만들기 위해서다.

 

변수로 만들어 줬으면, 그다음 할일은, 이미지가 들어있는 디렉토리의 정보, 이미지 사이즈 정보, 분류할 갯수 정보를 알려줘야 한다. 이것들을 flow_from_dirctory에 대입해 준다.
 

 

아래 train_generater는, 넘파이어레이와, 해당 이미지의 정답지도 가지고 있는 변수다. 즉, X_train과 y_train을 모두 한꺼번에 가지고 있다! fit에 학습데이터로 넣어 준뒤 validation_data에는 (validation_generator)를 대입해서 테스트한다.

+ Recent posts