100일 챌린지/빅데이터기반 인공지능 융합 서비스 개발자

Day 92 - 머신러닝을 활용하는 웹 서비스 만들기

ksyke 2024. 12. 9. 18:02
from pickle import dump
with open("filename.pkl", "wb") as f:
    dump(clf, f, protocol=5)
from pickle import load
with open("filename.pkl", "rb") as f:
    clf = load(f)

skmain.py

https://scikit-learn.org/1.5/model_persistence.html#pickle-joblib-and-cloudpickle

 

9. Model persistence

Summary of model persistence methods:,,, Persistence method, Pros, Risks / Cons,,, ONNX, Serve models without a Python environment, Serving and training environments independent of one another, Mos...

scikit-learn.org

 

%%writefile skmain.py
from fastapi import FastAPI
from pickle import load

with open("sk_iris_dtc.pkl", "rb") as f:
    model = load(f)

app=FastAPI()

@app.post('/iris')
def result(slength:float,swidth:float,plength:float,pwidth:float):
    idx=model.predict([[slength,swidth,plength,pwidth]])[0]
    target=['setosa', 'versicolor', 'virginica']
    return {'result':target[idx]}

Tensorflow

https://www.tensorflow.org/tutorials/keras/save_and_load?hl=ko

 

모델 저장과 복원  |  TensorFlow Core

모델 저장과 복원 컬렉션을 사용해 정리하기 내 환경설정을 기준으로 콘텐츠를 저장하고 분류하세요. 모델 진행 상황은 훈련 중 및 훈련 후에 저장할 수 있습니다. 즉, 모델이 중단된 위치에서

www.tensorflow.org

%%writefile tfmain.py
from fastapi import FastAPI
from tensorflow.keras.models import load_model
import numpy as np

model = load_model('iris_cnn.h5')

app=FastAPI()

@app.post('/iris')
def result(slength:float,swidth:float,plength:float,pwidth:float):
    idx=np.argmax(model.predict(np.array([[slength,swidth,plength,pwidth]])),axis=1)
    target=['setosa', 'versicolor', 'virginica']
    return {'result':target[idx[0]]}

파일 업로드하고 모델 적용하기

https://fastapi.tiangolo.com/ko/tutorial/request-files/

 

파일 요청 - FastAPI

FastAPI framework, high performance, easy to learn, fast to code, ready for production

fastapi.tiangolo.com

https://wikidocs.net/153080

 

1) Pillow 설치 및 이미지 불러오기

오늘은 이미지를 많이 다루고 처리하는 분들을 위해서 파이썬으로 이미지를 다룰 수 있게 해주는 Pillow라는 라이브러리에 대해서 공부해보겠습니다. # 1. Pillow란? P…

wikidocs.net

 

  • opencv 또는 pillow 사용.
  • opencv는 하드웨어 제어 가능.

PIL로 이미지 저장 및 모델 적용

%%writefile uploadmain.py
from typing import Annotated
from PIL import Image
import io
import numpy as np
from fastapi import FastAPI, File, UploadFile
from tensorflow.keras.models import load_model
model = load_model('mnist.h5')

app = FastAPI()

#(233, 255, 3)
@app.post("/files/")
async def create_file(file: Annotated[bytes, File()]):
    #print(file)
    img = Image.open(io.BytesIO(file))
    img = Image.eval(img,lambda x:255-x)
    img = img.resize((28,28))
    img = img.convert("L")
    x = np.array(img)
    print(x)
    print(x.shape)
    X_test = x.reshape(28*28)
    X_test = X_test.astype('float32')
    X_test /= 255
    result=np.argmax(model.predict(np.array([X_test])), axis=1)
    print(result)
    return {"result": str(result)}


@app.post("/uploadfile/")
async def create_upload_file(file: UploadFile):
    print(file.size)
    print(file.content_type)
    print(file.read())
    return {"filename": file.filename}