TensorFlow tf.keras.applications 개요

요약: tf.keras.applications 모듈은 ImageNet 등 대규모 데이터셋으로 사전 학습된 다양한 컴퓨터 비전 모델을 손쉽게 불러와, 특징 추출(feature extraction)미세 조정(fine-tuning)을 수행할 수 있도록 지원합니다[1].

주요 기능

  • 사전학습 모델 인스턴스화
  • tf.keras.applications.<ModelName>(...) 형태로 사용
  • 입력 전처리
  • preprocess_input 함수로 이미지 배열을 모델에 맞게 변환[2]
  • 예측 결과 해석
  • decode_predictions 함수로 ImageNet 클래스 이름과 확률을 반환[2]
  • 전이 학습
  • 특징 추출(feature extraction): 사전학습된 모델의 하위 층을 고정하고, 상위에 분류기만 학습
  • 미세 조정(fine-tuning): 사전학습된 모델의 일부 층까지 재학습하여 성능 향상[1]

제공되는 주요 모델 목록

DenseNet

  • DenseNet121, DenseNet169, DenseNet201
    EfficientNet
  • EfficientNetB0 ~ B7
    EfficientNetV2
  • EfficientNetV2B0, V2B1, V2B2, V2B3, V2M, V2S, V2L
    Inception
  • InceptionV3, InceptionResNetV2
    MobileNet
  • MobileNet, MobileNetV2, MobileNetV3Small, MobileNetV3Large
    NASNet
  • NASNetMobile, NASNetLarge
    ResNet
  • ResNet50, ResNet101, ResNet152
    ResNetV2
  • ResNet50V2, ResNet101V2, ResNet152V2
    VGG
  • VGG16, VGG19
    Xception
  • Xception
    ConvNeXt
  • ConvNeXtTiny, ConvNeXtSmall, ConvNeXtBase, ConvNeXtLarge, ConvNeXtXLarge[2]

주요 인수 비교

인수설명기본값
weights사전학습 가중치('imagenet', None)'imagenet'
include_top최상위 분류기(Fully-Connected) 포함 여부True
input_shape입력 이미지 크기 (H, W, C)모델별 권장 크기
classes분류 클래스 수 (include_top=False 시 사용)1000
pooling전역 풀링 방식('avg', 'max', None)None

기본 사용 예제

from tensorflow.keras.applications.resnet50 import ResNet50, preprocess_input, decode_predictions
from tensorflow.keras.preprocessing import image
import numpy as np

# 1. 모델 로드
model = ResNet50(
    weights='imagenet',
    include_top=True,
    input_shape=(224, 224, 3),
    classes=1000
)

# 2. 이미지 전처리
img = image.load_img('elephant.jpg', target_size=(224, 224))
x = image.img_to_array(img)
x = np.expand_dims(x, axis=0)
x = preprocess_input(x)

# 3. 예측 및 결과 해석
preds = model.predict(x)
print(decode_predictions(preds, top=3))

위 코드는 ResNet50 모델을 ImageNet 가중치로 로드한 뒤, 이미지를 전처리하고 상위 3개 클래스 예측 결과를 출력합니다[3].

전이 학습(Transfer Learning) 워크플로우

  1. 특징 추출 (Feature Extraction)
  • include_top=False로 최상위 분류기를 제거
  • 사전학습된 모델의 모든 층을 trainable=False로 고정
  • 새로운 분류기 레이어를 추가하여 학습
  1. 미세 조정 (Fine-Tuning)
  • 분류기만 학습한 뒤, 사전학습된 모델의 상위 일부 층(예: 마지막 4개 층)을 trainable=True로 전환
  • 전체 모델을 낮은 학습률로 재학습하여 성능 향상
import tensorflow as tf

# VGG16을 feature extractor로 사용
base_model = tf.keras.applications.VGG16(
    include_top=False,
    weights='imagenet',
    input_shape=(224, 224, 3)
)
# 대부분의 층 고정
for layer in base_model.layers[:-4]:
    layer.trainable = False

# 새로운 분류기 추가
x = base_model.output
x = tf.keras.layers.Flatten()(x)
x = tf.keras.layers.Dense(512, activation='relu')(x)
x = tf.keras.layers.Dropout(0.5)(x)
outputs = tf.keras.layers.Dense(3, activation='softmax')(x)

