기본 콘텐츠로 건너뛰기

베이즈 몸무게 추론 모델을 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.

댓글

이 블로그의 인기 게시물

Windows에 AMP와 MediaWiki 설치하기

1. 들어가기     AMP는 Apache + MySQL +  Perl/PHP/Python에 대한 줄임말이다. LAMP (Linux + AMP)라고 하여 Linux에 설치하는 것으로 많이 소개하고 있지만 Windows에서도 간편하게 설치하여 사용할 수 있다.       이 글은 Windows 7에 Apache + MySQL + PHP를 설치하고 그 기반에서 MediaWiki를 설치하여 실행하는 과정을 간략히 정리한 것이다. 2. MySQL     * 버전 5.6.12     1) 다운로드         http://dev.mysql.com/downloads/installer/         MySQL Installer 5.6.12         Windows (x86, 32-bit), MSI Installer         (mysql-installer-web-community-5.6.12.0.msi)     2) 다운로드한 MSI 파일을 더블클릭하여 설치를 진행한다.           설치 위치:                   C:\Program Files\MySQL               선택 사항:                       Install MySQL Products             Choosing a Se...

MATLAB Rutime 설치하기

MATLAB Rutime 설치하기 미설치시 에러 MATLAB Runtime 을 설치하지 않은 환경에서 MATLAB 응용프로그램이나 공유 라이브러리를 사용하려고 하면 아래와 같은 에러 메시지가 표시될 것입니다. 처리되지 않은 예외: System.TypeInitializationException: 'MathWorks.MATLAB.NET.Utility.MWMCR'의 형식 이니셜라이저에서 예 외를 Throw했습니다. ---> System.TypeInitializationException: 'MathWorks.MATLAB.NET.Arrays.MWArray'의 형식 이니셜라이저에서 예외를 Throw했습니다. ---> System.DllNotFoundException: DLL 'mclmcrrt9_3.dll'을(를) 로드할 수 없습니다. 지정된 모듈을 찾을 수 없습니다. (예외가 발생한 HRESULT: 0x8007007E) 위치: MathWorks.MATLAB.NET.Arrays.MWArray.mclmcrInitialize2(Int32 primaryMode) 위치: MathWorks.MATLAB.NET.Arrays.MWArray..cctor() --- 내부 예외 스택 추적의 끝 --- 위치: MathWorks.MATLAB.NET.Utility.MWMCR..cctor() --- 내부 예외 스택 추적의 끝 --- 위치: MathWorks.MATLAB.NET.Utility.MWMCR.processExiting(Exception exception) 해결 방법 이 문제를 해결하기 위해서는 MATLAB Runtime 을 설치해야 합니다. 여러 가지 방법으로 MATLAB Runtime 을 설치할 수 있습니다. MATLAB 이 설치되어 있는 경우에는 MATLAB 설치 폴더 아래에 있는 MATLAB Runtime 설치 프로그램을 실행하여 설치합니다. ...

Wi-Fi 카드 2.4GHz로만 동작시키기

Wi-Fi 카드 2.4GHz로만 동작시키기 별도의 Wi-Fi AP 장치를 두지 않고 아래와 같은 기기들로만 Wi-Fi 네트워크를 구성하고자 할 때 주변 기기들이 2.4GHz만 지원하기 때문에 PC에서 실행하는 AP가 항상 2.4GHz를 사용하도록 Wi-Fi 카드를 설정해 주어야 합니다. 기기 Wi-Fi 카드 주파수 대역 Wi-Fi Direct 지원 PC (Windows 10) 2.4GHz, 5GHz O 주변 기기들 2.4GHz X Wi-Fi 카드별 주파수 대역 선택 방법 Windows 시작 메뉴에서 설정 을 클릭합니다. Windows 설정 화면에서 네트워크 및 인터넷 을 클릭합니다. 설정 화면의 왼쪽 메뉴바에서 Wi-Fi 를 클릭합니다. 화면 오른쪽 관련 설정 구역에 있는 어댑터 옵션 변경 을 클릭합니다. 설정을 바꾸고자 하는 Wi-Fi 카드 항목을 선택하고 마우스 오른쪽을 누른 다음 속성 메뉴를 클릭합니다. 대화상자의 네트워킹 탭 화면에 있는 구성 버튼을 클릭합니다. 장치 속성 대화상자의 고급 탭 화면으로 이동합니다. 제시되는 속성 항목들은 제품별로 다르며 자세한 사항은 아래의 제품별 설명을 참고하여 값을 설정하시기 바랍니다. Intel Dual Band Wireless-AC 7265 기술 사양 주파수 대역: 2.4GHz, 5GHz 무선 표준: 802.11ac 주파수 대역 선택 장치 속성 대화상자에서 아래와 같이 선택합니다. Wireless Mode 1. 802.11a => 5GHz 4. 802.11b/g => 2.4GHz (이 항목 선택) 6. 802.11a/b/g => 2.4GHz, 5GHz Intel Dual Band Wireless-AC 8265 기술 사양 주파수 대역: 2.4GHz, 5GHz 무선 표준: 802.11ac 주파수 대역 선택 장치 속성 대화상자에서 아래와 같이 ...