Kamanda/Streamlit_Machine_Learning
0
1import streamlit as st2st.set_option('deprecation.showPyplotGlobalUse', False)3#st.markdown()4st.title("Document Title")5st.header("Article header")6st.subheader("Article subheader")7st.code("y = mx + c")8st.latex("\ int a y^2 \ , dy")9st.text("This is a chair!")10st.markdown('Staying hydrated is **_very_ cool**.')11 12students = ["Amelia Kami", "Antoinne Mark", "Peter Zen", "North Kim"]13 14marks = [82, 76, 96, 68]15 16import pandas as pd17 18df = pd.DataFrame()19 20df["Student Name"] = students21 22df["Marks"] = marks23#save to dataframe24df.to_csv("students.csv", index = False)25#display26st.dataframe(df)27 28#Static table29st.table(df)30 31#Metrics32st.metric("KPI", 56, 3)33#Json34st.json(df.to_dict())35 36#Code37#average of a list38code = '''def cal_average(numbers):39 sum_number = 040 for t in numbers:41 sum_number = sum_number + t 42 43 average = sum_number / len(numbers)44 return average'''45st.code(code, language='python')46#progress bar47 48import streamlit as st49import time50 51# Sample Progress bar52#bar_p = st.progress(0)53 54#for percentage_complete in range(100):55 #time.sleep(0.1)56 #bar_p.progress(percentage_complete + 1)57 58#with st.spinner('Please wait...'):59 #time.sleep(5)60#st.write('Complete!')61 62 63#Displaying an image using Streamlit64from PIL import Image65image = Image.open('media/ann-savchenko-H0h_89iFsWs-unsplash.jpg')66 67#st.image(image, caption='Sunset grass backgrounds')68 69#plotly70import plotly.express as px71# This dataframe has 244 rows, but 4 unique entries for the `day` variable72df = px.data.tips()73figx = px.pie(df, values='tip', names='day', title='Tips per day')74# Plot!75st.plotly_chart(figx, use_container_width=True)76 77#Altair78import altair as alt79import streamlit as st80import numpy as np81 82df = pd.DataFrame(83 np.random.randn(300, 4),84 columns=['a', 'b', 'c', 'd'])85 86chrt = alt.Chart(df).mark_circle().encode(87 x='a', y='b', size='c', color='c', tooltip=['a', 'b', 'c', 'd'])88 89st.altair_chart(chrt, use_container_width=True)90 91#Matplotlib92import matplotlib.pyplot as plt93import numpy as np94 95arr = np.random.normal(1, 1, size=1000)96fig, ax = plt.subplots()97ax.hist(arr, bins=30)98plt.grid()99st.pyplot(fig)100 101#Interactive widgets102st.button("Click here")103#st.download_button("Download audio", file)104selected = st.checkbox("Accept terms")105choice = st.radio("Select one", ["Apples", "Oranges"])106 107 108option = st.selectbox(109 'How would you like to receive your package?',110 ('By air', 'By sea', 'By rail'))111 112st.write('You selected:', option)113import datetime114day = st.date_input(115 "When is your birthday?",116 datetime.date(2022, 7, 6))117st.write('Your birthday is:', day)118 119color = st.color_picker('Choose A Color', '#00FFAA')120st.write('The selected color is', color)121 122 123@st.cache124def fetch_data():125 df = pd.read_csv("students.csv")126 return df127 128#data = fetch_data()129 130#Visualization131 132import matplotlib.pyplot as plt133import numpy as np134 135#Matplotlib136 137import matplotlib.pyplot as plt138import numpy as np139fig = plt.figure()140ax = fig.add_axes([0,0,1,1])141animals = ["Zebras", "Elephants", "Rhinos", "Leopards"]142number = [65, 72, 77, 59]143ax.bar(animals, number)144fig = plt.show()145st.pyplot(fig)146#Seaborn147import seaborn as sns148fig = plt.figure()149ax = sns.barplot(x = animals, y = number)150fig = plt.show()151st.pyplot(fig)152 153#Altair154#define data155df = pd.DataFrame()156 157df["Animals"] = animals158df["Number"] = number159#create chart160chrt = alt.Chart(df, title="Ploting using Altair in Streamlit").mark_bar().encode(161 x='Animals',162 y='Number'163)164#render with Streamlit165st.altair_chart(chrt, use_container_width=True)166#Plotly167#define data168df = pd.DataFrame()169df["Animals"] = animals170df["Number"] = number171#create plot172fig1 = px.bar(df, x='Animals', y='Number', title="Ploting using Plotly in Streamlit")173# Plot!174st.plotly_chart(fig1, use_container_width=True)175 176#data177df = pd.DataFrame()178df["Animals"] = animals179df["Number"] = number180#visualization181st.vega_lite_chart(df, {182 'mark': {'type': 'bar', 'tooltip': True},183 'encoding': {184 'x': {'field': 'Animals', 'type': 'nominal'},185 'y': {'field': 'Number', 'type': 'quantitative'},186 },187 }, use_container_width=True)188 189#Maps190import pandas as pd191states = pd.read_html('https://developers.google.com/public-data/docs/canonical/states_csv')[0]192states.columns = ['state', 'lat', 'lon', 'name']193states = states.drop(['state', 'name'], axis = 1)194 195st.map(states)196 197#Components198from st_aggrid import AgGrid199AgGrid(df)200 201#Statefulnness202import streamlit as st203 204st.title('Streamlit Counter Example')205count = 0206 207add = st.button('Addition')208if add:209 count += 1210 211st.write('Count = ', count)212 213 214import streamlit as st215 216st.title('Counter Session State')217if 'count' not in st.session_state:218 st.session_state.count = 0219 220increment = st.button('Add')221if increment:222 st.session_state.count += 1223 224st.write('Count = ', st.session_state.count)225 226#Layout227col1, col2 = st.columns(2)228 229with col1:230 st.altair_chart(chrt)231with col2:232 st.plotly_chart(fig1, use_container_width=True)233with st.beta_container():234 st.plotly_chart(figx, use_container_width=True)235 236 237 238#Add side widget239 240def your_widget(key):241 st.subheader('Hi! Welcome')242 return st.button(key + "Step")243 244# Displayed in the main area245clicked = your_widget("First")246 247# Shown within an expander248your_expander = st.expander("Expand", expanded=True)249with your_expander:250 clicked = your_widget("Second")251 252# Shown in the st.sidebar!253with st.sidebar:254 clicked = your_widget("Last")255#Session State256# Initialization257if 'key' not in st.session_state:258 st.session_state['key'] = 'value'259 260 261 262# Session State also supports attribute based syntax263if 'key' not in st.session_state:264 st.session_state.key = 'value'265 266st.session_state.key = 'value x' # New Attribute API267st.session_state['key'] = 'value x' # New Dictionary like API268 269st.write(st.session_state)270 271#Uploading files272 273import streamlit as st274 275#upload single file276file = st.file_uploader("Please select a file to upload")277if file is not None:278 #Can be used wherever a "file-like" object is accepted:279 df= pd.read_csv(file)280 st.dataframe(df)281 282#Multiple files283#adding a file uploader to accept multiple CSV file284uploaded_files = st.file_uploader("Please select a CSV file", accept_multiple_files=True)285for file in uploaded_files:286 df = pd.read_csv(file)287 st.write("File uploaded:", file.name)288 st.dataframe(df)289#Uploading and Processing290#upload single file291from PIL import Image292from PIL import ImageEnhance293def load_image(image):294 img = Image.open(image)295 return img296 297file = st.file_uploader("Please select image to upload and process")298if file is not None:299 image = Image.open(file) 300 fig = plt.figure()301 st.subheader("Original Image")302 plt.imshow(image)303 st.pyplot(fig)304 fig = plt.figure()305 contrast = ImageEnhance.Contrast(image).enhance(12)306 plt.imshow(contrast)307 st.subheader("Preprocessed Image")308 st.pyplot(fig)309 310 311#Image classification312import keras313from PIL import Image, ImageOps314import numpy as np315 316 317 318import streamlit as st319import streamlit as st320from transformers import pipeline321 322'''Hugging Face'''323 324import streamlit as st325from transformers import pipeline326 327if __name__ == "__main__":328 329 # Define the title of the and its description330 st.title("Answering questions using NLP through Streamlit interface")331 st.write("Pose questions, get answers")332 333 # Load file334 335 raw_text = st.text_area(label="Enter a text here")336 if raw_text != None and raw_text != '':337 338 # Display text339 with st.expander("Show question"):340 st.write(raw_text)341 342 # Conduct question answering using the pipeline343 question_answerer = pipeline('question-answering')344 345 answer = ''346 question = st.text_input('Ask a question')347 348 if question != '' and raw_text != '':349 answer = question_answerer({350 'question': question,351 'context': raw_text352 })353 354 st.write(answer)355 356 357 358 359 360 361 362 363 364 365 