갈루아의 반서재

 

커스텀 ML 툴을 만들어주는 가장 빠른 방법 중 하나인 Streamlit 앱에 대해서 알아보자.

먼저 전통적인 ML 엔지니어의 작업 플로우와 Streamlit 을 이용한 플로우를 비교해보자. 아래는 기존의 앱 빌딩 플로우이다. 

위의 방법도 물론 훌륭하다. 하지만 새로운 기능이 필요하다면, 그리고 툴 팀이 10개 이상의 서로 다른 프로젝트를 서포팅하고 있어 업데이트에 약 2달 정도 소요될 것입니다라고 말하는 바람에, 다시 주피터 노트북을 통해 실행한 다음, 이 내용을 파이썬 스크립트로 옮긴다. HTTP request, HTML, callback 등의 요소를 고려해가면서 Flask 앱 등을 작성한다. 구동해보고 부족한 기능이 있으면 다시 위의 과정을 반복한다고 생각해보자. 이러한 부분에서 어떻게 파이썬 스크립트를 작성하는 것처럼 손쉽게 ML 툴을 만들 수 없을까하는 의문에서 Streamlit 이 탄생했다. Streamlit 의 목표는 ML 엔지니어들이 Tools team의 필요없이 앱을 만들 수 있도록 하는 것이다. Streamlit 의 개발플로우는 다음과 같다.

 

Streamlit 의 특징은 다음과 같다.

#1: Embrace Python scripting 

파이썬 스크립트만 작성할 수 있다면, Streamlit 앱을 만들 수 있다. 예를 들면 다음과 같다. 

import streamlit as st
st.write('Hello, world!')

이에 앞서 해당 라이브러리부터 설치한다. 

(AnnaM) founder@hilbert:~$ pip install streamlit
Successfully built future tornado enum-compat watchdog blinker validators toolz pathtools
Successfully installed altair-3.2.0 argh-0.26.2 base58-1.0.3 blinker-1.4 boto3-1.9.247 botocore-1.12.247 click-7.0 docutils-0.15.2 enum-compat-0.0.2 future-0.18.0 jmespath-0.9.4 pathtools-0.1.2 s3transfer-0.2.1 streamlit-0.47.4 toml-0.10.0 toolz-0.10.0 tornado-5.1.1 tzlocal-2.0.0 validators-0.14.0 watchdog-0.9.0

hello world 앱을 실행해보자. 다음과 같이 입력한다. GCP 사용자의 경우 8501 포트 사용이 가능하도록 방화벽 정책부터 추가한다.

(AnnaM) founder@hilbert:~$ streamlit hello

  👋 Welcome to Streamlit!

  If you are one of our development partners or are interested in
  getting personal technical support, please enter your email address
  below. Otherwise, you may leave the field blank.

  Email:

  Telemetry: As an open source project, we collect usage statistics.
  We cannot see and do not store information contained in Streamlit apps.

  If you would like to opt out, add the following to ~/.streamlit/config.toml,
  creating that file if necessary:

    [browser]
    gatherUsageStats = false

Starting new HTTPS connection (1): pypi.org
Starting new HTTP connection (1): checkip.amazonaws.com

  You can now view your Streamlit app in your browser.

  Network URL: http://10.140.0.2:8501
  External URL: http://**.***.***.**:8501


실행된 모습이다.

주피터 노트북으로 작성한 앞선 코드를 실행해보자. 다음과 같은 형식으로 실행할 수 있다. 

(AnnaM) founder@hilbert:~/annam$ streamlit run Streamlit.ipynb
Starting new HTTP connection (1): checkip.amazonaws.com

  You can now view your Streamlit app in your browser.

  Network URL: http://10.140.0.2:8501
  External URL: http://**.***.***.**:8501

이 경우 다음과 같은 에러를 반환한다.

NameError: name 'null' is not defined

File "/home/founder/anaconda3/envs/AnnaM/lib/python3.7/site-packages/streamlit/ScriptRunner.py", line 306, in _run_script exec(code, module.__dict__)

File "/home/founder/annam/Streamlit.ipynb", line 15, in <module> "execution_count": null,\

그럼 이번에는 확장자를 py 로 바꿔서 실행해보자.

