Building ML Interfaces with Streamlit
Learn how to build interactive user interfaces for your ML applications with Streamlit.
I
InSkillCoach
· min
Building ML Interfaces with Streamlit
Learn how to build interactive user interfaces for your ML applications with Streamlit.
Basic Setup
1. Installation
pip install streamlit pandas numpy plotly scikit-learn
2. Basic Structure
# app.py
import streamlit as st
import pandas as pd
import plotly.express as px
# Page configuration
st.set_page_config(
page_title="Application ML",
page_icon="🤖",
layout="wide"
)
# Title and description
st.title("Application ML Interactive")
st.markdown("""
Cette application permet de :
- Visualiser des données
- Faire des prédictions
- Analyser les résultats
""")
Interface Components
1. Basic Widgets
# Input widgets
text_input = st.text_input("Texte", "Valeur par défaut")
number_input = st.number_input("Nombre", min_value=0, max_value=100)
selectbox = st.selectbox("Sélection", ["Option 1", "Option 2", "Option 3"])
multiselect = st.multiselect("Sélection multiple", ["A", "B", "C"])
# Buttons and actions
if st.button("Exécuter"):
st.write("Action exécutée!")
# Checkboxes
if st.checkbox("Afficher les détails"):
st.write("Détails supplémentaires...")
2. Data Visualization
# Creating a chart
def create_chart(data):
fig = px.line(data, x='date', y='value')
st.plotly_chart(fig, use_container_width=True)
# Displaying tables
def display_table(data):
st.dataframe(data)
st.table(data)
# Metrics
col1, col2, col3 = st.columns(3)
with col1:
st.metric("Précision", "95%")
with col2:
st.metric("Recall", "92%")
with col3:
st.metric("F1-Score", "93%")
Advanced Features
1. File Handling
# File upload
uploaded_file = st.file_uploader("Choisir un fichier", type=['csv', 'xlsx'])
if uploaded_file is not None:
if uploaded_file.type == "text/csv":
data = pd.read_csv(uploaded_file)
else:
data = pd.read_excel(uploaded_file)
st.write(data)
2. Sidebar and Navigation
# Sidebar configuration
with st.sidebar:
st.title("Configuration")
model_type = st.selectbox(
"Type de modèle",
["Classification", "Régression", "Clustering"]
)
parameters = {
"learning_rate": st.slider("Learning Rate", 0.01, 1.0, 0.1),
"epochs": st.number_input("Époques", 1, 100, 10),
"batch_size": st.selectbox("Batch Size", [16, 32, 64, 128])
}
3. Caching and Performance
@st.cache_data
def load_data():
return pd.read_csv("data.csv")
@st.cache_resource
def load_model():
return joblib.load("model.pkl")
# Usage
data = load_data()
model = load_model()
Backend Integration
1. API Calls
import requests
def call_api(data):
response = requests.post(
"http://localhost:8000/predict",
json=data
)
return response.json()
# Prediction interface
def prediction_interface():
st.subheader("Faire une prédiction")
# Input form
with st.form("prediction_form"):
features = {}
for feature in ["age", "income", "education"]:
features[feature] = st.number_input(feature)
submitted = st.form_submit_button("Prédire")
if submitted:
result = call_api(features)
st.write("Résultat:", result)
2. Error Handling
def safe_api_call(func):
def wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except requests.exceptions.RequestException as e:
st.error(f"Erreur de connexion: {str(e)}")
return None
return wrapper
@safe_api_call
def get_prediction(data):
return requests.post("http://localhost:8000/predict", json=data).json()
Best Practices
-
User Interface
- Responsive design
- Intuitive navigation
- User feedback
- Error handling
-
Performance
- Data caching
- Query optimization
- Progressive loading
- Memory management
-
Security
- Input validation
- Data protection
- Session management
- Logging
Conclusion
Key takeaways:
- Interactive interface
- Effective visualization
- Optimized performance
- Backend integration
Recommendations:
- Follow best practices
- Optimize performance
- Test the interface
- Document the code
- Keep learning Streamlit
About InSkillCoach
Training and technology expert
Coach specializing in advanced technologies and AI, backed by GNeurone Inc.
Certifications:
- AWS Certified Solutions Architect – Professional
- Google Cloud certifications
- Microsoft Certified: DevOps Engineer Expert
- Certified Kubernetes Administrator (CKA)
- CompTIA Security+
921
138
Comments
Comments are powered by GitHub Discussions
Sign in with GitHub to join the discussion