Streamlit: A Guide to Create an Interactive App
Introduction to Streamlit:
What is Streamlit?
Streamlit is an open-source Python library that allows you to build interactive and data-driven web applications with minimal effort. It is widely used in data science, machine learning, and analytics to create quick and interactive dashboards without requiring web development knowledge.
Why to use Streamlit?
• Easy to use: No front-end knowledge required.
• Quick development: Turn Python scripts into web apps instantly.
• Interactive widgets: Built-in support for user interaction.
• Ideal for Data Science & ML: Easily display visualizations, dataframes, and models.
Installation and Setup:
To install Streamlit, use the following command:
pip install streamlit
To check if Streamlit is installed correctly, run:
streamlit –version
Running Your First Streamlit App
Create a Python script app.py and add the following code:
import streamlit as st
st.title("Namaskara, Everyone!")
st.write("Welcome to Streamlit! This is my first web app.")
Run the app using:
streamlit run app.py
This will open your Streamlit app in the web browser.
Basic Streamlit Components
1. Displaying Text - Streamlit provides multiple ways to display text
st.title("This is a Title")
st.header("This is a Header")
st.subheader("This is a Subheader")
st.text("This is a simple text")
st.markdown("**This is bold text using Markdown**")
st.code("print('Hello, World!')", language="python")
2. Adding Widgets - Widgets allow user interaction
name = st.text_input("Enter your name:")
st.write(f"Hello, {name}!")
Other widgets:
st.button("Submit")
st.checkbox("Checkbox example")
st.radio("Choose an option:", ["Yes", "No"])
st.selectbox("Pick a number:", [1, 2, 3, 4])
st.slider("Select a range:", 0, 100, 50)
st.file_uploader("Upload a file")
3. Displaying Data
import pandas as pd
df = pd.DataFrame({
"Name": ["Tata", "Reliance", "BSNL"],
"Years": [29, 20, 65]
})
st.write(df)
st.dataframe(df) # Interactive table
st.table(df) # Static table
4. Visualizing Data
Streamlit supports various plotting libraries
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [10, 20, 25, 30, 40]
fig, ax = plt.subplots()
ax.plot(x, y, label="Line Plot")
ax.legend()
st.pyplot(fig)
Using Altair:
import altair as alt
chart = alt.Chart(df).mark_bar().encode(
x="Name",
y="Age"
)
st.altair_chart(chart)
Other Streamlit Features:
5. Layout and Sidebars
st.sidebar.title("Sidebar Menu")
choice = st.sidebar.selectbox("Choose an option", ["Home", "About", "Contact"])
if choice == "Home":
st.write("Welcome to the Home Page!")
elif choice == "About":
st.write("This is an About Page.")
6. Caching for Performance
@st.cache_data
def expensive_function(n):
import time
time.sleep(3)
return n * n
st.write(expensive_function(5)) # This will cache the result
7. Interactive Charts with Plotly
import plotly.express as px
df = px.data.iris()
fig = px.scatter(df, x="sepal_width", y="sepal_length", color="species")
st.plotly_chart(fig)
Advanced Streamlit Concepts
8. Session State (Maintaining State)
if "count" not in st.session_state:
st.session_state.count = 0
if st.button("Increment"):
st.session_state.count += 1
st.write("Counter:", st.session_state.count)
9. Authentication in Streamlit
import streamlit_authenticator as stauth
users = {"user1": "password123", "user2": "password456"}
username = st.text_input("Username")
password = st.text_input("Password", type="password")
if st.button("Login"):
if username in users and users[username] == password:
st.success("Login Successful!")
else:
st.error("Invalid Credentials")
10. Deploying Streamlit Apps
Streamlit apps can be deployed on platforms like:
1) Streamlit Cloud (Recommended) - https://streamlit.io
• Upload your project to GitHub.
• Go to https://streamlit.io
• Deploy directly from the repository.
2) Using Heroku
pip install heroku
heroku create streamlit-app
git push heroku main
3) Using AWS or GCP
• Use services like AWS EC2, Lambda, or Google Cloud Run.
11. Example of End-to-End Project: ML Model Deployment
1. Building a Machine Learning Model
import joblib
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.datasets import load_iris
iris = load_iris()
X_train, X_test, y_train, y_test = train_test_split(iris.data, iris.target, test_size=0.2)
model = RandomForestClassifier()
model.fit(X_train, y_train)
joblib.dump(model, "model.pkl")
2. Creating the Streamlit Interface
model = joblib.load("model.pkl")
sepal_length = st.slider("Sepal Length", 4.0, 8.0, 5.5)
sepal_width = st.slider("Sepal Width", 2.0, 4.5, 3.0)
petal_length = st.slider("Petal Length", 1.0, 7.0, 3.5)
petal_width = st.slider("Petal Width", 0.1, 2.5, 1.0)
prediction = model.predict([[sepal_length, sepal_width, petal_length, petal_width]])
st.write(f"Predicted Species: {iris.target_names[prediction[0]]}")
Deep Learning Examples
Streamlit app provides an interactive interface for multiple Deep Learning applications:
1. Image Classification (CNN) - Uses MobileNetV2 for image classification
2. Object Detection (CV) - Uses YOLOv5 for detecting objects in images
3. Text Generation (RNN) - Uses an RNN to generate text
4. Time Series Prediction (LSTM) - Uses an LSTM model for forecasting
5. GANs for Image Generation - Generates images using a GAN model
Note: You need to have the pre-trained models for RNN, LSTM, and GAN loaded properly!
# Importing necessary libraries
import streamlit as st
import tensorflow as tf
import numpy as np
import cv2
from PIL import Image
import torch
import torchvision.transforms as transforms
# Title of the Interative app
st.title("Deep Learning with Streamlit")
# Sidebar for model selection
option = st.sidebar.selectbox("Choose a Deep Learning Model", [
"Image Classification (CNN)", "Object Detection (CV)", "Text Generation (RNN)", "Time Series Prediction (LSTM)", "GANs for Image Generation"
])
# Image Classification with CNN
if option == "Image Classification (CNN)":
st.subheader("Image Classification using CNN")
model = tf.keras.applications.MobileNetV2(weights='imagenet')
uploaded_file = st.file_uploader("Upload an Image", type=["jpg", "png", "jpeg"])
if uploaded_file is not None:
image = Image.open(uploaded_file).convert('RGB')
st.image(image, caption='Uploaded Image', use_container_width=True)
img_array = np.array(image)
img_resized = cv2.resize(img_array, (224, 224)) / 255.0
img_reshaped = np.expand_dims(img_resized, axis=0)
prediction = model.predict(img_reshaped)
decoded_prediction = tf.keras.applications.mobilenet_v2.decode_predictions(prediction, top=3)[0]
for i, (imagenet_id, label, score) in enumerate(decoded_prediction):
st.write(f"{i+1}. {label}: {score:.4f}")
# Object Detection (CV)
elif option == "Object Detection (CV)":
st.subheader("Object Detection using YOLOv5")
model = torch.hub.load('ultralytics/yolov5', 'yolov5s', pretrained=True)
uploaded_file = st.file_uploader("Upload an Image", type=["jpg", "png", "jpeg"])
if uploaded_file is not None:
image = Image.open(uploaded_file).convert('RGB')
st.image(image, caption='Uploaded Image', use_container_width=True)
img_array = np.array(image)
results = model(img_array)
results.render()
st.image(results.ims[0], caption='Object Detection Result', use_container_width=True)
# Text Generation using RNN – Download or upload the model to cloud and link it
elif option == "Text Generation (RNN)":
st.subheader("Text Generation using RNN")
model = tf.keras.models.load_model("rnn_text_gen_model.h5") # Assume a pre-trained RNN model is available
input_text = st.text_input("Enter seed text:")
if input_text:
generated_text = input_text
for _ in range(50):
input_seq = np.array([[ord(c) for c in generated_text[-10:]]])
prediction = model.predict(input_seq)
next_char = chr(np.argmax(prediction))
generated_text += next_char
st.write("Generated Text:", generated_text)
# Time Series Prediction with LSTM
elif option == "Time Series Prediction (LSTM)":
st.subheader("Time Series Prediction using LSTM")
model = tf.keras.models.load_model("lstm_time_series.h5") # Assume a trained LSTM model is available
input_data = st.text_area("Enter past time-series data (comma-separated):")
if input_data:
series = np.array([float(x) for x in input_data.split(',')])
series = series.reshape(1, -1, 1)
prediction = model.predict(series)
st.write("Next predicted value:", prediction[0][0])
# GANs for Image Generation
elif option == "GANs for Image Generation":
st.subheader("Image Generation using GANs")
generator = tf.keras.models.load_model("gan_generator.h5") # Assume a trained GAN generator
noise_dim = 100
noise = np.random.normal(0, 1, (1, noise_dim))
generated_image = generator.predict(noise)[0]
generated_image = (generated_image * 127.5 + 127.5).astype(np.uint8)
st.image(generated_image, caption='Generated Image', use_container_width=True)
Conclusion:
Streamlit is a powerful and beginner-friendly tool for building web applications, particularly in data science and machine learning. With its simple syntax, rapid development capabilities, and interactive features, it is an excellent choice for deploying models and visualizations.
Key Takeaways:
· Simple syntax, yet powerful
· Easy to integrate with ML models
· Interactive UI without front-end expertise
· Great for rapid prototyping and deployment
Comments
Post a Comment