DeepLearning/CNN

[Keras] EfficientNet 설명 및 예시

헬로희 2024. 11. 29. 21:01
728x90

기본 EfficientNet B0~B7까지 다룸. V2 등등은 공부예정

EfficientNet이란?

이 글은 논문 " EfficientNet: Rethinking Model Scaling for Convolutional Neural Networks " 을 참고하여 작성됨.

  1. Baseline: The original network without scaling.
  2. Width Scaling: Increasing the number of channels in each layer.
  3. Depth Scaling: Increasing the number of layers.
  4. Resolution Scaling: Increasing the input image resolution.
  5. Compound Scaling: Simultaneously increasing width, depth, and resolution according to the compound scaling formula.

설명과 같이 EfficientNet은 (a) Baseline을 기준으로 레이어가 균등하게 (b) 폭이 늘어나거나, (c) 깊이가 늘어나거나 (d) 해상도가 커질 수으며, (e) 복합적으로 늘이거나 줄일 수 있다. 논문에서 EfficientNet은 CNN 모델로 레이어들을 "균등하게" Scaling하는 네트워크로 정의하고 있다.

Baseline이 되는 B0의 레이어 구조는 다음과 같다


EfficientNet은 Baseline이 되는 B0부터 B7까지 존재하며 숫자가 커질수록 복잡한 모델로 성능이 더 우수하다.

  • EfficientNet-B0: The baseline model with moderate depth, width, and resolution.
  • EfficientNet-B1 to B7: Successively larger variants achieved by increasing the compound scaling coefficient φ.
  • EfficientNet-Lite: Lightweight variants designed for mobile and edge devices, achieving a good balance between performance and efficiency.

EfficientNet의 Input과 Output은 다음과 같다.
실제 네트워크를 사용할 때 Input Size를 정의할 수 있지만,
아래는 최적의 Input Size로 처음 학습시 이 size로 시작하는 것을 추천한다.

  B0 B1 B2 B3 B4 B5 B6 B7
Input 224,224,3 240,240,3 260,260,3 300,300,3 380,380,3 456,456,3 528,528,3 600,600,3
Output 1280 1280 1408 1536 1792 2048 2304 2560

Example)

Cifar10을 이용하여 EfficientNet B0를 학습 및 평가하려고 한다.

import os
import tensorflow as tf
import numpy as np

from tensorflow.python.client import device_lib #gpu 사용
print(device_lib.list_local_devices()) # cpu와 gpu 확인
os.environ["CUDA_VISIBLE_DEVICES"] = "0" #"-1"은 cpu

#cifar10 images 사용
(x_train, y_train),(x_test, y_test) = tf.keras.datasets.cifar10.load_data()
#test data에서 validation data 용으로 일부 나눔
x_valid=x_test[:300]
y_valid=y_test[:300]
x_test2 = x_test[300:]
y_test2 = y_test[300:]

cls = np.unique(y_train) # y값 종류가 몇 개 있는지 확인 (0~9)
h,w,ch = x_train[0].shape # image size 확인 (32,32,3)

model = tf.keras.applications.EfficientNetB0(include_top = False,
                                             weights=None,
                                             input_shape=(h, w, ch),
                                             classes=len(cls),
                                             classifier_activation='softmax')
model.compile(optimizer="adam", loss="sparse_categorical_crossentropy", metrics=["accuracy"])
"""
loss에 "categorical_crossentropy"는 label이 0과 1로만 이루어진 one-hot-encoded 여야 사용가능한데,
integer로 되어 있으면 "sparse_catrgorical_crossentropy"를 사용해야 함.
"categorical_crossentropy"의 이점은 class확률을 제공함
"""

model.fit(x_train, y_train, epochs=100, batch_size=32,validation_data=(x_valid, y_valid))
test_loss, test_acc = model.evaluate(x_test2,  y_test2, verbose=2)
print(test_acc)

 

 

 

728x90