{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# ML Practice Series: Module 25 - Model Deployment with Streamlit\n", "\n", "A model in a notebook is just an experiment. A **deployed model** is a product! In this module, you'll learn to turn your ML models into interactive web applications using **Streamlit**.\n", "\n", "### Objectives:\n", "1. **Streamlit Basics**: Creating interactive UIs with pure Python.\n", "2. **Model Persistence**: Saving and loading models with `joblib`.\n", "3. **User Input**: Sliders, text boxes, and file uploads.\n", "4. **Real-Time Prediction**: Deploying your Iris classifier as a web app.\n", "\n", "---" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 1. Training and Saving a Model\n", "\n", "First, let's train a simple classifier and save it to disk." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from sklearn.datasets import load_iris\n", "from sklearn.ensemble import RandomForestClassifier\n", "import joblib\n", "\n", "# Load and train\n", "iris = load_iris()\n", "X, y = iris.data, iris.target\n", "\n", "model = RandomForestClassifier(n_estimators=100, random_state=42)\n", "model.fit(X, y)\n", "\n", "# Save the model\n", "joblib.dump(model, 'iris_model.pkl')\n", "print(\"Model saved as iris_model.pkl\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 2. Creating a Streamlit App\n", "\n", "### Task 1: Build the App\n", "Create a file called `app.py` with the following Streamlit code. This app will:\n", "1. Load the saved model\n", "2. Accept user inputs (sepal/petal measurements)\n", "3. Make predictions in real-time" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "%%writefile app.py\n", "import streamlit as st\n", "import joblib\n", "import numpy as np\n", "\n", "# Load the model\n", "model = joblib.load('iris_model.pkl')\n", "\n", "st.title('🌸 Iris Species Predictor')\n", "st.write('Enter the flower measurements to predict the species!')\n", "\n", "# User inputs\n", "sepal_length = st.slider('Sepal Length (cm)', 4.0, 8.0, 5.8)\n", "sepal_width = st.slider('Sepal Width (cm)', 2.0, 4.5, 3.0)\n", "petal_length = st.slider('Petal Length (cm)', 1.0, 7.0, 4.0)\n", "petal_width = st.slider('Petal Width (cm)', 0.1, 2.5, 1.2)\n", "\n", "# Make prediction\n", "if st.button('Predict Species'):\n", " features = np.array([[sepal_length, sepal_width, petal_length, petal_width]])\n", " prediction = model.predict(features)\n", " species = ['Setosa', 'Versicolor', 'Virginica']\n", " \n", " st.success(f'Predicted Species: **{species[prediction[0]]}**')\n", " st.balloons()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 3. Running the App\n", "\n", "### Task 2: Launch Streamlit\n", "Open your terminal and run:\n", "```bash\n", "streamlit run app.py\n", "```\n", "\n", "Your browser will open with an interactive web app!" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 4. Advanced Features\n", "\n", "### Task 3: File Upload\n", "Modify `app.py` to allow users to upload a CSV file and make batch predictions." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "
\n", "Click to see Solution\n", "\n", "```python\n", "# Add this to your app.py\n", "import pandas as pd\n", "\n", "uploaded_file = st.file_uploader(\"Upload CSV for batch predictions\", type=\"csv\")\n", "\n", "if uploaded_file is not None:\n", " df = pd.read_csv(uploaded_file)\n", " predictions = model.predict(df)\n", " df['Predicted Species'] = [species[p] for p in predictions]\n", " st.write(df)\n", "```\n", "
" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "--- \n", "### Deployment Mastered! \n", "You now know how to turn any ML model into a shareable web app.\n", "Next: **End-to-End ML Project Workflow**." ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.12.7" } }, "nbformat": 4, "nbformat_minor": 4 }