/web-to-ai-ml-integrations

ML Model Deployment Using Streamlit Cloud

Step-by-step ML model deployment with Streamlit Cloud. Quick guide to scalable, efficient ML launches.

Book a free  consultation
4.9
Clutch rating 🌟
600+
Happy partners
17+
Countries served
190+
Team members
Matt Graham, CEO of Rapid Developers

Book a call with an Expert

Starting a new venture? Need to upgrade your web app? RapidDev builds application with your growth in mind.

Book a free No-Code consultation

ML Model Deployment Using Streamlit Cloud

 

Integrating Your Trained ML Model with a Streamlit Application

 
  • Train and Persist Your Model: Ensure you have a trained machine learning model saved in an interoperable format (for example, using joblib or pickle). This file (e.g., model.pkl) is the basis for your predictions.
  • Design a User Interface: Use Streamlit’s interactive widgets to gather user input. This can include text input, file upload, sliders, or dropdowns. These inputs will be passed to your model to get predictions.

// Import necessary libraries
import streamlit as st
import joblib   // Used for loading the saved ML model

// Load the persisted model
model = joblib.load("model.pkl")

// Define a function that receives user input and returns predictions
def make_prediction(input_data):
    // Process or transform the input data as necessary
    prediction = model.predict([input\_data])
    return prediction

// Streamlit app logic begins here
st.title("ML Model Deployment on Streamlit Cloud")

// Capture user input; adapt based on model requirements
user_input = st.text_input("Enter the input value:")

// Trigger prediction on button click
if st.button("Predict"):
    try:
        result = make_prediction(user_input)
        st.write("Prediction Result:", result)
    except Exception as e:
        st.error("Error processing prediction: " + str(e))

 

Incorporating Model Logic with Interactive Components

 
  • Decoupling Computation and UI: Separate the model inference logic from user interface code. This makes maintenance easier and allows you to upgrade either side without disturbing the other.
  • Preprocessing Functions: If your model requires a specific data format or normalization, include helper functions within your app. Clear inline comments explain each step to any reader.

// Example preprocessing function
def preprocess_data(raw_input):
    // Convert the raw string input into a numerical format
    try:
        processed_input = float(raw_input)
    except ValueError:
        st.error("Invalid input: please enter a numerical value")
        return None
    return processed\_input

// Updated prediction function utilizing preprocessing
def make_prediction(raw_input):
    processed_input = preprocess_data(raw\_input)
    if processed\_input is None:
        return None
    prediction = model.predict([processed\_input])
    return prediction

 

Managing Dependencies via requirements.txt

 
  • Pin Exact Versions: List all required packages (e.g., streamlit, joblib, scikit-learn, etc.) in a requirements.txt file. This ensures consistent behavior across deployments.
  • Example Entry: streamlit==1.15.0 (adapt version as necessary), along with others required for data processing and model execution.

// Sample content of requirements.txt:
// streamlit==1.15.0
// joblib==1.1.0
// scikit-learn==1.1.1

 

Configuring Secrets and Environment Variables

 
  • Sensitive Data: For API keys, database connections, or any sensitive configuration, use Streamlit’s Secrets Management. This allows you to keep such details out of your source code.
  • Setting a Secret: In your .streamlit/secrets.toml file, define properties like api_key="YOUR_API_KEY". In your code, access them with st.secrets["api_key"].

// Accessing a secret variable within the app
api_key = st.secrets["api_key"]

 

Integrating with Git for Version Control and Deployment

 
  • Version Control: Store the entire project, including the Streamlit app file, the model file, and the requirements.txt, in a Git repository.
  • Repository Setup: Include a .streamlit folder with all necessary configuration files. This organization aids in continuous integration and deployment via Streamlit Cloud.

 

Deploying on Streamlit Cloud

 
  • Deployment Dashboard: Access your Streamlit Cloud account, click on “New App”, and link the repository hosting your project's source code.
  • Configuration: Specify the branch and main file (commonly app.py), confirming that all dependencies are correctly declared. Streamlit Cloud will install them automatically from requirements.txt.
  • Monitoring Deployment: Once deployed, monitor real-time logs via the Streamlit Cloud dashboard. These logs help diagnose startup issues or runtime errors.

 

Debugging and Iterative Updates

 
  • Error Logs: Use Streamlit Cloud’s built-in logging to inspect errors. Detailed error messages can help narrow down issues in data processing, dependency mismatches, or model loading.
  • Local Test Runs: Before each push, run the app locally using streamlit run app.py. This ensures a smoother deployment process on Streamlit Cloud.

// Sample command (run in your terminal locally):
// streamlit run app.py

 

Continuous Integration and Updates

 
  • Frequent Commits: As you update your model or UI logic, commit and push changes to Git. Streamlit Cloud automatically redeploys the app on detecting changes.
  • Testing Enhancements: Integrate unit tests for your data preprocessing and model loading functions. This minimizes downtime and unexpected behavior once deployed.


Recognized by the best

Trusted by 600+ businesses globally

From startups to enterprises and everything in between, see for yourself our incredible impact.

RapidDev was an exceptional project management organization and the best development collaborators I've had the pleasure of working with.

They do complex work on extremely fast timelines and effectively manage the testing and pre-launch process to deliver the best possible product. I'm extremely impressed with their execution ability.

Arkady
CPO, Praction
Working with Matt was comparable to having another co-founder on the team, but without the commitment or cost.

He has a strategic mindset and willing to change the scope of the project in real time based on the needs of the client. A true strategic thought partner!

Donald Muir
Co-Founder, Arc
RapidDev are 10/10, excellent communicators - the best I've ever encountered in the tech dev space.

They always go the extra mile, they genuinely care, they respond quickly, they're flexible, adaptable and their enthusiasm is amazing.

Mat Westergreen-Thorne
Co-CEO, Grantify
RapidDev is an excellent developer for custom-code solutions.

We’ve had great success since launching the platform in November 2023. In a few months, we’ve gained over 1,000 new active users. We’ve also secured several dozen bookings on the platform and seen about 70% new user month-over-month growth since the launch.

Emmanuel Brown
Co-Founder, Church Real Estate Marketplace
Matt’s dedication to executing our vision and his commitment to the project deadline were impressive. 

This was such a specific project, and Matt really delivered. We worked with a really fast turnaround, and he always delivered. The site was a perfect prop for us!

Samantha Fekete
Production Manager, Media Production Company
The pSEO strategy executed by RapidDev is clearly driving meaningful results.

Working with RapidDev has delivered measurable, year-over-year growth. Comparing the same period, clicks increased by 129%, impressions grew by 196%, and average position improved by 14.6%. Most importantly, qualified contact form submissions rose 350%, excluding spam.

Appreciation as well to Matt Graham for championing the collaboration!

Michael W. Hammond
Principal Owner, OCD Tech

We put the rapid in RapidDev

Need a dedicated strategic tech and growth partner? Discover what RapidDev can do for your business! Book a call with our team to schedule a free, no-obligation consultation. We’ll discuss your project and provide a custom quote at no cost.Â