(AnnaM) founder@hilbert:~/annam$ streamlit run Streamlit.py
Starting new HTTP connection (1): checkip.amazonaws.com

  You can now view your Streamlit app in your browser.

  Network URL: http://10.140.0.2:8501
  External URL: http://**.***.***.**:8501

다음과 같이 정리할 수 있다.

(AnnaM) founder@hilbert:~/annam$ streamlit
Usage: streamlit [OPTIONS] COMMAND [ARGS]...

  Try out a demo with:

      $ streamlit hello

  Or use the line below to run your own script:

      $ streamlit run your_script.py

Options:
  --log_level [error|warning|info|debug]
  --version                       Show the version and exit.
  --help                          Show this message and exit.

Commands:
  activate  Activate Streamlit by entering your email.
  cache     Manage the Streamlit cache.
  config    Manage Streamlit's config settings.
  docs      Show help in browser.
  hello     Runs the Hello World script.
  help      Print this help message.
  run       Run a Python script, piping stderr to Streamlit.
  version   Print Streamlit's version number.

 

#2: Treat widgets as variables 

Streamlit 에는 콜백이 없다.

import streamlit as st 
x = st.slider('x') 
st.write(x, 'squared is', x * x)

 

#3: Reuse data and computation

만약 수많은 데이터를 다운로드받고 복잡한 연산을 실행할려고 한다면? 키는 어떻게 안전하게 정보를 재사용하느냐에 달려있다. Streamlit 은 안전하고 손쉽게 정보를 재사용하기 위한 cache primitive 를 사용한다. 다음의 코드가 그러한 예인데, 아래 코드는 Udacity Self-driving car 프로젝트의 데이터를 한 번만 다운받지만, 심플하고 빠른 성능을 보여준다. 

import streamlit as st
import pandas as pd

# Reuse this data across runs!
read_and_cache_csv = st.cache(pd.read_csv)

BUCKET = "https://streamlit-self-driving.s3-us-west-2.amazonaws.com/"
data = read_and_cache_csv(BUCKET + "labels.csv.gz", nrows=1000)
desired_label = st.selectbox('Filter to:', ['car', 'truck'])
st.write(data[data.label == desired_label])

 

Using st.cache to persist data across Streamlit runs. To run this code, please follow these instructions.

Streamlit 은 다음과 같이 작동하는 셈이다.

 

 

Streamlit Demo: The Udacity Self-driving Car Image Browser

상기 프로젝트는 Udacity self-driving-car 데이터셋 YOLO object detection 을 하나의 Streamlit 앱으로 통합시켰다. 이 데모는 불과 300라인 미만의 코드로 이루어져있다. 이 Streamlit 데모는 전체 Udacity 자율주행차 사진 데이터셋에 대해 시맨틱 검색을 수행하여, 사람이 주석을 단 실측자료 라벨을 시각화하고, 동시에 실시간으로 complete neural net (YOLO)을 구동하게 한다.

구동방법은 다음과 같다. 먼저 라이브러리를 설치한다.

(AnnaM) founder@hilbert:~/annam$ pip install --upgrade streamlit opencv-python
Requirement already up-to-date: streamlit in /home/founder/anaconda3/envs/AnnaM/lib/python3.7/site-packages (0.47.4)
Installing collected packages: opencv-python
Successfully installed opencv-python-4.1.1.26

Streamlit 앱을 실행한다.

(AnnaM) founder@hilbert:~/annam$ streamlit run https://raw.githubusercontent.com/streamlit/demo-self-driving/master/app.py
Starting new HTTPS connection (1): raw.githubusercontent.com
Starting new HTTP connection (1): checkip.amazonaws.com

  You can now view your Streamlit app in your browser.

  Network URL: http://10.140.0.2:8501
  External URL: http://**.***.**.**:8501

다음은 실행한 화면이다. 

전체 코드는 여기서 확인가능하다. 해당 코드에는 23개의 Streamlit 콜이 포함되어 있다. 

 

원문소스 https://towardsdatascience.com/coding-ml-tools-like-you-code-ml-models-ddba3357eace

 

Turn Python Scripts into Beautiful ML Tools

Introducing Streamlit, an app framework built for ML engineers

towardsdatascience.com