import joblib
joblib.dump(regressor, 'regressor.pkl')
joblib.dump(scaler_X, 'scaler_X.pkl')
joblib.dump(scaler_y, 'scaler_y.pkl')

joblib을 통해 인공지능 모델 regressor와 x의 스케일러 scaler_X y의 스케일러 scaler_y를 pickle로 저장한다.

regressor = joblib.load('data/regressor.pkl')
scaler_X = joblib.load('data/scaler_X.pkl')
scaler_y = joblib.load('data/scaler_y.pkl')

그후 streamlit이 작동되는 환경에서 폴더에 pickle파일들을 넣고 load한다. 이제 scaler_X로 새로운 데이터 전처리를 한후 regressor모델에 대입하고 scaler_y.inverse_transform함수로 예측값을 뽑아낸다.

1. 주피터 노트북에서 탐색적 데이터 분석을 마친다.

2. 코랩같은 클라우드 환경에서 인공지능 모델링과 학습을 해준다.

3. 인공지능 모델을 pickle로 다운로드 받아서 로컬환경에서 streamlit 라이브러리로 ui와 함께 Data Dashboard App을 만든다.

4. 로컬에서 잘 작동하는지 확인 했다면, aws ec2에 업로드 한다.

먼저 메인 파이썬 파일을 만들어 준다.

## 파일을 분리해서 만드는 앱 ###

import streamlit as st
from app9_about import run_about
from app9_eda import run_eda

from app9_home import run_home
from app9_ml import run_ml

def main():
    st.title('파일 분리 앱')

    menu = ['Home', 'EDA', 'ML', 'About']

    choice = st.sidebar.selectbox('메뉴', menu)

    if choice == menu[0]:
        run_home()
    elif choice == menu[1]:
        run_eda()
    elif choice == menu[2]:
        run_ml()
    elif choice == menu[3]:
        run_about()

if __name__ == '__main__':
    main()

그리고 from 모듈 import 함수로 다른 파일에 있는 함수를 불러온다.

아래는 app9_home파일이다.

import streamlit as st
from PIL import Image

def run_home():
    st.subheader('홈 화면입니다.')

    st.text('파일 분리 앱 실습하는 중')

    img = Image.open('data2/image_03.jpg')

    st.image(img)

 

import streamlit as st
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

def main():
    st.title('차트 그리기 1')

    df = pd.read_csv('data2/iris.csv')

    st.dataframe(df)

    # 차트 그리기
    # sepal_length 와 sepal_width 의 관계를
    # 차트로 나타내시오.

    fig = plt.figure()
    plt.scatter(data = df, x = 'sepal_length', y = 'sepal_width')
    plt.title('Sepal Length vs Width')
    plt.xlabel('Sepal Length')
    plt.ylabel('Sepal Width')
    st.pyplot(fig)

    fig2 = plt.figure()
    sns.scatterplot(data = df, x = 'sepal_length', y = 'sepal_width')
    plt.title('Sepal Length vs Width')
    st.pyplot(fig2)

    fig3 = plt.figure()
    sns.regplot(data = df, x = 'sepal_length', y = 'sepal_width')
    st.pyplot(fig3)

    # sepal_length 로 히스토그램을 그린다.
    # bin 의 갯수는 20개로.

    fig4 = plt.figure()
    plt.hist(data = df, x = 'sepal_length', bins = 20, rwidth = 0.8)
    st.pyplot(fig4)

    # sepal_length 히스토그램을 그리되,
    # bin 의 갯수를 10개와 20개로 
    # 두개의 차트를 수평으로 보여주기

    fig5 = plt.figure(figsize = (10,4))
    plt.subplot(1, 2, 1)
    plt.hist(data = df, x = 'sepal_length', bins = 10, rwidth = 0.8)

    plt.subplot(1, 2, 2)
    plt.hist(data = df, x = 'sepal_length', bins = 20, rwidth = 0.8)

    st.pyplot(fig5)

    # species 컬럼의 데이터를 각각 몇개씩 있는지
    # 차트로 나타내시오.

    fig6 = plt.figure()
    sns.countplot(data = df, x = 'species')
    st.pyplot(fig6)

    #### 지금까지 한건, plt와 seanborn 차트를
    # streamlit에 그리는 방법했다.

    #### 데이터프레임이 제공하는 차트함수도
    # streamlit에 그릴 수 있다.

    # species 는 각각 몇개인지, 데이터프레임의
    # 차트로 그리는 방법
    
    fig7 = plt.figure()
    df['species'].value_counts().plot(kind = 'bar')
    st.pyplot(fig7)

    # sepal_length 컬럼을 히스토그램으로!
    fig8 = plt.figure()
    df['sepal_length'].hist(bins = 40)
    st.pyplot(fig8)

