데이터증강.py

TensorFlow Datasets를 활용한 데이터 증강 예제

핵심 개념

  • tensorflow_datasets (tfds) 활용
  • tf_flowers 데이터셋
  • 전처리 레이어 (Resizing, Rescaling)
  • 데이터 증강 (RandomFlip, RandomRotation)
  • CNN 이미지 분류
#pip install tf-nightly
#pip install tensorflow_datasets
#https://www.tensorflow.org/tutorials/images/data_augmentation

import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf
import tensorflow_datasets as tfds  #새로운 데이터셋 다운로드

from tensorflow.keras import layers
from tensorflow.keras.datasets import mnist

# 파일을 다운받으면서 세개로 나눈다
(train_ds, val_ds, test_ds), metadata = tfds.load(
    'tf_flowers',
    split=['train[:80%]', 'train[80%:90%]', 'train[90%:]'],
    with_info=True,
    as_supervised=True,
)

num_classes = metadata.features['label'].num_classes
print(num_classes)  # 5개 클래스

get_label_name = metadata.features['label'].int2str

image, label = next(iter(train_ds))
plt.imshow(image)
plt.title(get_label_name(label))

IMG_SIZE = 180

# 전처리 레이어
resize_and_rescale = tf.keras.Sequential([
  layers.experimental.preprocessing.Resizing(IMG_SIZE, IMG_SIZE),
  layers.experimental.preprocessing.Rescaling(1./255)
])

# 데이터 증강 레이어
data_augmentation = tf.keras.Sequential([
    layers.experimental.preprocessing.RandomFlip("horizontal"),
    layers.experimental.preprocessing.RandomRotation(0.2),
])

# 증강된 이미지 시각화
image = tf.expand_dims(image, 0)

plt.figure(figsize=(10, 10))
for i in range(12):
  augmented_image = data_augmentation(image)
  ax = plt.subplot(3, 4, i + 1)
  plt.imshow(augmented_image[0])
  plt.axis("off")

plt.show()

# 모델 구축 (전처리 + 증강 포함)
model = tf.keras.Sequential([
  resize_and_rescale,
  data_augmentation,
  layers.Conv2D(16, 3, padding='same', activation='relu'),
  layers.MaxPooling2D(),
  layers.Conv2D(32, 3, padding='same', activation='relu'),
  layers.MaxPooling2D(),
  layers.Conv2D(64, 3, padding='same', activation='relu'),
  layers.MaxPooling2D(),
  layers.Flatten(),
  layers.Dense(128, activation='relu'),
  layers.Dense(num_classes)
])

model.compile(optimizer='adam',
              loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
              metrics=['accuracy'])

epochs=5
history = model.fit(
  train_ds,
  epochs=epochs
)

데이터 증강 효과

증강 기법 설명
RandomFlip(“horizontal”) 수평 뒤집기
RandomRotation(0.2) 최대 20% 회전
RandomZoom(0.2) 최대 20% 확대/축소

데이터 증강은 과적합을 방지하고 모델의 일반화 성능을 향상시킵니다.