기본 콘텐츠로 건너뛰기

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

댓글

이 블로그의 인기 게시물

Intel MKL 예제를 Microsoft Visual C++로 빌드하기

Intel MKL 예제를 Microsoft Visual C++로 빌드하기 인텔 프로세서 시스템에서 아래의 영역에 해당하는 수학 계산을 빠르게 수행하고자 한다면 Intel MKL 라이브러리를 사용할 수 있습니다. Linear Algebra Fast Fourier Transforms (FFT) Vector Statistics & Data Fitting Vector Math & Miscellaneous Solvers 이 문서는 Intel MKL 이 제공하는 예제 파일을 Microsoft Visual C++ 로 컴파일하고 링크하여 실행 파일을 만드는 과정을 소개합니다. 빌드 환경 다음은 이 문서를 작성하는 과정에서 Intel MKL 예제를 빌드하기 위하여 사용한 환경입니다. 시스템 운영체제: Windows 10 (64비트) 프로세서: Intel Core i7 설치 제품 IDE: Microsoft Visual Studio Community 2019 (version 16) 라이브러리: Intel Math Kernel Library 2019 Update 5 환경 변수 명령 프롬프트 창을 엽니다. 아래 스크립트를 실행하여 환경 변수 INCLUDE , LIB , 그리고 PATH 를 설정합니다. @echo off set CPRO_PATH=C:\Program Files (x86)\IntelSWTools\compilers_and_libraries\windows set MKLROOT=%CPRO_PATH%\mkl set REDIST=%CPRO_PATH%\redist set INCLUDE=%MKLROOT%\include;%INCLUDE% set LIB=%MKLROOT%\lib\intel64;%LIB% set PATH=%REDIST%\intel64\mkl;%PATH% REM for OpenMP intel thread set LIB=%CPRO_PATH%\compiler\lib...

Llama 3.2로 문장 생성 및 챗팅 완성 실습

Llama 3.2로 문장 생성 및 챗팅 완성 실습 Running Meta Llama on Linux 문서의 내용을 참고하여 Llama 3.2 1B 모델로 다음 두 가지 기능을 실습합니다. 문장 완성 챗팅 완성 실습 환경 Ubuntu 20.04.6 LTS Python 3.12.7 Llama3.2-1B, Llama3.2-1B-Instruct rustc 1.83.0 NVIDIA RTX 4090 24GB 프로그램 준비 실습에서 사용할 wget , md5sum 설치 sudo apt-get install wget sudo apt-get install md5sum NVIDIA GPU 설치 여부 확인 nvidia-smi 실습 디렉토리 만들기 mkdir llama3-demo cd llama3-demo git clone https://github.com/meta-llama/llama3.git Python 3.10 이상의 버전으로 가상환경 만들고 활성화 python -m venv llama-venv . llama-venv/bin/activate Rust 컴파일러 설치 How To Install Rust on Ubuntu 20.04 문서를 참고하여 Rust 컴파일러를 설치합니다. curl --proto '=https' --tlsv1.3 https://sh.rustup.rs -sSf | sh 위 명령을 실행하면 아래와 같이 세 가지 선택 옵션이 나타나는데 그냥 엔터를 쳐서 1번 옵션으로 진행합니다. ... 1) Proceed with installation (default) 2) Customize installation 3) Cancel installation 아래 명령을 실행하여 현재 쉘에 반영하고 설치된 컴파일러 버전을 확인합니다. source $HOME/.cargo/env rustc --version 의존 라이브러리 설치 pip install ...