if __name__ == '__main__':
    main()
import streamlit as st
import pandas as pd

import altair as alt
import plotly.express as px

def main():
    # 스트림릿에서 제공해주는 차트
    # line_chart, area_chart
    
    df1 = pd.read_csv('data2/lang_data.csv')
    st.dataframe(df1)

    lang_list = df1.columns[1:]

    choice_list = st.multiselect('언어를 선택해주세요.', lang_list)

    if len(choice_list) != 0:
        df_choice = df1[choice_list]

        st.dataframe(df_choice)

        # 스트림릿이 제공하는 line_chart
        st.line_chart(df_choice)

        # 스트림릿이 제공하는 area_chart
        st.area_chart(df_choice)

    df2 = pd.read_csv('data2/iris.csv')

    # 스트림릿이 제공하는 bar_chart
    st.bar_chart(df2.iloc[:, 0: -2 + 1])

    ## 웹에서 사용할 수 있는 차트 라이브러리 중
    ## Altair 차트

    alt_chart = alt.Chart(df2).mark_circle().encode(x = 'petal_length', y = 'petal_width', color = 'species')
    st.altair_chart(alt_chart)

    ## 스트림릿의 map 차트
    df3 = pd.read_csv('data2/location.csv', index_col = 0)
    st.dataframe(df3)

    st.map(df3)

    # plotly 라이브러리를 이용한 차트 그리기.

    df4 = pd.read_csv('data2/prog_languages_data.csv', index_col = 0)
    st.dataframe(df4)

    # plotly 의 pie 차트
    fig1 = px.pie(df4, names = 'lang', values = 'Sum', title = '각 언어별 파이차트') 
    st.plotly_chart(fig1)

    # plotly 의 bar 차트

    df4_sorted = df4.sort_values('Sum', ascending = False)

    fig2 = px.bar(df4_sorted, x = 'lang', y = 'Sum')
 
    st.plotly_chart(fig2)
  
if __name__ == '__main__':
    main()
###### 파일을 업로드 하는 방법 #########
###### 이미지 파일, CSV 파일 업로드

import streamlit as st
from PIL import Image
import pandas as pd
import os
from datetime import datetime

# 디렉토리 정보와 파일을 알려주면, 해당 디렉토리에
# 파일을 저장하는 함수
def save_uploaded_file(directory, file) :
    # 1.디렉토리가 있는지 확인하여, 없으면 디렉토리부터만든다.
    if not os.path.exists(directory) :
        os.makedirs(directory)
    # 2. 디렉토리가 있으니, 파일을 저장.
    with open(os.path.join(directory, file.name), 'wb') as f :
        f.write(file.getbuffer())
    return st.success("Saved file : {} in {}".format(file.name, directory))

def main():
    
    # 사이드바 만들기 
    st.title('파일 업로드 프로젝트')

    menu = ['Image', 'CSV', 'About']
    choice = st.sidebar.selectbox('메뉴', menu)

    if choice == menu[0] :
        st.subheader('이미지 파일 업로드')
        upload_file = st.file_uploader('이미지 파일 선택', type=['jpg','png','jpeg'])
        if upload_file is not None :
            print(upload_file.name)
            print(upload_file.size)
            print(upload_file.type)

            # 파일명을 유니크하게 만들어서 저장해야 한다.
            # 현재시간을 활용해서, 파일명을 만든다. 
            current_time = datetime.now()
            print(current_time.isoformat().replace(':', '_'))
            
            new_filename = current_time.isoformat().replace(':', '_') + '.jpg'

            upload_file.name = new_filename
            save_uploaded_file('temp', upload_file)


    elif choice == menu[1] :
        st.subheader('CSV 파일 업로드')

        upload_file = st.file_uploader('CSV 파일 선택', type = ['csv'])

        if upload_file is not None:

            # 파일명을 유니크하게 만들어서 저장해야 한다.
            # 현재시간을 활용해서, 파일명을 만든다. 
            current_time = datetime.now()
            print(current_time.isoformat().replace(':', '_'))
            
            new_filename = current_time.isoformat().replace(':', '_') + '.csv'

            upload_file.name = new_filename
            save_uploaded_file('temp', upload_file)

    else :
        st.subheader('파일 업로드 프로젝트 입니다.')



