[Tensorflow] 2. Convolutional Neural Networks in Tensorflow (2 week Augmentation: A technique to avoid overfitting) - Programming (2)

gunny·2024년 4월 14일
0

[Tensorflow] 2. Convolutional Neural Networks in Tensorflow (2 week Augmentation: A technique to avoid overfitting) - Programming (2)

말 또는 인간 데이터세트의 데이터 증강

  • 고양이/개 분류를 위한 데이터 셋에서 데이터 증강을 통하여 모델 성능을 향상시키는 방법을 사용했엇다. 고양이와 개 데이터는 학습 이미지를 조정함으로써 모델은 검증 데이터를 대표하는 특징을 학습할 수 있었다.
  • 그러나 데이터 증강을 적용하려면 데이터 세트를 잘 이해해야 한다. 단순히 무작위로 변환한다고 해서 항상 좋은 결과가 나오는 것은 아니다.
    말 또는 인간 데이터세트에 동일한 기술인 데이터 증강을 적용해보고 결과를 비교해보자.

[1] Data download & data load

import requests

url_1 = 'https://storage.googleapis.com/tensorflow-1-public/course2/week3/horse-or-human.zip'
file_name_1 = "horse-or-human.zip"

response = requests.get(url_2)

with open(file_name_1, 'wb') as f:
    f.write(response.content)
    
print('말-인간 학습 데이터셋 다운로드 완료')


url_2 = 'https://storage.googleapis.com/tensorflow-1-public/course2/week3/validation-horse-or-human.zip'
file_name_2 = "validation-horse-or-human.zip"

response = requests.get(url_2)

with open(file_name_2, 'wb') as f:
    f.write(response.content)
    
print('말-인간 검증 데이터셋 다운로드 완료')

다운 받은 압축 파일 풀기


import os
import zipfile

# Extract the archive
zip_ref = zipfile.ZipFile('./horse-or-human.zip', 'r')
zip_ref.extractall('horse-or-human')

zip_ref = zipfile.ZipFile('./validation-horse-or-human.zip', 'r')
zip_ref.extractall('validation-horse-or-human')

zip_ref.close()

학습 데이터와 검증 데이터의 폴더 위치 지정


# Directory with training horse pictures
train_horse_dir = os.path.join('horse-or-human/horses')

# Directory with training human pictures
train_human_dir = os.path.join('horse-or-human/humans')

# Directory with validation horse pictures
validation_horse_dir = os.path.join('validation-horse-or-human/horses')

# Directory with validation human pictures
validation_human_dir = os.path.join('validation-horse-or-human/humans')


print(train_horse_dir)
print(train_human_dir)
print(validation_horse_dir)
print(validation_human_dir)

horse-or-human/horses
horse-or-human/humans
validation-horse-or-human/horses
validation-horse-or-human/humans

[2] model build & model compile & ImageGenerator & model train

import tensorflow as tf

# Build the model
model = tf.keras.models.Sequential([
    tf.keras.layers.Conv2D(16, (3,3), activation='relu', input_shape=(300, 300, 3)),
    tf.keras.layers.MaxPooling2D(2, 2),
    tf.keras.layers.Conv2D(32, (3,3), activation='relu'),
    tf.keras.layers.MaxPooling2D(2,2),
    tf.keras.layers.Conv2D(64, (3,3), activation='relu'),
    tf.keras.layers.MaxPooling2D(2,2),
    tf.keras.layers.Conv2D(64, (3,3), activation='relu'),
    tf.keras.layers.MaxPooling2D(2,2),
    tf.keras.layers.Conv2D(64, (3,3), activation='relu'),
    tf.keras.layers.MaxPooling2D(2,2),
    tf.keras.layers.Flatten(),
    tf.keras.layers.Dense(512, activation='relu'),
    tf.keras.layers.Dense(1, activation='sigmoid')
])

model.summary()

모델 컴파일

model.compile(loss='binary_crossentropy',
              optimizer=tf.keras.optimizers.RMSprop(learning_rate=1e-4),
              metrics=['accuracy'])

ImageGenerator 생성

from tensorflow.keras.preprocessing.image import ImageDataGenerator

train_datagen = ImageDataGenerator(
      rescale=1./255,
      rotation_range=40,
      width_shift_range=0.2,
      height_shift_range=0.2,
      shear_range=0.2,
      zoom_range=0.2,
      horizontal_flip=True,
      fill_mode='nearest')

validation_datagen = ImageDataGenerator(rescale=1/255)

train_generator = train_datagen.flow_from_directory(
        'horse-or-human/',
        target_size=(300, 300),
        batch_size=128,
        class_mode='binary')

validation_generator = validation_datagen.flow_from_directory(
        'validation-horse-or-human/',
        target_size=(300, 300),
        batch_size=32,
        class_mode='binary')
        
#output
Found 1027 images belonging to 2 classes.
Found 256 images belonging to 2 classes.

모델 학습


EPOCHS = 20

history = model.fit(
    train_generator,
    steps_per_epoch= 8,
    epochs = EPOCHS,
    verbose = 1,
    validation_data = validation_generator,
    validation_steps=8,
)

[3] 모델 평가

import matplotlib.pyplot as plt

# Plot the model results
acc = history.history['accuracy']
val_acc = history.history['val_accuracy']
loss = history.history['loss']
val_loss = history.history['val_loss']

epochs = range(len(acc))

plt.plot(epochs, acc, 'r', label='Training accuracy')
plt.plot(epochs, val_acc, 'b', label='Validation accuracy')
plt.title('Training and validation accuracy')

plt.figure()

plt.plot(epochs, loss, 'r', label='Training Loss')
plt.plot(epochs, val_loss, 'b', label='Validation Loss')
plt.title('Training and validation loss')
plt.legend()

plt.show()

  • 위 학습 결과에서 볼 수 있듯이 데이터 증강이 사용된 전처리 기술은 결과에 큰 도움이 되지 않았.
  • 검증 정확도는 변동이 심하며 훈련 정확도처럼 상승 추세를 보이지 않는다. 이는 생성된 추가 학습 데이터가 여전히 검증 데이터의 기능을 나타내지 않기 때문일 수 있다.
  • 예를 들어 검증 세트의 일부 인간 또는 말 자세는 ImageDataGenerator가 제공하는 이미지 처리 기술로 모방할 수 없다. 훈련 이미지의 배경도 학습되어 검증 세트의 흰색 배경이 자르기에도 모델을 벗어나게 할 수도 있다ek.
  • '/validation-horse-or-human' 디렉터리에 있는 검증 이미지를 살펴보고(참고: Colab을 사용하는 경우 왼쪽의 파일 탐색기를 사용하여 이미지를 탐색할 수 있음) 훈련 이미지를 보강할 수 있는지 확인한 후에 그 특성에 맞게. 이것이 가능하지 않다면 이 시점에서 다른 기술을 고려해 볼 수 있다.
profile
꿈꾸는 것도 개발처럼 깊게

0개의 댓글

관련 채용 정보