Full CNN Classifier (MNIST)
AdvancedComplete Advanced ML Projects with Full Code
Common setup (run once)
Open your terminal / VS Code and create a virtual environment, then install packages used across projects:
python -m venv venv
# activate:
# Windows: venv\Scripts\activate
# macOS / Linux: source venv/bin/activate
pip install numpy pandas matplotlib scikit-learn tensorflow flask joblib yfinanceIf you only need specific projects, you can install a smaller subset. Each project also repeats its own required installs.
File: project1_cnn_mnist.py
Purpose: train a CNN on MNIST and save model cnn_mnist.h5. Uses TensorFlow Keras.
# project1_cnn_mnist.py
import tensorflow as tf
from tensorflow.keras import layers, models
from tensorflow.keras.datasets import mnist
from tensorflow.keras.utils import to_categorical
import numpy as np
def load_and_prepare():
(x_train, y_train), (x_test, y_test) = mnist.load_data()
# Reshape to (samples, 28,28,1) and scale
x_train = x_train.reshape(-1, 28, 28, 1).astype("float32") / 255.0
x_test = x_test.reshape(-1, 28, 28, 1).astype("float32") / 255.0
return (x_train, y_train), (x_test, y_test)
def build_model():
model = models.Sequential([
layers.Conv2D(32, (3,3), activation="relu", input_shape=(28,28,1)),
layers.MaxPooling2D((2,2)),
layers.Conv2D(64, (3,3), activation="relu"),
layers.MaxPooling2D((2,2)),
layers.Flatten(),
layers.Dense(128, activation="relu"),
layers.Dense(10, activation="softmax")
])
model.compile(optimizer="adam",
loss="sparse_categorical_crossentropy",
metrics=["accuracy"])
return model
def main():
(x_train, y_train), (x_test, y_test) = load_and_prepare()
model = build_model()
print(model.summary())
# Train
model.fit(x_train, y_train, epochs=5, batch_size=128, validation_split=0.1)
# Evaluate
loss, acc = model.evaluate(x_test, y_test, verbose=2)
print(f"Test Loss: {loss:.4f}, Test Accuracy: {acc:.4f}")
# Save model
model.save("cnn_mnist.h5")
print("Saved model to cnn_mnist.h5")
if __name__ == "__main__":
main()Run
python project1_cnn_mnist.py