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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
MNIST Digit Classifier - Streamlit Web Application
|
| 3 |
+
Deploy to Hugging Face Spaces or run locally with: streamlit run app.py
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
import streamlit as st
|
| 7 |
+
import numpy as np
|
| 8 |
+
import tensorflow as tf
|
| 9 |
+
from tensorflow import keras
|
| 10 |
+
from PIL import Image, ImageOps
|
| 11 |
+
import cv2
|
| 12 |
+
from streamlit_drawable_canvas import st_canvas
|
| 13 |
+
|
| 14 |
+
# Page configuration
|
| 15 |
+
st.set_page_config(
|
| 16 |
+
page_title="MNIST Digit Classifier",
|
| 17 |
+
page_icon="๐ข",
|
| 18 |
+
layout="wide"
|
| 19 |
+
)
|
| 20 |
+
|
| 21 |
+
# Custom CSS for better styling
|
| 22 |
+
st.markdown("""
|
| 23 |
+
<style>
|
| 24 |
+
.main-header {
|
| 25 |
+
font-size: 3rem;
|
| 26 |
+
color: #1f77b4;
|
| 27 |
+
text-align: center;
|
| 28 |
+
margin-bottom: 2rem;
|
| 29 |
+
}
|
| 30 |
+
.prediction-box {
|
| 31 |
+
padding: 2rem;
|
| 32 |
+
border-radius: 10px;
|
| 33 |
+
background-color: #f0f2f6;
|
| 34 |
+
text-align: center;
|
| 35 |
+
}
|
| 36 |
+
.confidence-bar {
|
| 37 |
+
margin: 0.5rem 0;
|
| 38 |
+
}
|
| 39 |
+
</style>
|
| 40 |
+
""", unsafe_allow_html=True)
|
| 41 |
+
|
| 42 |
+
# Title and description
|
| 43 |
+
st.markdown('<h1 class="main-header">๐ข MNIST Digit Classifier</h1>', unsafe_allow_html=True)
|
| 44 |
+
st.markdown("""
|
| 45 |
+
<p style='text-align: center; font-size: 1.2rem;'>
|
| 46 |
+
Draw a digit or upload an image, and the AI will predict what number it is!
|
| 47 |
+
</p>
|
| 48 |
+
""", unsafe_allow_html=True)
|
| 49 |
+
|
| 50 |
+
# Load or create model
|
| 51 |
+
@st.cache_resource
|
| 52 |
+
def load_model():
|
| 53 |
+
"""Load pre-trained model or create a new one"""
|
| 54 |
+
try:
|
| 55 |
+
# Try to load saved model
|
| 56 |
+
model = keras.models.load_model('mnist_model.h5')
|
| 57 |
+
st.success("โ
Pre-trained model loaded successfully!")
|
| 58 |
+
except:
|
| 59 |
+
# Create and train a simple model if not available
|
| 60 |
+
st.info("๐ Training a new model... This will take a moment.")
|
| 61 |
+
|
| 62 |
+
# Load MNIST data
|
| 63 |
+
(X_train, y_train), (X_test, y_test) = keras.datasets.mnist.load_data()
|
| 64 |
+
|
| 65 |
+
# Preprocess
|
| 66 |
+
X_train = X_train.reshape(-1, 28 * 28).astype('float32') / 255.0
|
| 67 |
+
X_test = X_test.reshape(-1, 28 * 28).astype('float32') / 255.0
|
| 68 |
+
y_train = keras.utils.to_categorical(y_train, 10)
|
| 69 |
+
y_test = keras.utils.to_categorical(y_test, 10)
|
| 70 |
+
|
| 71 |
+
# Build model
|
| 72 |
+
model = keras.Sequential([
|
| 73 |
+
keras.layers.Input(shape=(784,)),
|
| 74 |
+
keras.layers.Dense(128, activation='relu'),
|
| 75 |
+
keras.layers.Dropout(0.2),
|
| 76 |
+
keras.layers.Dense(64, activation='relu'),
|
| 77 |
+
keras.layers.Dropout(0.2),
|
| 78 |
+
keras.layers.Dense(10, activation='softmax')
|
| 79 |
+
])
|
| 80 |
+
|
| 81 |
+
model.compile(
|
| 82 |
+
optimizer='adam',
|
| 83 |
+
loss='categorical_crossentropy',
|
| 84 |
+
metrics=['accuracy']
|
| 85 |
+
)
|
| 86 |
+
|
| 87 |
+
# Train with progress bar
|
| 88 |
+
with st.spinner("Training model..."):
|
| 89 |
+
model.fit(X_train, y_train, epochs=5, batch_size=128,
|
| 90 |
+
validation_split=0.1, verbose=0)
|
| 91 |
+
|
| 92 |
+
# Save model
|
| 93 |
+
model.save('mnist_model.h5')
|
| 94 |
+
|
| 95 |
+
# Evaluate
|
| 96 |
+
test_loss, test_acc = model.evaluate(X_test, y_test, verbose=0)
|
| 97 |
+
st.success(f"โ
Model trained! Test Accuracy: {test_acc:.4f}")
|
| 98 |
+
|
| 99 |
+
return model
|
| 100 |
+
|
| 101 |
+
model = load_model()
|
| 102 |
+
|
| 103 |
+
# Preprocessing function
|
| 104 |
+
def preprocess_image(image):
|
| 105 |
+
"""Preprocess image for model prediction"""
|
| 106 |
+
# Convert to grayscale if needed
|
| 107 |
+
if len(image.shape) == 3:
|
| 108 |
+
image = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
|
| 109 |
+
|
| 110 |
+
# Resize to 28x28
|
| 111 |
+
image = cv2.resize(image, (28, 28))
|
| 112 |
+
|
| 113 |
+
# Invert if background is white (MNIST is white on black)
|
| 114 |
+
if np.mean(image) > 127:
|
| 115 |
+
image = 255 - image
|
| 116 |
+
|
| 117 |
+
# Normalize
|
| 118 |
+
image = image.astype('float32') / 255.0
|
| 119 |
+
|
| 120 |
+
# Reshape for model
|
| 121 |
+
image = image.reshape(1, 784)
|
| 122 |
+
|
| 123 |
+
return image
|
| 124 |
+
|
| 125 |
+
# Create tabs for different input methods
|
| 126 |
+
tab1, tab2, tab3 = st.tabs(["โ๏ธ Draw", "๐ค Upload", "๐ Model Info"])
|
| 127 |
+
|
| 128 |
+
with tab1:
|
| 129 |
+
st.subheader("Draw a digit (0-9)")
|
| 130 |
+
|
| 131 |
+
col1, col2 = st.columns([2, 1])
|
| 132 |
+
|
| 133 |
+
with col1:
|
| 134 |
+
# Drawing canvas
|
| 135 |
+
canvas_result = st_canvas(
|
| 136 |
+
fill_color="rgba(255, 255, 255, 1)",
|
| 137 |
+
stroke_width=20,
|
| 138 |
+
stroke_color="rgb(255, 255, 255)",
|
| 139 |
+
background_color="rgb(0, 0, 0)",
|
| 140 |
+
height=280,
|
| 141 |
+
width=280,
|
| 142 |
+
drawing_mode="freedraw",
|
| 143 |
+
key="canvas",
|
| 144 |
+
)
|
| 145 |
+
|
| 146 |
+
with col2:
|
| 147 |
+
if canvas_result.image_data is not None:
|
| 148 |
+
# Get the image from canvas
|
| 149 |
+
img = canvas_result.image_data.astype('uint8')
|
| 150 |
+
|
| 151 |
+
# Show preprocessed image
|
| 152 |
+
st.write("**Preprocessed (28x28):**")
|
| 153 |
+
processed = cv2.cvtColor(img, cv2.COLOR_RGBA2GRAY)
|
| 154 |
+
processed = cv2.resize(processed, (28, 28))
|
| 155 |
+
st.image(processed, width=140, clamp=True)
|
| 156 |
+
|
| 157 |
+
# Predict button
|
| 158 |
+
if st.button("๐ฎ Predict", key="predict_draw", type="primary"):
|
| 159 |
+
# Preprocess and predict
|
| 160 |
+
input_data = preprocess_image(img[:, :, :3])
|
| 161 |
+
predictions = model.predict(input_data, verbose=0)
|
| 162 |
+
predicted_digit = np.argmax(predictions[0])
|
| 163 |
+
confidence = predictions[0][predicted_digit] * 100
|
| 164 |
+
|
| 165 |
+
# Display prediction
|
| 166 |
+
st.markdown("---")
|
| 167 |
+
st.markdown(f"""
|
| 168 |
+
<div class="prediction-box">
|
| 169 |
+
<h2 style='color: #1f77b4; margin: 0;'>Predicted Digit</h2>
|
| 170 |
+
<h1 style='font-size: 4rem; margin: 1rem 0;'>{predicted_digit}</h1>
|
| 171 |
+
<p style='font-size: 1.2rem;'>Confidence: {confidence:.2f}%</p>
|
| 172 |
+
</div>
|
| 173 |
+
""", unsafe_allow_html=True)
|
| 174 |
+
|
| 175 |
+
# Show all probabilities
|
| 176 |
+
st.write("**All Probabilities:**")
|
| 177 |
+
for digit in range(10):
|
| 178 |
+
prob = predictions[0][digit] * 100
|
| 179 |
+
st.progress(predictions[0][digit], text=f"Digit {digit}: {prob:.2f}%")
|
| 180 |
+
|
| 181 |
+
with tab2:
|
| 182 |
+
st.subheader("Upload an image of a digit")
|
| 183 |
+
|
| 184 |
+
uploaded_file = st.file_uploader("Choose an image...", type=['png', 'jpg', 'jpeg'])
|
| 185 |
+
|
| 186 |
+
if uploaded_file is not None:
|
| 187 |
+
col1, col2 = st.columns(2)
|
| 188 |
+
|
| 189 |
+
with col1:
|
| 190 |
+
# Display original image
|
| 191 |
+
image = Image.open(uploaded_file)
|
| 192 |
+
st.image(image, caption="Uploaded Image", use_container_width=True)
|
| 193 |
+
|
| 194 |
+
with col2:
|
| 195 |
+
# Convert to numpy array
|
| 196 |
+
img_array = np.array(image)
|
| 197 |
+
|
| 198 |
+
# Preprocess and predict
|
| 199 |
+
input_data = preprocess_image(img_array)
|
| 200 |
+
predictions = model.predict(input_data, verbose=0)
|
| 201 |
+
predicted_digit = np.argmax(predictions[0])
|
| 202 |
+
confidence = predictions[0][predicted_digit] * 100
|
| 203 |
+
|
| 204 |
+
# Display prediction
|
| 205 |
+
st.markdown(f"""
|
| 206 |
+
<div class="prediction-box">
|
| 207 |
+
<h2 style='color: #1f77b4; margin: 0;'>Predicted Digit</h2>
|
| 208 |
+
<h1 style='font-size: 4rem; margin: 1rem 0;'>{predicted_digit}</h1>
|
| 209 |
+
<p style='font-size: 1.2rem;'>Confidence: {confidence:.2f}%</p>
|
| 210 |
+
</div>
|
| 211 |
+
""", unsafe_allow_html=True)
|
| 212 |
+
|
| 213 |
+
# Show preprocessed image
|
| 214 |
+
processed = cv2.resize(img_array, (28, 28))
|
| 215 |
+
if len(processed.shape) == 3:
|
| 216 |
+
processed = cv2.cvtColor(processed, cv2.COLOR_RGB2GRAY)
|
| 217 |
+
st.image(processed, caption="Preprocessed (28x28)", width=140)
|
| 218 |
+
|
| 219 |
+
# Show all probabilities
|
| 220 |
+
st.write("**Probability Distribution:**")
|
| 221 |
+
chart_data = {f"Digit {i}": [predictions[0][i]] for i in range(10)}
|
| 222 |
+
st.bar_chart(chart_data)
|
| 223 |
+
|
| 224 |
+
with tab3:
|
| 225 |
+
st.subheader("๐ Model Information")
|
| 226 |
+
|
| 227 |
+
col1, col2 = st.columns(2)
|
| 228 |
+
|
| 229 |
+
with col1:
|
| 230 |
+
st.markdown("""
|
| 231 |
+
### Model Architecture
|
| 232 |
+
- **Input Layer:** 784 neurons (28ร28 pixels)
|
| 233 |
+
- **Hidden Layer 1:** 128 neurons (ReLU)
|
| 234 |
+
- **Dropout:** 20%
|
| 235 |
+
- **Hidden Layer 2:** 64 neurons (ReLU)
|
| 236 |
+
- **Dropout:** 20%
|
| 237 |
+
- **Output Layer:** 10 neurons (Softmax)
|
| 238 |
+
|
| 239 |
+
### Training Details
|
| 240 |
+
- **Dataset:** MNIST (70,000 images)
|
| 241 |
+
- **Optimizer:** Adam
|
| 242 |
+
- **Loss Function:** Categorical Crossentropy
|
| 243 |
+
- **Training Samples:** 60,000
|
| 244 |
+
- **Test Samples:** 10,000
|
| 245 |
+
""")
|
| 246 |
+
|
| 247 |
+
with col2:
|
| 248 |
+
st.markdown("""
|
| 249 |
+
### About MNIST
|
| 250 |
+
The MNIST database contains 70,000 images of handwritten digits:
|
| 251 |
+
- **Training set:** 60,000 images
|
| 252 |
+
- **Test set:** 10,000 images
|
| 253 |
+
- **Image size:** 28ร28 pixels
|
| 254 |
+
- **Classes:** 10 (digits 0-9)
|
| 255 |
+
|
| 256 |
+
### How to Use
|
| 257 |
+
1. **Draw Tab:** Draw a digit using your mouse/touchscreen
|
| 258 |
+
2. **Upload Tab:** Upload an image file
|
| 259 |
+
3. Click **Predict** to see the results
|
| 260 |
+
4. View confidence scores for all digits
|
| 261 |
+
""")
|
| 262 |
+
|
| 263 |
+
# Model summary
|
| 264 |
+
st.subheader("Model Summary")
|
| 265 |
+
|
| 266 |
+
# Create a string buffer to capture model summary
|
| 267 |
+
from io import StringIO
|
| 268 |
+
buffer = StringIO()
|
| 269 |
+
model.summary(print_fn=lambda x: buffer.write(x + '\n'))
|
| 270 |
+
st.text(buffer.getvalue())
|
| 271 |
+
|
| 272 |
+
# Footer
|
| 273 |
+
st.markdown("---")
|
| 274 |
+
st.markdown("""
|
| 275 |
+
<p style='text-align: center; color: #666;'>
|
| 276 |
+
Built with Streamlit โข TensorFlow โข MNIST Dataset<br>
|
| 277 |
+
Deploy to Hugging Face Spaces for free hosting!
|
| 278 |
+
</p>
|
| 279 |
+
""", unsafe_allow_html=True)
|