Spaces:
Running
Running
File size: 6,643 Bytes
854c114 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 | {
"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": [
"<details>\n",
"<summary><b>Click to see Solution</b></summary>\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",
"</details>"
]
},
{
"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
} |