페이지

2019년 7월 29일 월요일

베이즈 몸무게 추론 모델을 Heroku에 배포하기

베이즈 몸무게 추론 모델을 Heroku에 배포하기

실습 준비

개발 환경

  • Windows 10
  • Anaconda 2019.03
  • Python 3.7
  • Flask 1.1.1

배포 환경

  • Heroku
  • Python
  • Flask
  • Gunicorn

설치 프로그램

  1. Git
  2. Heroku CLI
  3. Anaconda

프로젝트 폴더

프로젝트 소스는 아래 URL에서 다운로드할 수 있습니다.
프로젝트 폴더 구조
bayesian-weight-inference\
    templates\
        index.html
        result.html
    .gitignore
    Procfile
    README.md
    requirements.txt
    script.py

Heroku 계정 생성

  • Heroku 사이트에서 무료 계정을 생성합니다.

실습 진행

프로젝트 폴더 작업

script.py 파일 추가
  • bayesian-weight-inference 폴더 아래에 script.py 파일을 추가하고 텍스트 파일 편집기를 사용하여 아래 내용을 저장합니다.
    import numpy as np
    import scipy.stats as stats
    import flask
    
    app = flask.Flask(__name__)
    
    def get_posteriori(w_prior, s_prior, w_actual, s_actual, w_measured_arr):
        l_measured = stats.norm.pdf(w_measured_arr, w_actual, s_actual)
        weighting = stats.norm.pdf(w_actual, w_prior, s_prior)
        posteriori = np.prod(l_measured * weighting)
        return posteriori
        
    def ValuePredictor(request_params):
        w_measured_arr = []
        for str in request_params['w_measured'].split(','):
            w_measured_arr.append(float(str))
        
        s_actual = float(request_params['s_actual'])
            
        w_prior = float(request_params['w_prior'])
        s_prior = float(request_params['s_prior'])
        
        print(f'w_measured : {w_measured_arr}')
        print(f's_actual   : {s_actual}')
        print(f'w_prior    : {w_prior}')
        print(f's_prior    : {s_prior}')
        
        w_actual_arr = np.arange(10, 200, 0.1)
        posteriori_arr = []
            
        for w_actual in w_actual_arr:
            posteriori = get_posteriori(w_prior, s_prior, w_actual, s_actual, w_measured_arr)
            posteriori_arr.append(posteriori)
    
        peak_location = w_actual_arr[np.argmax(posteriori_arr)]
        print(f'Peak location: {peak_location:.1f}')
        
        return peak_location
    
    @app.route('/')
    @app.route('/index')
    def index():
        return flask.render_template('index.html')
    
    @app.route('/result', methods = ['POST'])
    def result():
        if flask.request.method == 'POST':
            request_params = flask.request.form.to_dict()
            
            result = ValuePredictor(request_params)
            prediction = f'{result:.1f}'
            
            return flask.render_template("result.html", prediction = prediction)
    

가상환경 구성하기

Anaconda Prompt 창에서 실습을 진행합니다.
  1. 가상환경 만들기
    > conda create -n bayesian_weight_inference
    
  2. 가상환경 활성화
    > conda activate bayesian_weight_inference
    
  3. 라이브러리 설치
    > conda install pip
    > pip install flask
    > pip install gunicorn
    > pip install numpy
    > pip install scipy
    

웹앱을 로컬에서 실행하기

  1. Anaconda Prompt 창을 열고 아래 폴더로 이동합니다.
    > cd bayesian-weight-inference
    
  2. 웹앱 실행
    > set FLASK_APP=script.py
    > flask run
    
  3. 브라우져로 확인
    1. 브라우져로 http://localhost:5000/ 주소의 페이지를 엽니다.
    2. HTML 폼에 값들을 입력하고 Submit 버튼을 클릭합니다.
    3. Inferred actual weight: xx kg 메시지가 표시되면 오류 없이 정상적으로 실행된 것입니다.
      • 오류가 발생하면 웹앱 실행 프롬프트 창에서 오류와 관련된 메시지가 있는지 확인하고 이를 해결합니다.

Heroku 웹앱으로 준비하기

  1. Anaconda Prompt 창을 열고 아래 폴더로 이동합니다.
    > cd bayesian-weight-inference
    
  2. requirements.txt 파일 만들기
    > pip freeze > requirements.txt
    
    생성된 requirements.txt 파일 내용은 아래와 같습니다.
    certifi==2019.6.16
    Click==7.0
    Flask==1.1.1
    gunicorn==19.9.0
    itsdangerous==1.1.0
    Jinja2==2.10.1
    MarkupSafe==1.1.1
    numpy==1.17.0
    scipy==1.3.0
    Werkzeug==0.15.5
    wincertstore==0.2
    
  3. Procfile 파일 만들기
    bayesina-weight-inference 폴더 아래에 Procfile 파일을 추가하고 텍스트 파일 편집기를 사용하여 아래 내용을 저장합니다.
    web: gunicorn script:app
    
  4. .gitignore 파일 만들기
    bayesina-weight-inference 폴더 아래에 .gitignore 파일을 추가하고 텍스트 파일 편집기를 사용하여 아래 내용을 저장합니다.
    __pycache__/
    
  5. Git 저장소 만들기
    > git init
    > git add .
    > git commit -m "Initial commit."
    

웹앱을 Heroku 클라우드로 배포하기

  1. Command Prompt 창을 열고 아래 폴더로 이동합니다.
    > cd bayesian-weight-inference
    
  2. Heroku 클라우드에 로그인
    > heroku login -i
    
  3. Heroku 클라우드에 앱 생성
    > heroku create trvoid-weight-inference
    Creating ⬢ trvoid-weight-inference... done
    https://trvoid-weight-inference.herokuapp.com/ | https://git.heroku.com/trvoid-weight-inference.git
    
  4. 웹앱 배포장소를 Heroku 클라우드로 지정하기
    > heroku git:remote -a trvoid-weight-inference
    set git remote heroku to https://git.heroku.com/trvoid-weight-inference.git
    
  5. 웹앱을 배포하기
    > git push heroku master
    ...
    remote:        https://trvoid-weight-inference.herokuapp.com/ deployed to Heroku
    remote:
    remote: Verifying deploy... done.
    To https://git.heroku.com/trvoid-weight-inference.git
     * [new branch]      master -> master
    
  6. 브라우져에서 웹앱 열기
    브라우져에서 아래 주소의 페이지를 엽니다.
    또는 명령 프롬프트에서 아래 명령을 사용하여 위 주소의 페이지를 브라우져로 열 수 있습니다.
    > heroku open
    
Written with StackEdit.

댓글 없음:

댓글 쓰기

가설 검정 제대로 이해하기

가설 검정 제대로 이해하기 용어 정리 출처: 위키백과 , WIKIPEDIA 통계적 추론 추론 통계 또는 추론 통계학(inferential statistics)으로 불린다. 기술 통계학(descripti...