딥러닝
[딥러닝] 데이터 증강(ImageDataGenerator)
퓨어맨
2022. 7. 26. 10:33
데이터 증강(이미지 증식)
- 모델의 과대적합을 방지하기 위한 기법 중 하나
- 유사한 이미지를 생성하여 학습에 용이하게 만들어주고 학습데이터의 양 자체를 늘려주는 효과
from tensorflow.keras.preprocessing.image import ImageDataGenerator
# ImageDataGenerator : 이미지 데이터를 생성하기 위한 조건을 설정하는 함수
aug = ImageDataGenerator(rotation_range=30, # 이미지 회전 각도
width_shift_range=0.2, # 20% 내외 수평이동
height_shift_range=0.2, # 20% 내외 수직이동
zoom_range=0.2, # 0.8 ~ 1.2배로 축소/확대
horizontal_flip=True, # 수평방향으로 뒤집기
fill_mode='nearest' # 이미지가 변형되면서 비는 공간을 가장 가까운 픽셀값으로 채워줌
)
pre_trained_model2 = VGG16(include_top=False,
input_shape=(224,224,3),
weights='imagenet'
)
for layer in pre_trained_model2.layers :
if layer.name == 'block5_conv3' :
layer.trainable = True
else :
layer.trainable = False
cnn_model4 = Sequential()
cnn_model4.add(pre_trained_model2)
cnn_model4.add(Flatten())
cnn_model4.add(Dense(128, activation ='relu'))
cnn_model4.add(Dense(64, activation ='relu'))
cnn_model4.add(Dense(32, activation ='relu'))
cnn_model4.add(Dense(3, activation ='softmax'))
cnn_model4.compile(loss='sparse_categorical_crossentropy',
optimizer='Adam',
metrics =['acc']
)
# flow : ImageDataGenerator로 설정한 조건을 통해 이미지를 생성하여 학습에 적용시켜주는 함수
cnn_model4.fit(aug.flow(X_train, y_train, batch_size=128),
# 한 epoch 당 7.5번 돌고 끝나게 됨(128 * 7.5으로 총 960개의 새로운 이미지를 생성)
steps_per_epoch=len(X_train) / 128,
epochs=50
)
# 1epoch 때 증식된 이미지 960개로 학습, 2epoch 때 960개가 추가되어서 총 1920개로 학습
pre = cnn_model4.predict(X_test)
print(classification_report(y_test, np.argmax(pre, axis=1)))
precision recall f1-score support
0 0.85 0.85 0.85 87
1 0.88 0.82 0.85 79
2 0.80 0.85 0.82 74
accuracy 0.84 240
macro avg 0.84 0.84 0.84 240
weighted avg 0.84 0.84 0.84 240