Spaces:
Runtime error
Runtime error
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,88 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import numpy as np
|
2 |
+
import matplotlib.pyplot as plt
|
3 |
+
from sklearn.metrics import classification_report
|
4 |
+
from tensorflow import keras
|
5 |
+
from tensorflow.keras import layers
|
6 |
+
from tensorflow.keras.datasets import mnist
|
7 |
+
import streamlit as st
|
8 |
+
|
9 |
+
# Load the MNIST dataset
|
10 |
+
(train_images, train_labels), (test_images, test_labels) = mnist.load_data()
|
11 |
+
|
12 |
+
# Preprocess the data
|
13 |
+
train_images = train_images.reshape((60000, 28, 28, 1)).astype("float32") / 255
|
14 |
+
test_images = test_images.reshape((10000, 28, 28, 1)).astype("float32") / 255
|
15 |
+
|
16 |
+
# Convert labels to categorical format
|
17 |
+
train_labels = keras.utils.to_categorical(train_labels, 10)
|
18 |
+
test_labels = keras.utils.to_categorical(test_labels, 10)
|
19 |
+
|
20 |
+
# Define the CNN model
|
21 |
+
def create_model():
|
22 |
+
model = keras.Sequential([
|
23 |
+
layers.Conv2D(32, (3, 3), activation="relu", input_shape=(28, 28, 1)),
|
24 |
+
layers.MaxPooling2D((2, 2)),
|
25 |
+
layers.Conv2D(64, (3, 3), activation="relu"),
|
26 |
+
layers.MaxPooling2D((2, 2)),
|
27 |
+
layers.Conv2D(64, (3, 3), activation="relu"),
|
28 |
+
layers.Flatten(),
|
29 |
+
layers.Dense(64, activation="relu"),
|
30 |
+
layers.Dense(10, activation="softmax")
|
31 |
+
])
|
32 |
+
|
33 |
+
model.compile(optimizer="adam", loss="categorical_crossentropy", metrics=["accuracy"])
|
34 |
+
return model
|
35 |
+
|
36 |
+
# Streamlit UI
|
37 |
+
st.title("CNN for MNIST Classification")
|
38 |
+
|
39 |
+
if st.button("Train Model"):
|
40 |
+
model = create_model()
|
41 |
+
with st.spinner("Training..."):
|
42 |
+
history = model.fit(train_images, train_labels, validation_data=(test_images, test_labels), epochs=10, batch_size=64)
|
43 |
+
|
44 |
+
# Plot training loss and accuracy
|
45 |
+
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 4))
|
46 |
+
|
47 |
+
ax1.plot(history.history["loss"], label="Train Loss")
|
48 |
+
ax1.plot(history.history["val_loss"], label="Val Loss")
|
49 |
+
ax1.set_title("Training and Validation Loss")
|
50 |
+
ax1.set_xlabel("Epoch")
|
51 |
+
ax1.set_ylabel("Loss")
|
52 |
+
ax1.legend()
|
53 |
+
|
54 |
+
ax2.plot(history.history["accuracy"], label="Train Accuracy")
|
55 |
+
ax2.plot(history.history["val_accuracy"], label="Val Accuracy")
|
56 |
+
ax2.set_title("Training and Validation Accuracy")
|
57 |
+
ax2.set_xlabel("Epoch")
|
58 |
+
ax2.set_ylabel("Accuracy")
|
59 |
+
ax2.legend()
|
60 |
+
|
61 |
+
st.pyplot(fig)
|
62 |
+
|
63 |
+
# Evaluate the model on test data
|
64 |
+
test_preds = np.argmax(model.predict(test_images), axis=1)
|
65 |
+
true_labels = np.argmax(test_labels, axis=1)
|
66 |
+
|
67 |
+
# Classification report
|
68 |
+
report = classification_report(true_labels, test_preds, digits=4)
|
69 |
+
st.text("Classification Report:")
|
70 |
+
st.text(report)
|
71 |
+
|
72 |
+
# Testing with a specific index
|
73 |
+
index = st.number_input("Enter an index (0-9999) to test:", min_value=0, max_value=9999, step=1)
|
74 |
+
|
75 |
+
def test_index_prediction(index):
|
76 |
+
image = test_images[index].reshape(28, 28)
|
77 |
+
st.image(image, caption=f"True Label: {true_labels[index]}", use_column_width=True)
|
78 |
+
|
79 |
+
prediction = model.predict(test_images[index].reshape(1, 28, 28, 1))
|
80 |
+
predicted_class = np.argmax(prediction)
|
81 |
+
st.write(f"Predicted Class: {predicted_class}")
|
82 |
+
|
83 |
+
if st.button("Test Index"):
|
84 |
+
if 'model' in locals() and model:
|
85 |
+
test_index_prediction(index)
|
86 |
+
else:
|
87 |
+
st.error("Train the model first.")
|
88 |
+
|