Computer >> 컴퓨터 >  >> 프로그래밍 >> Python

TensorFlow로 꽃 데이터셋을 로드하고 활용하는 방법

이 글에서는 수천 장의 꽃 이미지를 담고 있는 꽃(flowers) 데이터셋을 TensorFlow 환경에 불러오고 전처리하는 방법을 살펴봅니다. 이 데이터셋은 총 5개의 클래스로 구성되어 있으며, 각 클래스마다 별도의 하위 디렉터리가 하나씩 존재합니다.

Google Colaboratory 실행 환경

아래 코드는 Google Colaboratory(Colab)에서 실행됩니다. Colab은 브라우저에서 바로 Python 코드를 실행할 수 있게 해주는 도구로, 별도의 설정 없이 무료로 GPU(그래픽 처리 장치)까지 사용할 수 있다는 장점이 있습니다. Colaboratory는 Jupyter Notebook을 기반으로 만들어졌습니다.

데이터셋 로드 및 학습/검증 세트 분할

'get_file' 메서드를 통해 꽃 데이터셋을 다운로드한 후, 이를 환경에 불러와 작업합니다. 로더에 필요한 매개변수는 명시적으로 지정하며, 불러온 데이터는 학습(training) 세트검증(validation) 세트로 나누어집니다.

print("로더에 사용할 매개변수 정의")
batch_size = 32
img_height = 180
img_width = 180

print("Keras를 사용해 이미지 데이터셋 전처리")
print("데이터셋을 학습 세트와 검증 세트로 분할")

train_ds = tf.keras.preprocessing.image_dataset_from_directory(
    data_dir,
    validation_split=0.2,
    subset="training",
    seed=123,
    image_size=(img_height, img_width),
    batch_size=batch_size)

print("데이터셋을 학습 세트와 검증 세트로 분할")
val_ds = tf.keras.preprocessing.image_dataset_from_directory(
    data_dir,
    validation_split=0.2,
    subset="validation",
    seed=123,
    image_size=(img_height, img_width),
    batch_size=batch_size)

print("하위 디렉터리에 존재하는 클래스 이름 출력")
class_names = train_ds.class_names
print(class_names)

코드 출처: https://www.tensorflow.org/tutorials/load_data/images

실행 결과

Loading parameters for the loader
Preprocessing the image dataset using Keras
Splitting dataset into training and validation set
Found 3670 files belonging to 5 classes.
Using 2936 files for training.
Splitting dataset into training and validation set
Found 3670 files belonging to 5 classes.
Using 734 files for validation.
Printing the class names present in sub-directories
['daisy', 'dandelion', 'roses', 'sunflowers', 'tulips']

실행 결과를 보면 전체 3,670개 파일이 5개 클래스로 분류되었으며, 그중 2,936개 파일은 학습에, 734개 파일은 검증에 사용되었습니다.

코드 설명

  • 매개변수 정의: 배치 크기(batch_size)는 32, 이미지 높이와 너비는 각각 180픽셀로 지정합니다.
  • 데이터셋 분할: 'image_dataset_from_directory' 메서드의 validation_split 옵션을 사용해 전체 데이터의 20%를 검증 세트로, 나머지 80%를 학습 세트로 나눕니다.
  • 클래스 이름 확인: 각 이미지가 분류되는 클래스 이름 목록('daisy', 'dandelion', 'roses', 'sunflowers', 'tulips')이 콘솔에 출력됩니다.