Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Data Science
  • Data Science Projects
  • Data Analysis
  • Data Visualization
  • Machine Learning
  • ML Projects
  • Deep Learning
  • NLP
  • Computer Vision
  • Artificial Intelligence
Open In App
Next Article:
Deploy a Machine Learning Model using Streamlit Library
Next article icon

Deploy a Machine Learning Model using Streamlit Library

Last Updated : 27 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Streamlit is a Python tool that helps you build websites for your data projects or machine learning models. It’s easy to use and lets you create interactive apps with very little code. You don’t need to know how to build a website from scratch. With Streamlit you don’t need to worry about backend development or handling HTTP requests.

In this article, we’ll learn how to deploy a machine learning model using the Streamlit library in a step-by-step manner.

Steps to Deploy a Machine Learning Model Using Streamlit

Let’s train a machine learning model to classify Iris flowers and then deploy it with Streamlit. Firstly we need to install the following:

1. Importing Libraries and Dataset

We'll import pandas and scikit learn library and then import Iris dataset which contains data on three species of Iris flowers. Each entry includes measurements of the flowers' sepal length, sepal width, petal length and petal width. You can download the dataset from here. Iris Dataset

Python
import pandas as pd from sklearn.model_selection import train_test_split from sklearn.ensemble import RandomForestClassifier from sklearn.metrics import accuracy_score  df = pd.read_csv("iris.csv") 

2. Training the Model

We’ll start by loading and preparing the dataset. Since the goal of this article is deployment we will do only basic preprocessing but feel free to make changes. We will use a Random Forest Classifier for this example but other classifiers like Logistic Regression or Support Vector Machine can also be used.

python
df.drop('Id', axis=1, inplace=True)  X = df.drop('Species', axis=1) y = df['Species']  X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)  model = RandomForestClassifier() model.fit(X_train, y_train)  y_pred = model.predict(X_test) accuracy = accuracy_score(y_test, y_pred) print(f"Model accuracy: {accuracy * 100:.2f}%") 

We get an accuracy of 95.55% which is pretty good. Now in order to use this model to predict other unknown data, we need to save it. We can save it by using pickle which is used for serializing and deserializing a Python object structure.

3. Saving the Model

Now that the model is trained we need to save it so it can be used for predictions later. We can use the pickle library to serialize the model and save it as .pkl file.

python
import pickle  with open("classifier.pkl", "wb") as model_file:     pickle.dump(model, model_file) 

This will create a classifier.pkl in your working directory which contains the trained model.

4. Deploying with Streamlit

Next let’s deploy the model using Streamlit. Create a new Python file like app.py and add the following code

python
import streamlit as st import pickle import numpy as np  with open("classifier.pkl", "rb") as model_file:     model = pickle.load(model_file)  st.title("Iris Species Classifier") st.write("Enter the flower measurements to classify the species.")  sepal_length = st.slider("Sepal Length (cm)", min_value=4.0, max_value=8.0, step=0.1) sepal_width = st.slider("Sepal Width (cm)", min_value=2.0, max_value=5.0, step=0.1) petal_length = st.slider("Petal Length (cm)", min_value=1.0, max_value=7.0, step=0.1) petal_width = st.slider("Petal Width (cm)", min_value=0.1, max_value=2.5, step=0.1)  if st.button("Predict"):     features = np.array([[sepal_length, sepal_width, petal_length, petal_width]])     prediction = model.predict(features)     st.write(f"Predicted Iris Species: {prediction[0]}") 

This code creates a simple web app where users can input flower measurements and the model will predict the Iris species based on those values

5. Running the App

To run the app open your terminal and type:

streamlit run app.py

This will launch the Streamlit app in your browser. You can enter flower measurements, click "Predict," and the model will output the predicted species

Output:

Deploying machine learning models with Streamlit is fast, simple and perfect for creating interactive applications. With just a few lines of code you can turn your machine learning model into a user-friendly web application. For more detail refer to:

  • Diabetes Prediction Machine Learning Project Using Python Streamlit
  • Data Science Apps Using Streamlit
  • How to use PyGWalker with Streamlit in Python

Next Article
Deploy a Machine Learning Model using Streamlit Library

A

AashalKamdar
Improve
Article Tags :
  • Machine Learning
  • AI-ML-DS
  • python
  • Python Framework
  • Flask Projects
  • AI-ML-DS With Python
Practice Tags :
  • Machine Learning
  • python

Similar Reads

    Machine Learning Tutorial
    Machine learning is a branch of Artificial Intelligence that focuses on developing models and algorithms that let computers learn from data without being explicitly programmed for every task. In simple words, ML teaches the systems to think and understand like humans by learning from the data.Machin
    5 min read

    Prerequisites for Machine Learning

    Python for Machine Learning
    Welcome to "Python for Machine Learning," a comprehensive guide to mastering one of the most powerful tools in the data science toolkit. Python is widely recognized for its simplicity, versatility, and extensive ecosystem of libraries, making it the go-to programming language for machine learning. I
    6 min read
    SQL for Machine Learning
    Integrating SQL with machine learning can provide a powerful framework for managing and analyzing data, especially in scenarios where large datasets are involved. By combining the structured querying capabilities of SQL with the analytical and predictive capabilities of machine learning algorithms,
    6 min read

    Getting Started with Machine Learning

    Advantages and Disadvantages of Machine Learning
    Machine learning (ML) has revolutionized industries, reshaped decision-making processes, and transformed how we interact with technology. As a subset of artificial intelligence ML enables systems to learn from data, identify patterns, and make decisions with minimal human intervention. While its pot
    3 min read
    Why ML is Important ?
    Machine learning (ML) has become a cornerstone of modern technology, revolutionizing industries and reshaping the way we interact with the world. As a subset of artificial intelligence (AI), ML enables systems to learn and improve from experience without being explicitly programmed. Its importance s
    4 min read
    Real- Life Examples of Machine Learning
    Machine learning plays an important role in real life, as it provides us with countless possibilities and solutions to problems. It is used in various fields, such as health care, financial services, regulation, and more. Importance of Machine Learning in Real-Life ScenariosThe importance of machine
    13 min read
    What is the Role of Machine Learning in Data Science
    In today's world, the collaboration between machine learning and data science plays an important role in maximizing the potential of large datasets. Despite the complexity, these concepts are integral in unraveling insights from vast data pools. Let's delve into the role of machine learning in data
    9 min read
    Top Machine Learning Careers/Jobs
    Machine Learning (ML) is one of the fastest-growing fields in technology, driving innovations across healthcare, finance, e-commerce, and more. As companies increasingly adopt AI-based solutions, the demand for skilled ML professionals is Soaring. Machine Learning JobsThis article delves into the Ty
    10 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences