dgith commited on
Commit
6748826
·
verified ·
1 Parent(s): dc0f672

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +52 -272
app.py CHANGED
@@ -1,279 +1,59 @@
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)
 
1
+ # train_model.py - Download, train, and export MNIST model
 
 
 
2
 
 
 
3
  import tensorflow as tf
4
+ import numpy as np
5
+ import os
6
+
7
+ print("Loading MNIST dataset...")
8
+
9
+ # Load and preprocess data
10
+ (x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data()
11
+
12
+ # Normalize pixel values to [0, 1]
13
+ x_train = x_train.astype('float32') / 255.0
14
+ x_test = x_test.astype('float32') / 255.0
15
+
16
+ # Optional: Use subset for faster training during development
17
+ # x_train, y_train = x_train[:20000], y_train[:20000]
18
+ # x_test, y_test = x_test[:5000], y_test[:5000]
19
+
20
+ print(f"Training on {len(x_train)} samples")
21
+ print(f"Testing on {len(x_test)} samples")
22
+
23
+ # Build model
24
+ model = tf.keras.Sequential([
25
+ tf.keras.layers.Flatten(input_shape=(28, 28)),
26
+ tf.keras.layers.Dense(128, activation='relu'),
27
+ tf.keras.layers.Dropout(0.2),
28
+ tf.keras.layers.Dense(64, activation='relu'),
29
+ tf.keras.layers.Dropout(0.1),
30
+ tf.keras.layers.Dense(10, activation='softmax')
31
+ ])
32
+
33
+ # Compile
34
+ model.compile(
35
+ optimizer='adam',
36
+ loss='sparse_categorical_crossentropy',
37
+ metrics=['accuracy']
38
  )
39
 
40
+ # Train
41
+ print("Training model...")
42
+ model.fit(
43
+ x_train, y_train,
44
+ epochs=5,
45
+ batch_size=32,
46
+ validation_data=(x_test, y_test),
47
+ verbose=1
48
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49
 
50
+ # Evaluate
51
+ test_loss, test_accuracy = model.evaluate(x_test, y_test, verbose=0)
52
+ print(f"\n✅ Model trained! Test Accuracy: {test_accuracy:.4f}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
53
 
54
+ # Create models directory
55
+ os.makedirs("model", exist_ok=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
56
 
57
+ # Save model in Keras format (.h5)
58
+ model.save("model/mnist_model.h5")
59
+ print("💾 Model saved to model/mnist_model.h5")