Streamlit Matplotlib 한글폰트 적용 예제

Streamlit Matplotlib-Seaborn 한글폰트 적용

개요

  • 배포 시, matplotlib & seaborn 한글 폰트 적용 하는 방법에 대해 알아본다.
  • 나눔고딕 폰트를 적용해본다.

폰트 다운로드

Untitled

개발환경 세팅

  • git clone 명령어를 활용하여 프로젝트 repo를 다운로드 받는다.

Untitled

  • 가상환경을 설정한다.
    • virtualenv venv 실행한다.
    • source venv/Scripts/activate 실행하여 가상환경에 접속한다.
$ virtualenv venv
created virtual environment CPython3.9.13.final.0-64 in 606ms
  creator CPython3Windows(dest=C:\Users\YONSAI\Desktop\streamlit-korean-fonts\venv, clear=False, no_vcs_ignore=False, global=False)
  seeder FromAppData(download=False, pip=bundle, setuptools=bundle, wheel=bundle, via=copy, app_data_dir=C:\Users\YONSAI\AppData\Local\pypa\virtualenv)
    added seed packages: pip==23.1.2, setuptools==67.6.1, wheel==0.40.0
  activators BashActivator,BatchActivator,FishActivator,NushellActivator,PowerShellActivator,PythonActivator
$ source venv/Scripts/activate
(venv)
$ 
  • requirements.txt 파일에 다음 라이브러리만 설치한다.
streamlit
matplotlib
seaborn
pandas
numpy

폰트 폴더 설정

  • customFonts 폴더를 만들고 다운로드 받은 폴더를 추가한다.

Untitled

SPSS 반복측정 분산분석

반복측정 분산분석

  • comercial_ratings.csv 데이터 불러오기

Untitled

데이터탐색

  • 분석 - 기술통계량 - 데이터탐색
  • 아래와 같이 4개의 설문조사 데이터는 종속변수로 넣는다.
  • 확인 버튼을 누른다.

Untitled

Untitled

  • 데이터가 40개가 넘으므로 정규성 검토를 할 필요가 없음

만약에 정규성 분포를 한다고 하면 어떻게 할까?

  • 일반선형모형 - 반복측정’

Untitled

  • 여기에서 수준의 수를 정의하는 것이 1차 핵심이다.
    • 총 광고의 종류는 4개이므로 요인의 수는 4가 된다.
  • 요인의 이름은 문맥에 맞게 저장한다
  • 측정 이름도 결과에 맞게 저장한다.
    • 예) 매력도, 평가 등

Untitled

SPSS - 케이스 선택

공지

  • 본 내용은 아래 교재를 참조하여 작성하였다. SPSS를 활용하여 논문을 쓰셔야 하는 분은 좋은 책이니 반드시 살 것을 권한다.

PREVIEW

  • 케이스 선택은 주로 연구 대상만 남겨두고 나머지 케이스는 필터링하거나 삭제할 때 사용
  • 케이스 선택 방법 : 데이터 - 케이스 선택

케이스

  • 케이스 선택은 특정 케이스를 필터링(삭제하지 않고 분석 시 제외하는 것)하거나 삭제하고자 할 때 사용함
    • 예시 : 연구 대상자가 남자라면 성별이 여자인 케이스는 필터링하거나 삭제해야 함

케이스 선택 방법

  • SPSS 상단 메뉴의 데이터-케이스 선택에서 진행함
  • 연구 대상자가 남자일 때 어떻게 진행하는지 살펴본다.

SPSS에서 케이스 선택하기

  • 연구 대상자가 남자인 경우
  • 연구 대상자가 남자이므로 성별이라는 변수의 값을 클릭해 설정
    • 1 = 남자, 2 = 여자로 설정

Untitled

R 4.2.3 설치 - Windows

R 프로그램 설치

Untitled

  • 0-Cloud 선택

Untitled

  • 각 OS에 맞는 버전 설치, 여기서는 Windows 선택

Untitled

  • Windows의 경우 아래와 같이 나타난다.

Untitled

  • Download R-4.2.3 for Windows 설치

Untitled

  • 다운로드 받은 설치 파일을 관리자 권한으로 실행한다.

Untitled

  • 언어는 한국어로 해도 상관없지만, 필자는 주로 영어로 선택해서 했기 때문에, 영어로 진행하도록 한다.

Untitled

  • 특별하게 주의 깊게 살펴서 해야 할 항목은 없기 때문에, Next 버튼을 순차적으로 클릭한다.

Untitled

Untitled

Google Clound & WSL2 Ubuntu 20.04 개발환경 설정

개요

  • GCP에서 개발환경을 설정하도록 한다.
  • Local PC에서 GCP로 접속을 하도록 한다.

사전준비

  • WSL2 Ubuntu 설치 과정은 여기에서 다루지 않는다.

Untitled

개발환경 설치

  • Python3 설치한다. (본인에게 맞는 언어를 선택한다)