model = tf.keras.Model(inputs=base_model.input, outputs=outputs)
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])

최상위 4개 층만 재학습 대상으로 설정하여, 작은 데이터셋에서도 높은 성능을 얻을 수 있습니다[4].

주요 활용 시나리오:

  • 특징 추출: 빠른 실험 및 적은 데이터로도 모델 구축 가능
  • 미세 조정: 적당한 크기의 데이터셋으로도 최첨단 성능 달성 가능[1]

출처
[1] [TensorFlow] Vision Modeling(2) Transfer Learning https://littlefoxdiary.tistory.com/86
[2] 강의 01 applications 패키지 기학습 모델–임시이미지 – 위키독스 https://wikidocs.net/103926
[3] [Keras] Keras Applications 사용 방법 – A Head Full Of Dreams https://vivalee.tistory.com/entry/Keras-Keras-Applications-%EC%82%AC%EC%9A%A9-%EB%B0%A9%EB%B2%95
[4] Ch8. Model of Keras Application – velog https://velog.io/@korkite/Ch8.-Model-of-Keras-Application
[5] Pretrained Models for Transfer Learning in Keras for Computer Vision https://dev.to/amananandrai/pretrained-models-for-transfer-learning-in-keras-for-computer-vision-5eei
[6] Module: tf.keras | TensorFlow v2.7.4 https://www.tensorflow.org/versions/r2.7/api_docs/python/tf/keras
[7] Applications – Keras Documentation https://faroit.com/keras-docs/1.2.0/applications/
[8] MobileNet, MobileNetV2, and MobileNetV3 – Keras https://keras.io/api/applications/mobilenet/
[9] Keras Applications https://keras.io/api/applications/
[10] The Model class – Keras https://keras.io/api/models/model/
[11] Module: tf.keras.applications | TensorFlow v2.16.1 https://www.tensorflow.org/api_docs/python/tf/keras/applications
[12] 딥러닝 | tf.keras 주요 모듈 정리 – velog https://velog.io/@ksolar03/%EB%94%A5%EB%9F%AC%EB%8B%9D-tf.keras-%EC%A3%BC%EC%9A%94-%EB%AA%A8%EB%93%88-%EC%A0%95%EB%A6%AC
[13] Use tensorflow operation in tf.keras Model https://stackoverflow.com/questions/49616081/use-tensorflow-operation-in-tf-keras-model
[14] 케라스와 텐서플로우와의 통합 – 김태영의 케라스 블로그 https://tykimos.github.io/2017/02/22/Integrating_Keras_and_TensorFlow/
[15] Keras: The high-level API for TensorFlow https://www.tensorflow.org/guide/keras
[16] Keras documentation: Data loading https://keras.io/api/data_loading/
[17] Keras | TensorFlow Core https://www.tensorflow.org/guide/keras?hl=ko
[18] KerasLayer vs tf.keras.applications performances – Stack Overflow https://stackoverflow.com/questions/59994205/keraslayer-vs-tf-keras-applications-performances
[19] Keras 모델 저장 및 로드 | TensorFlow Core https://tensorflow.google.cn/guide/keras/save_and_serialize?hl=ko
[20] [TensorFlow] Dataset 모듈 및 TFRecord 기본 사용법 정리 https://hcnoh.github.io/2018-11-05-tensorflow-data-module
[21] [딥러닝] Tensorflow에서 모델 생성하는 법 https://minimin2.tistory.com/106
[22] 텐서플로 라이트 모델 개발 (2) – 모델 개발 실습 – velog https://velog.io/@jiyeah3108/%ED%85%90%EC%84%9C%ED%94%8C%EB%A1%9C-%EB%9D%BC%EC%9D%B4%ED%8A%B8-%EB%AA%A8%EB%8D%B8-%EA%B0%9C%EB%B0%9C-2-%EB%AA%A8%EB%8D%B8-%EA%B0%9C%EB%B0%9C
[23] 모듈, 레이어 및 모델 소개 | TensorFlow Core https://www.tensorflow.org/guide/intro_to_modules
[24] Tensorflow 케라스 EfficientNet Finetuning 예제 – 1 – 딥딥딥 – 티스토리 https://deep-deep-deep.tistory.com/18
[25] Attentions — tf-keras-vis v0.8.8 documentation https://keisen.github.io/tf-keras-vis-docs/examples/attentions.html

코멘트

답글 남기기

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다