MNIST CNN vs Random Forest Comparison

By Eldar · Published July 8, 2026

Side-by-side evaluation of Convolutional Neural Networks and Random Forest classifiers on MNIST digit recognition with confusion matrices and prediction visualizations.

  • mnist
  • cnn
  • random-forest
  • classification
  • comparison
  • computer-vision
8 cells4 experiments11 views0 forks

Inside this notebook

# %% [markdown]
# ## Shared Setup — MNIST Handwritten Digit Recognition
# Comparing **CNN** vs **Random Forest** side-by-side.

# %%
%pip install tensorflow -q

import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from tensorflow import keras
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import classification_report, confusion_matrix, accuracy_score
import warnings
warnings.filterwarnings('ignore')
print("All imports loaded.")
Note: you may need to restart the kernel to use updated packages.
All imports loaded.
# Load MNIST
(x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data()

# Normalize to [0,1]
x_train = x_train.astype('float32') / 255.0
x_test = x_test.astype('float32') / 255.0

print(f"Train: {x_train.shape}, Test: {x_test.shape}")
print(f"Classes: {np.unique(y_train)}")
Train: (60000, 28, 28), Test: (10000, 28, 28)
Classes: [0 1 2 3 4 5 6 7 8 9]
def evaluate_and_show(model, x_test, y_test, approach_name, is_cnn=True):
    """Evaluate a model and show predictions with visual examples."""
    # Get predictions
    if is_cnn:
        preds = model.predict(x_test, verbose=0)
        y_pred = np.argmax(preds, axis=1)
    else:
        y_pred = model.predict(x_test)
    
    # Accuracy
    acc = accuracy_score(y_test, y_pred)
    print(f"\n{'='*50}")
    print(f"  {approach_name}")
    print(f"  Test Accuracy: {acc:.4f} ({acc*100:.2f}%)")
    print(f"{'='*50}")
    print(classification_report(y_test, y_pred))
    
    # Confusion matrix heatmap
…
evaluate_and_show() helper ready.
MNIST CNN vs Random Forest Comparison | Clusy