sudo apt update
sudo apt install -y python3 python3-pip
python3

최신 버전(417.0.1) gcloud CLI 설치

$ sudo apt-get install apt-transport-https ca-certificates gnupg
  • 패키지 소스로 gcloud CLI 배포 URI를 추가합니다. 배포판에서 서명 옵션을 지원하는 경우 다음 명령어를 실행합니다.
$ echo "deb [signed-by=/usr/share/keyrings/cloud.google.gpg] https://packages.cloud.google.com/apt cloud-sdk main" | sudo tee -a /etc/apt/sources.list.d/google-cloud-sdk.list
  • Google Cloud 공개 키를 가져옵니다. 배포판의 apt-key 명령어가 --keyring 인수를 지원하는 경우 다음 명령어를 실행합니다.
$ curl https://packages.cloud.google.com/apt/doc/apt-key.gpg | sudo apt-key --keyring /usr/share/keyrings/cloud.google.gpg add -
  • gcloud CLI를 업데이트하고 설치합니다.
$ sudo apt-get update && sudo apt-get install google-cloud-cli

Shell 재시작 후 설치 확인

  • 다음 명령어를 통해 설치가 정상적으로 되었는지 확인한다.
$ exec -l $SHELL
$ gcloud version
Google Cloud SDK 419.0.0
alpha 2023.02.17
beta 2023.02.17
bq 2.0.85
bundled-python3-unix 3.9.16
core 2023.02.17
gcloud-crc32c 1.0.0
gsutil 5.20