if __name__=='__main__' :
    main()
from email import message
import streamlit as st 

def main():

    # 유저한테 입력을 받는 방법 

    # 1. 이름 입력 받기
    name = st.text_input('이름을 입력하세요!')
    if name != '' :
        st.subheader(name + '님 안녕하세요??')

    # 2. 입력 글자 갯수 제한 
    address = st.text_input('주소를 입력하세요', max_chars=10)
    st.subheader(address)

    # 3. 여러 행을 입력가능토록
    message = st.text_area('메세지를 입력하세요', height=3)
    st.subheader(message)

    # 4. 숫자 입력 , 정수
    st.number_input('숫자 입력', 1, 100)

    # 5. 숫자 입력 , 실수
    st.number_input('실수 입력', 1.0, 100.0)

    # 6. 날짜 입력 
    my_date = st.date_input('약속날짜')
    st.write(my_date)

    # 요일 찍기
    st.write( my_date.weekday() )
    st.write( my_date.strftime('%A'))

    # 7. 시간 입력
    my_time = st.time_input('시간 선택')
    st.write(my_time)

    # 8. 색깔 입력
    color = st.color_picker('색을 선택하세요')
    st.write(color)

    # 9. 비밀번호 입력
    password = st.text_input('비밀번호 입력', type='password')
    st.write(password)

if __name__ == '__main__':
    print(__name__)
    main()

'streamlit' 카테고리의 다른 글

streamlit에서 Chart 사용법  (0) 2022.05.20
streamlit 사이드 바와 파일 업로드  (0) 2022.05.20
streamlit 이미지, 동영상 처리  (0) 2022.05.20
streamlit 버튼, 박스  (0) 2022.05.20
streamlit 데이터 프레임  (0) 2022.05.20
import streamlit as st
import pandas as pd

# 이미지 처리를 위한 라이브러리
from PIL import Image

def main():
    # 1. 저장되어있는, 이미지 파일을, 화면에 표시하기
    img = Image.open('data2/image_03.jpg')

    st.image(img)

    st.image(img, use_column_width=True)

    # 2. 인터넷상에 있는 이미지를 화면에 표시하기.
    #    URL이 있는 이미지를 말한다.
    url = 'https://dimg.donga.com/wps/NEWS/IMAGE/2019/07/01/96260737.1.jpg'
    
    st.image(url)

    video_file = open('data2/secret_of_success.mp4', 'rb')
    st.video(video_file)

    audio_file = open('data2/song.mp3', 'rb')
    st.audio( audio_file.read() , format='audio/mp3' )


if __name__ == '__main__' :
    main()

 

'streamlit' 카테고리의 다른 글

streamlit 사이드 바와 파일 업로드  (0) 2022.05.20
streamlit 유저한테 입력을 받는 방법  (0) 2022.05.20
streamlit 버튼, 박스  (0) 2022.05.20
streamlit 데이터 프레임  (0) 2022.05.20
streamlit 제목, 문구  (0) 2022.05.20
import streamlit as st
import pandas as pd

