0.참고주소
1.
스트림릿 기본 사용법
•
https://wikidocs.net/230763
2.
스트림릿 플레이 그라운드
•
https://streamlit.io/playground?example=hello
3.
스트림릿 데모
•
https://github.com/streamlit/demo-self-driving
1.스트림릿이란?
[ 스트림릿 ]
1.
스트림릿(Streamlit)은 프런트엔드에 대한 지식 없이도 머신러닝 모델을 쉽고 빠르게 시연하고 배포할 수 있도록 돕는 오픈소스 프레임워크
- 웹 개발을 하려면 HTML 뿐만 아니라 CSS와 JavaScript를 어느 정도는 알아야 하는데
- 스트림릿 하나면 끝
Plain Text
복사
2.
장점: 파이썬 코드만으로 사용자와 상호작용하는 LLM 웹 애플리케션을 손쉽게 생성 가능
3.
어디다 써먹을 수 있을까?
•
데이터 애플리케이션을 만들고 공유하는 더 빠른 방법(A faster way to build and share data apps)
2.설치후 프레임워크 작동확인
•
설치가 성공했는지 확인하기 위해 데모 프로그램인 hello를 실행
•
터미널창에 아래 명령어를 넣어서 실행해보기
streamlit hello
Bash
복사
컴퓨터에서 첫 실행시 터미널로 이메일 입력요청하면 입력생략 가능
[ 콘솔에 출력되는 주소 ]
•
콘솔에 출력된 http://localhost:8502로 접속했을 때 아래와 같은 화면이 출력되면 성공적으로 설치 된 것임
[ 웹페이지 내용 ]
3.스트림릿 실행
1.
일반적으로 Streamlit 앱은 Jupyter 내에서 직접 실행되지않음
2.
따라서 .py파일과 같은 스크립트파일로 만든다음
streamlit run 파일명.py
으로 실행하면 됨
3.
주피터로 하는 것은 복잡하기만하고, 스트림릿 기능을 모두 쓸 수 없다는 아쉬움 존재
[중요] 스트림을 중지하고 싶을때
해당 터미널에서 Ctrl + C클릭
4.풍선 예제
[1_st.py 예제]
import streamlit as st
st.title("Hello Streamlit-er 👋")
st.markdown(
""" This is a playground for you to try Streamlit and have fun. **There's :rainbow[so much] you can build!** We prepared a few examples for you to get started. Just click on the buttons above and discover what you can do with Streamlit. """)
if st.button("Send balloons!"):
st.balloons()
Python
복사
5.차트 예제
import streamlit as st
text = "스트림릿 익숙해지기"st.header(text, divider='rainbow')
st.subheader(text)
st.title(text)
st.write(text)
st.write("# Bar Chart")
vocab_logits = {"나는": 0.01,"내일": 0.03,"오늘": 0.25,"어제": 0.3,
"산에": 0.4,"학교에": 0.5,"집에": 0.65,
"오른다": 1.2,"간다": 1.05,"왔다": 0.95}
st.bar_chart(vocab_logits)
st.caption(text)
Python
복사
6.멧플롯립과 연계하는 방법
import streamlit as st
import matplotlib.font_manager as fm
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
# 설치된 폰트# for font in fm.fontManager.ttflist: print(font.name) # 설치된 폰트 확인plt.rcParams['font.family'] = 'HYGraphic-Medium'# 인공신경망 마지막 레이어의 로짓값을 가정vocab_logits = {"나는": 0.01, "내일": 0.03, "오늘": 0.25, "어제": 0.3,
"산에": 0.4, "학교에": 0.5, "집에": 0.65,
"오른다": 1.2, "간다": 1.05, "왔다": 0.95}
# 로짓값을 temperature를 적용하여 확률값으로 변경하는 함수def softmax_with_temperature(values, temperature):
epsilon = 1e-2
temperature = max(temperature, epsilon) # 온도가 0이 되는 것을 방지 # Calculate the softmax with temperature exp_values = np.exp(np.array(values) / temperature)
sum_exp_values = np.sum(exp_values)
softmax_probs = exp_values / sum_exp_values
return softmax_probs.tolist()
# 바 그래프를 그리는 함수def draw_prob_graph(vocab, probs):
# Smaller figure size fig = plt.figure(figsize=(8, 4))
# Gradient from light to dark red colors = sns.color_palette("Reds", n_colors=len(vocab))
# Sort the vocabulary and probabilities sorted_vocab_prob = sorted(zip(vocab, probs), key=lambda x: x[1])
sorted_vocab, sorted_probs = zip(*sorted_vocab_prob)
# Convert numpy array to list for the palette palette_as_list = [colors[vocab.index(word)] for word in sorted_vocab]
# Using 'hue' with the same values as 'x' and setting legend to False sns.barplot(x=sorted_vocab, y=sorted_probs, hue=sorted_vocab, palette=palette_as_list, dodge=False)
plt.legend([],[], frameon=False)
st.pyplot(fig) # Use Streamlit to display the plot# Streamlit 슬라이더를 사용하여 temperature 값을 조정temperature = st.slider("Temperature 값 조정", min_value=0.01, max_value=100.0, value=1.0, step=0.01, key='temp_slider')
# 로짓에서 확률 분포로 변경vocab = list(vocab_logits.keys())
logits = list(vocab_logits.values())
probs = softmax_with_temperature(logits, temperature=temperature)
# Markdown을 통해 HTML 코드를 Streamlit에 표시draw_prob_graph(vocab, probs)
# HTML을 사용한 가운데 정렬centered_text = "<div style='text-align:center'> 로짓에서 확률분포로 변경된 상태</div>"st.markdown(centered_text, unsafe_allow_html=True)
Python
복사