시작하기

  • 시작하려면 [gcloud init](https://cloud.google.com/sdk/gcloud/reference/init?hl=ko)을 실행합니다.
$ gcloud init
Welcome! This command will take you through the configuration of gcloud.

Your current configuration has been set to: [default]

You can skip diagnostics next time by using the following flag:
  gcloud init --skip-diagnostics

Network diagnostic detects and fixes local network connection issues.
Checking network connection...done.                                                                      
Reachability Check passed.
Network diagnostic passed (1/1 checks passed).

You must log in to continue. Would you like to log in (Y/n)?  Y

Go to the following link in your browser:

    https://accounts.google.com/o/oauth2/auth?response_type=...

Enter authorization code: your_code
You are logged in as: [your_email@gmail.com].

Pick cloud project to use: 
 [1] Enter a project ID
 ...
 [2] Create a new project
Please enter numeric choice or text value (must exactly match list item):  

Your current project has been set to: [your_project_name].

...

Some things to try next:

* Run `gcloud --help` to see the Cloud Platform services you can interact with. And run `gcloud help COMMAND` to get help on any gcloud command.
* Run `gcloud topic --help` to learn about advanced features of the SDK like arg files and output formatting
* Run `gcloud cheat-sheet` to see a roster of go-to `gcloud` commands.

WM 설정

  • 아래 화면에서 VM을 선택한다.

Untitled

Matplotlib 한글폰트 적용 예제 - Windows 10

강의소개

개요

  • 한글폰트를 다운로드 받아서 matplotlib에 적용하는 코드를 작성해본다.
  • 주요 코드를 기억해서 업무에 활용해보도록 한다.

폰트 다운로드

Untitled

  • 스크롤을 내리면 TTF 다운로드 버튼을 클릭한다.

Untitled

폰트 설치

  • 다운로드 받은 폰트를 압축을 푼다.

Untitled

가계금융복지조사 데이터 수집

개요

  • 통계청(https://mdis.kostat.go.kr/) 에서는 마이크로데이터를 제공하고 있음
  • 해당 사이트에서 회원가입은 필수로 진행해야 한다.

MDIS 다운로드 서비스 이용

  • 2022년 기준 가계금융복지조사 데이터를 다운로드 받는다.
  • 다운로드 서비스/소득소비자산/가계금융복지조사/가구마스터(제공)/2022년도를 아래와 같이 순차적으로 클릭한다.

Untitled

Untitled

Untitled

  • 다운로드받을 데이터의 형태와 해당 데이터를 입수할 때 필요한 ‘통계 툴 읽기 스크립트’를 선택한다.
  • Python 스크립트는 제공하지 않아서, R로 선택을 한다.

Untitled

Untitled

Untitled

  • 위 그림에서 마이페이지를 클릭한다.

Untitled

Untitled

Docker Streamlit Sample

개요

  • 도커를 활용하여 Streamlit 배포를 진행해본다.
  • Dockerfile의 의미에 대해 이해한다.

Dockerfile

  • Docker 이미지를 빌드하기 위한 일련의 명령어를 포함하는 텍스트 파일
  • 컨테이너에서 애플리케이션이 실행될 때 필요한 환경과 종속성을 정의하는 방법을 제공
  • 패키지 설치, 파일 복사 및 환경 변수 설정 등의 지시어가 포함

사전준비

소스코드 예제

  • 소스코드는 크게 아래와 같이 작성했다.
  • 먼저 app.py는 아래와 같다.
import numpy as np 
import pandas as pd 
import matplotlib 
import sklearn 
import scipy
import plotly
import streamlit as st

def main():
    st.write(np.__version__)
    st.write(pd.__version__)
    st.write(matplotlib.__version__)
    st.write(sklearn.__version__)
    st.write(scipy.__version__)
    st.write(plotly.__version__)

if __name__ == "__main__":
    main()
  • 그 다음은 requirements.txt 파일을 작성한다.
streamlit
numpy
scipy
pandas
matplotlib
plotly
scikit-learn
  • 작성된 코드가 잘 실행되는지 로컬호스트에서 확인을 한다.
$ streamlit run app.py 

  You can now view your Streamlit app in your browser.

  Local URL: http://localhost:8501
  Network URL: http://192.168.0.49:8501

Untitled

Docker 기본 문법

무작정 도커 시작하기

  • dockerUbuntu를 설치하고 실행해본다.
  • 현재 파일 목록들을 살펴본다.
  • 빠져 나올 때는 EXIT를 실행한다.
C:\Users\human>docker run -it ubuntu:18.04
Unable to find image 'ubuntu:18.04' locally
18.04: Pulling from library/ubuntu
72d9f18d70f3: Pull complete
Digest: sha256:a3765b4d74747b5e9bdd03205b3fbc4fa19a02781c185f97f24c8f4f84ed7bbf
Status: Downloaded newer image for ubuntu:18.04
root@7a7a49e2d83e:/# ls
bin  boot  dev  etc  home  lib  lib64  media  mnt  opt  proc  root  run  sbin  srv  sys  tmp  usr  var
root@7a7a49e2d83e:/#
  • 현재 도커 컨테이너 리스트를 확인한다.
$ docker ps -a
CONTAINER ID   IMAGE          COMMAND       CREATED        STATUS         PORTS     NAMES
7a7a49e2d83e   ubuntu:18.04   "/bin/bash"   18 hours ago   Up 5 minutes             practical_euler
  • STATUS가 Docker 컨테이너 재진입
docker exec -it 7a7a49e2d83e /bin/bash
  • 현재 운영중인 도커를 멈추고 싶다면 아래와 같이 작성한다.
docker stop 7a7a49e2d83e
  • 재활성화 하고 싶다면 아래와 같이 작업한다.
docker start 7a7a49e2d83e

컨테이너 이미지화

$ docker login -u your_id
Password:
Login Succeeded
Authenticating with existing credentials...
Login Succeeded

Logging in with your password grants your terminal complete access to your account.
For better security, log in with a limited-privilege personal access token. Learn more at https://docs.docker.com/go/access-tokens/
  • 기존 컨테이너 ID 7a7a49e2d83e를 이미지로 변환한다.
    • 새로운 Repository 이름은 mlearn 이라고 한다.
    • 태그 이름은 latest 라고 한다.
docker commit 7a7a49e2d83e your_id/mlearn:latest
  • 도커 이미지가 만들어졌는지 확인한다.
  • ubuntu 이미지를 다운받았기 때문에 size가 비슷한 것을 확인할 수 있다.
$ docker images
REPOSITORY        TAG       IMAGE ID       CREATED          SIZE
your_id/mlearn    latest    b26bdf7b071e   29 minutes ago   63.1MB
ubuntu            18.04     5d2df19066ac   2 weeks ago      63.1MB
hello-world       latest    feb5d9fea6a5   16 months ago    13.3kB
  • 도커 이미지를 push 하도록 한다.
docker push your_id/mlearn:latest

호스트 OS의 홈 폴더 마운트하기

  • 호스트 OS의 홈 폴더를 마운트 하기 위해서는 컨테이너 실행 시 -v 옵션을 지정한다.
    • : 기준으로 왼쪽은 로컬 PC, 오른쪽은 가상환경 내 경로임을 잊지 말자.
$ docker run -it -v C:\Users\human\Desktop\dockerhome:/home mlearn
  • home 폴더에서 temp 폴더를 생성하면 아래와 같이 폴더가 만들어지는 것을 확인한다.
root@5c950356cfc3:/# cd home/
root@5c950356cfc3:/home# mkdir temp

Untitled

Git 배치파일 Windows

개요

배치파일 생성하기

  • 프로젝트 폴더에 배치파일을 실행한다.
  • 파일명은 submit.bat 로 지정했다.
set root=C:\Users\human\Desktop\streamlit-predictions
call git add .
call git commit -m "updated from batch file"
call git push

배치파일 실행하기

  • 우선 해당 폴더에서 submit.bat 파일을 더블클릭한다.

Untitled

  • 더블 클릭하면 자동으로 배치파일이 실행되면서 해당 명령어들이 순차적으로 돌아가는 것을 확인할 수 있다.

Untitled