[파이썬] TensorFlow에서 MobileNet

MobileNet

MobileNet은 Google에서 개발한 경량화된 딥러닝 모델이며, 이를 TensorFlow를 통해 구현할 수 있습니다. MobileNet은 이미지 분류, 객체 감지 및 세분화 등 다양한 컴퓨터 비전 작업에 사용됩니다. 이 글에서는 TensorFlow에서 MobileNet 모델을 불러오고 사용하는 방법을 소개하겠습니다.

MobileNet 설치 및 불러오기

MobileNet은 TensorFlow에 포함되어 있으므로 따로 설치할 필요가 없습니다. 우선 TensorFlow를 설치하세요:

pip install tensorflow

다음으로, TensorFlow에서 MobileNet 모델을 불러오는 방법은 다음과 같습니다:

from tensorflow.keras.applications import MobileNet

# Pre-trained MobileNet 모델 불러오기
model = MobileNet(weights='imagenet')

MobileNet을 통한 이미지 분류

MobileNet 모델을 사용하여 이미지 분류를 수행하는 방법은 다음과 같습니다:

from tensorflow.keras.preprocessing import image
from tensorflow.keras.applications.mobilenet import preprocess_input, decode_predictions

# 이미지 불러오기
img_path = 'image.jpg'
img = image.load_img(img_path, target_size=(224, 224))
x = image.img_to_array(img)
x = preprocess_input(x)
x = np.expand_dims(x, axis=0)

# 이미지 분류
predictions = model.predict(x)
results = decode_predictions(predictions, top=3)[0]

# 결과 출력
for result in results:
    print(f'{result[1]}: {result[2]*100:.2f}%')

MobileNet Fine-tuning

만약 MobileNet 모델을 기존 데이터셋에 맞게 Fine-tuning하고 싶다면, 다음과 같이 할 수 있습니다:

from tensorflow.keras.applications import MobileNet
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import GlobalAveragePooling2D, Dense

# Pre-trained MobileNet 모델 불러오기
base_model = MobileNet(weights='imagenet', include_top=False)

# 새로운 모델 생성
model = Sequential()
model.add(base_model)
model.add(GlobalAveragePooling2D())
model.add(Dense(256, activation='relu'))
model.add(Dense(10, activation='softmax'))

# 기존 가중치 동결
for layer in base_model.layers:
    layer.trainable = False

# 모델 컴파일
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])

위의 코드에서 include_top=False로 설정하여 MobileNet의 Fully Connected Layer를 포함하지 않고, 새로운 Fully Connected Layer를 추가하여 Fine-tuning할 수 있습니다.

TensorFlow에서 MobileNet을 사용하는 방법을 알아보았습니다. MobileNet은 경량화된 딥러닝 모델로써 효율적인 예측을 가능케 하기 때문에 모바일 및 임베디드 기기에서 실시간 컴퓨터 비전 작업에 이상적입니다.