기본 콘텐츠로 건너뛰기

Flask(플라스크) - 머신러닝, 딥러닝 웹 서비스 예제 소스 및 개념 설명(2)

Flask(플라스크) - 머신러닝, 딥러닝 웹 서비스 예제 소스 및 개념 설명(2)

import flask

from flask import Flask, request, render_template

from sklearn.externals import joblib

import numpy as np

from scipy import misc

from ml.model import export_model

from flask_restful import Resource, Api

app = Flask(__name__)

api = Api(app)

# 메인 페이지 라우팅

@app.route( "/" )

@app.route( "/index" )

def index():

return flask.render_template( 'index.html' )

# 데이터 예측 처리

@app.route( '/predict' , methods = [ 'POST' ])

def make_prediction():

if request.method = = 'POST' :

# 업로드 파일 처리 분기

file = request.files[ 'image' ]

if not file : return render_template( 'index.html' , ml_label = "No Files" )

# 이미지 픽셀 정보 읽기

# 알파 채널 값 제거 후 1차원 Reshape

img = misc.imread( file )

img = img[:, :, : 3 ]

img = img.reshape( 1 , - 1 )

# 입력 받은 이미지 예측

prediction = model.predict(img)

# 예측 값을 1차원 배열로부터 확인 가능한 문자열로 변환

label = str (np.squeeze(prediction))

# 숫자가 10일 경우 0으로 처리

if label = = '10' : label = '0'

# 결과 리턴

return render_template( 'index.html' , ml_label = label)

# 데이터 모델 재학습

@app.route( '/retrain' , methods = [ 'POST' ])

def make_model():

if request.method = = 'POST' :

# 모델 재 생성

export_model( 'R' )

return render_template( 'index.html' , md_label = '모델 재생성 완료' )

# 데이터 모델 재학습(RestApi)

class RestMl(Resource):

def get(self):

export_model( 'R' )

return { 'result' : True, 'modelName' : 'model.pkl' }

# Rest 등록

api.add_resource(RestMl, '/retrainModel' )

if __name__ = = '__main__' :

# 모델 로드

# ml/model.py 선 실행 후 생성

model = joblib.load( './model/model.pkl' )

# Flask 서비스 스타트

from http://niceman.tistory.com/193 by ccl(S)

댓글

이 블로그의 인기 게시물

[GCP] Flask로 TF 2.0 MNIST 모델 서빙하기

[GCP] Flask로 TF 2.0 MNIST 모델 서빙하기 Google Cloud Platform 우선 TensorFlow 2.0을 설치하자. 머신에 직접 설치하거나 도커를 다운받아 사용, 혹은 구글 colab을 활용( https://www.tensorflow.org/install)하면 되는데, TensorFlow에서 권장하는대로 머신에 VirtualEnv를 활용해서 설치하자 ( https://www.tensorflow.org/install/pip). 설치하는 김에 Flask도 같이 설치해보자. Compute Machine 하나를 생성(크게 부담 없는 예제라 g1 instance)하고, SSH를 연결하여 실행하면 된다. $ sudo apt update $ sudo apt install python3-dev python3-pip $ sudo pip3 install -U virtualenv # 굳이 system-wide로 flask를 설치할 필요는 없지만 그렇게 했다. $ sudo pip3 install flask $ sudo pip3 install flask-restful # virtualenv 환경에서 tensorflow 2.0 설치 $ virtualenv --system-site-packages -p python3 ./venv $ source ./venv/bin/activate # sh, bash, ksh, or zsh (venv) $ pip install --upgrade pip (venv) $ pip install --upgrade tensorflow 모든 환경이 마련되었으니, 우선 MNIST 모델을 TF 2.0으로 Training하여 모델을 Save 해 두자(tf_mnist_train.py). 대략 99% 이상 정확도가 나온다! import tensorflow as tf import numpy as np # 학습 데이터 load ((train_data, train_label), (eval_data, eval_label)) = tf....

스프링 프레임워크(Spring Framework)란?

스프링 프레임워크(Spring Framework)란? "코드로 배우느 스프링 웹 프로젝트"책을 개인 공부 후 자료를 남기기 위한 목적이기에 내용 상에 오류가 있을 수 있습니다. '스프링 프레임워크'가 무엇인지 말 할 수 있고, 해당 프레임워크의 특징 및 장단점을 설명할 수 잇는 것을 목표로합니다. 1. 프레임워크란? 2. 스프링 프레임워크 "뼈대나 근간을 이루는 코드들의 묶음" Spring(Java의 웹 프레임워크), Django(Python의 웹 프레임워크), Flask(Python의 마이크로 웹 프레임워크), Ruby on rails(Ruby의 웹 프레임워크), .NET Framework, Node.js(Express.js 프레임워크) 등등. 프레임워 워크 종류 : 3. 개발 시간을 단축할 수 있다. 2. 일정한 품질이 보장된 결과물을 얻을 수 있다. 1. 실력이 부족한 개발자라 허다러도 반쯤 완성한 상태에서 필요한 부분을 조립하는 형태의 개발이 가능하다. 프레임워크를 사용하면 크게 다음 3가지의 장점 이 있습니다. 프레임워크 이용 한다는 의미 : 프로그램의 기본 흐름이나 구조를 정하고, 모든 팀원이 이 구조에 자신의 코드를 추가하는 방식으로 개발 한다. => 이러한 상황을 극복하기 위한 코드의 결과물이 '프레임워크' 입니다. 개발자는 각 개개인의 능력차이가 크고, 따라서 개발자 구성에 따라서 프로젝트의 결과 차이가 큽니다. 2. 스프링 프레임워크(Spring Framework) 자바 플랫폼을 위한 오픈 소스 애플리케이션 스프링의 다른 프레임워크와 가장 큰 차이점은 다른 프레임워크들의 포용 입니다. 이는 다시말해 기본 뼈대를 흔들지 않고, 여러 종류의 프레임워크를 혼용해서 사용할 수 있다는 점입니다. 대한민국 공공기관의 웹 서비스 개발 시 사용을 권장하고 있는 전자정부 표준프레임워크 이다. 여러 프레임워크들 중 자바(JAV...

Dummy to resolve the flask problems

Dummy to resolve the flask problems This post is about flask problems that I struggled with. Hope you this is useful things when you taste it. Issue : How to deploy a flask application on Apache2 Resolve : As you know, flask is a micro framework. It can be handled on Apache2 using WSGI module. See the reference. Reference: https://www.digitalocean.com/community/tutorials/how-to-deploy-a-flask-application-on-an-ubuntu-vps Issue : Flask caused ERR_CONNECTION_ABORTED on POST Resolve : There are lots issues for this problem in principle. It caused when browser keep sending some buffer but server doesn't want to receive. My case is like this (submit.html) (submit.py) @bp.route('/submit', methods=["GET", "POST"]) def submit(): return render_template("submit.html") This kinda skel code to explain this. In flask case, this can be caused when it runs as develop server such as run...