def main():
    df = pd.read_csv('data2/iris.csv')

    # 버튼 만들기
    # if st.button('데이터 보기'):
    #     st.dataframe(df)

    # "대문자" 버튼을 만들고,
    # 버튼을 누르면, species컬럼의 값들을 대문자로 변경한
    # 데이터 프레임을 보여주세요.

    if st.button('대문자'):
        df['species'] = df['species'].str.upper()
        st.dataframe(df)

    # 라디오버튼 : 여러개중에 한개 선택할때
    my_order = ['오름차순 정렬', '내림차순 정렬']

    status = st.radio('정렬방법 선택', my_order)

    if status == my_order[0]:
        # petal_lengeth 컬럼을 오름차순으로 정렬해서 화면에 보여준다.
        # df.sort_values('petal_length')
        st.dataframe(df.sort_values('petal_length'))
    elif status == my_order[1]:
        # df.sort_values('petal_length', ascending = False)
        st.dataframe(df.sort_values('petal_length', ascending = False))

    status = st.radio('정렬방법 선택2', my_order)

    if status == my_order[0]:
        # petal_lengeth 컬럼을 오름차순으로 정렬해서 화면에 보여준다.
        df = df.sort_values('petal_length')
        st.dataframe(df)
    elif status == my_order[1]:
        df = df.sort_values('petal_length', ascending = False)
        st.dataframe(df)

    # 체크박스 : 체크 해제/체크
    if st.checkbox('헤드 5개 보기'):
        st.dataframe(df.head())
    else:
        st.text('헤드 숨겼습니다.')

    # 셀렉트 박스 : 여러개에서 한개만 고르는 UI
    language = ['Python', 'C', 'Java', 'Go', 'PHP']
    my_choice = st.selectbox('좋아하는 언어 선택', language)

    if my_choice == language[0]:
        st.write('파이썬을 선택했습니다.')
    elif my_choice == language[1]:
        st.write('C언어가 좋아요')
    elif my_choice == language[2]:
        st.write('자바 선택')

    # 멀티셀렉트 : 여러개 중에서, 여러개 선택하는 UI
    st.multiselect('여러개 선택가능', language)

    # 멀티셀렉트를 이용해서, 특정 컬럼들만 가져오기.
    # 유저에게, iris df의 컬럼들을 다 보여주고,
    # 유저가 선택한 컬럼들만 데이터 프레임을 화면에 보여줄 것!

    column_list = df.columns
    choice_list = st.multiselect('컬럼을 선택하세요', column_list)

    st.dataframe(df[choice_list])

    # 슬라이더 : 숫자 조정하는데 주로 사용
    # st.slider('나이', 1.0, 120.0, 30.0, 0.1)
    age = st.slider('나이', 1, 120, 30)

    st.text('제가 선택한 나이는 {}입니다'.format(age))

    # 익스펜더
    with st.expander('Hello'):
        st.text('안녕하세요')
        st.dataframe(df)



if __name__ == '__main__':
    main()

'streamlit' 카테고리의 다른 글

streamlit 유저한테 입력을 받는 방법  (0) 2022.05.20
streamlit 이미지, 동영상 처리  (0) 2022.05.20
streamlit 데이터 프레임  (0) 2022.05.20
streamlit 제목, 문구  (0) 2022.05.20
streamlit visual studio 셋팅 방법  (0) 2022.05.20
import streamlit as st
import pandas as pd

def main():
    df = pd.read_csv('data2/iris.csv')

    st.dataframe(df)

    species = df['species'].unique()

    st.text('아이리스 꽃은 ' + species + '으로 되어있다.')

    st.dataframe(df.head())
    st.write(df.head())

if __name__ == '__main__':
    main()

'streamlit' 카테고리의 다른 글

streamlit 이미지, 동영상 처리  (0) 2022.05.20
streamlit 버튼, 박스  (0) 2022.05.20
streamlit 제목, 문구  (0) 2022.05.20
streamlit visual studio 셋팅 방법  (0) 2022.05.20
streamlit 설치 방법  (0) 2022.05.20
import streamlit as st

def main():
    st.title('웹 대시보드')
    st.text('웹 대시보드 개발하기')

    name = '홍길동'

    # 제 이름은 홍길동 입니다.
    print('제 이름은 {}입니다.'.format(name))

    st.text('제 이름은 {}입니다.'.format(name))

    st.header('이 영역은 헤더 영역')

    st.subheader('이 영역은 subheader영역')

    st.success('작업이 성공했을때 사용하자')
    st.warning('경고 문구를 보여주고 싶을 때 사용하자.')
    st.info('정보를 보여주고 싶을 때')
    st.error('문제가 발생했을 때 사용')

    # 파이썬의 함수 사용법을 보여주고 싶을 때
    st.help(sum)
    st.help(len)

if __name__ == '__main__':
    main()

'streamlit' 카테고리의 다른 글

streamlit 이미지, 동영상 처리  (0) 2022.05.20
streamlit 버튼, 박스  (0) 2022.05.20
streamlit 데이터 프레임  (0) 2022.05.20
streamlit visual studio 셋팅 방법  (0) 2022.05.20
streamlit 설치 방법  (0) 2022.05.20

+ Recent posts