Teachable Machine을 사용하여 강아지 표정을 학습시키고, 모델을 불러와 스트림릿 서버에 배포하는 과정을 블로그로 작성하는 방법을 설명해드리겠습니다.
1. Teachable Machine 강아지 표정 학습하기
- Google의 Teachable Machine 웹사이트에 접속합니다.

2. "이미지 프로젝트" 옵션을 선택 후 표준 이미지 모델로 학습하겠습니다.



3. 강아지 표정에 대한 데이터를 준비합니다. (예: 행복, 슬픔, 화남, 평온)

학습용 8 테스트용 2 비율로 데이터를 나눴습니다.
데이터셋은 kaggle 사이트의 Dog Emotion 데이터셋을 사용하였습니다.
(출처 : https://www.kaggle.com/datasets/danielshanbalico/dog-emotion)
4. 각 클래스에 해당하는 강아지 표정 이미지를 업로드합니다.

5. 적절한 에포크와 배치 크기를 지정하여 모델 학습시키기 버튼을 클릭합니다.
(원래는 에포크 100으로 하였으나, 정확도 이슈가 발생하여 에포크 50으로 학습하였습니다.)

6. 학습이 완료되면 테스트 하여 활용할만한 모델인지 확인합니다.
(테스트 파일에 있는 사진으로 테스트하겠습니다.)

7. 테스트가 완료되면 모델 내보내기를 클릭하고 "Tensorflow" 옵션을 선택하여 keras 모델로 다운로드합니다.

2. 모델 불러오기
1. 다운로드한 모델 파일 중 "keras_model.h5"와 "labels.txt"를 프로젝트 폴더로 복사합니다.


3. Streamlit 앱 개발
1. 필요한 라이브러리 설치

2. Streamlit 앱 코드 작성
app.py 파일에 다음 코드를 작성합니다.
import streamlit as st
from keras.models import load_model
from PIL import Image, ImageOps
import numpy as np
import math
import pandas as pd
@st.cache(allow_output_mutation=True)
def load_keras_model():
return load_model("model/keras_model.h5", compile=False)
# 케라스 모델을 로드하고 캐싱하는 함수. 앱 성능 향상을 위해 사용됨
def load_labels():
return open("model/labels.txt", "r", encoding='UTF-8').readlines()
# 레이블 파일을 로드하는 함수
def predict_emotion(image, model, class_names):
size = (224, 224)
image = ImageOps.fit(image, size, Image.Resampling.LANCZOS)
image_array = np.asarray(image)
normalized_image_array = (image_array.astype(np.float32) / 127.5) - 1
data = np.ndarray(shape=(1, 224, 224, 3), dtype=np.float32)
data[0] = normalized_image_array
prediction = model.predict(data)
index = np.argmax(prediction)
class_name = class_names[index]
confidence_score = prediction[0][index]
return class_name[2:], confidence_score
# 이미지를 전처리하고 모델을 사용하여 감정을 예측하는 함수
def main():
st.title('반려견의 감정을 알아보자!')
st.info('반려견의 사진을 업로드 하면, 반려견의 표정을 분석하여 감정을 나타내줍니다.')
# 앱 제목과 설명을 표시
image = st.file_uploader('반려견을 보여주세요!', type=['jpg','png','jpeg','webp'])
# 사용자가 이미지를 업로드할 수 있는 파일 업로더 생성
if image is not None:
image = Image.open(image)
st.image(image, caption='업로드된 이미지', use_column_width=True)
# 업로드된 이미지를 표시
model = load_keras_model()
class_names = load_labels()
# 모델과 레이블 로드
emotion, confidence = predict_emotion(image, model, class_names)
# 감정 예측
st.info(f'반려견은 현재 {math.floor(confidence*100*10)/10}% 확률로 {emotion} 상태입니다.')
# 예측 결과를 표시
# 감정 확률 시각화
st.subheader('감정 확률 분포')
emotion_probs = model.predict(np.expand_dims(np.array(image.resize((224, 224))) / 255, 0))[0]
emotion_df = pd.DataFrame({'emotion': [name[2:].strip() for name in class_names], 'probability': emotion_probs})
st.bar_chart(emotion_df.set_index('emotion'))
# 모든 감정에 대한 확률을 막대 그래프로 시각화
if __name__=='__main__':
main()
# 메인 함수 실행
3. 앱 실행
터미널에서 다음 명령어를 실행하여 로컬에서 앱을 테스트합니다.(Streamlit 기본포트는 :8501입니다.)



6. Streamlit 클라우드에 배포
테스트 결과 문제가 없음을 확인했으므로 Streamlit 클라우드에 배포하겠습니다.
1. Streamlit 클라우드에서 라이브러리를 사용할 수 있게 requirements.txt를 작성합니다.

2. GitHub에 프로젝트를 Commit 후 Pust합니다.
3. Streamlit 사이트로 이동하여 로그인 합니다.

4-1. 이후 화면에서 Create app을 누릅니다.

4-2 Github로 Deploy 하는 것으로 선택합니다.

5. 배포 설정 화면에서 배포할 프로젝트와 메인 파이썬 파일 그리고 " Advanced settings" 를 클릭하여 자신이 작업한 파이썬 버전을 선택하여 배포합니다.



7. Streamlit 클라우드에서 확인
서버에서 똑같이 강아지 표정 예측을 실행해보겠습니다.

로컬호스트에서 서버 도메인으로 바뀐 모습을 확인할 수 있고 기능 구현도 되었다는 것을 알 수 있습니다.
이제 강아지의 감정을 인식하는 웹 애플리케이션이 스트림릿 서버에 배포되었습니다.
사용자는 강아지 사진을 업로드하면 예측된 감정과 함께 각 감정에 대한 확률을 시각화하여 볼 수 있습니다.
Strealit app 주소 : https://animal-app-nvrvwmmvsos8wyiuaowkkh.streamlit.app/
app
This app was built in Streamlit! Check it out and visit https://streamlit.io for more awesome community apps. 🎈
animal-app-nvrvwmmvsos8wyiuaowkkh.streamlit.app
개발자 Github : https://github.com/dmdals1012/animal-app
'Python' 카테고리의 다른 글
| Python에서 Jupyter Notebook을 통해 머신러닝하기 : Clustering편 (1) | 2025.02.21 |
|---|---|
| Python에서 Jupyter Notebook을 통해 머신러닝하기 : Classfication편 (0) | 2025.02.21 |
| Python에서 Jupyter Notebook을 통해 머신러닝하기 : Regression편 (0) | 2025.02.20 |
| Python 데이터 분석 (0) | 2025.02.11 |
| Python 라이브러리 설명 : pandas 편 (0) | 2025.02.10 |