Image classification assigns a label to a whole image – “cat”, “defective part”, “digit 7”. This tutorial trains classic ML models on handwritten digits, then shows the CNN approach used for real photos.
What You Will Learn
- How images become feature vectors
- Train logistic regression, SVM and an MLP on digits
- Read the errors
- A Keras CNN for larger images
- Practical tips for your own dataset
Prerequisites
What is Machine Learning, OpenCV Image Processing.
Load the Digits
from sklearn.datasets import load_digits
d = load_digits()
X, y = d.data / 16.0, d.target # pixel values 0–16 scaled to 0–1
print(d.images.shape, X.shape)
(1797, 8, 8) (1797, 64)
Explanation: 1,797 images of 8×8 pixels. Classic models need a flat vector, so each image becomes 64 numbers.
Train Three Models
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.svm import SVC
from sklearn.neural_network import MLPClassifier
from sklearn.metrics import accuracy_score
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.25, random_state=42, stratify=y)
models = {"Logistic": LogisticRegression(max_iter=2000),
"SVM (RBF)": SVC(gamma=0.05, C=5),
"MLP": MLPClassifier((64,), max_iter=600, random_state=0)}
for name, m in models.items():
m.fit(X_tr, y_tr)
print(f"{name:10s}", round(accuracy_score(y_te, m.predict(X_te)), 3))
Logistic 0.962 SVM (RBF) 0.991 MLP 0.984
Explanation: An RBF-kernel SVM gets 99.1% – only 4 mistakes on 450 test images. Simple models work here because the images are tiny, centred and clean.
Inspect the Errors
import numpy as np
from sklearn.metrics import confusion_matrix
svm = models["SVM (RBF)"]
pred = svm.predict(X_te)
cm = confusion_matrix(y_te, pred)
np.fill_diagonal(cm, 0)
i, j = np.unravel_index(cm.argmax(), cm.shape)
print("most confused:", i, "->", j, cm.max(), "| total errors", (pred != y_te).sum(), "of", len(y_te))
most confused: 8 -> 1 2 | total errors 4 of 450
Explanation: Two of the four errors are 8s predicted as 1s. Looking at mistakes – see the confusion matrix – tells you what extra data or features would help.
The Weakness of Flat Pixels
Shift every test image one pixel to the right and the SVM’s accuracy collapses from 99% to 52%, because each pixel position is a separate feature. The fix – training on shifted copies – is shown in Image Data Augmentation. CNNs reduce this problem by design: their filters slide over the image.
CNN for Real Images
from tensorflow import keras
(x_tr, y_tr), (x_te, y_te) = keras.datasets.cifar10.load_data() # 32x32 colour, 10 classes
model = keras.Sequential([
keras.Input(shape=(32, 32, 3)),
keras.layers.Rescaling(1 / 255),
keras.layers.Conv2D(32, 3, activation="relu", padding="same"), keras.layers.MaxPooling2D(),
keras.layers.Conv2D(64, 3, activation="relu", padding="same"), keras.layers.MaxPooling2D(),
keras.layers.Conv2D(128, 3, activation="relu", padding="same"), keras.layers.GlobalAveragePooling2D(),
keras.layers.Dropout(0.3),
keras.layers.Dense(10, activation="softmax")])
model.compile("adam", "sparse_categorical_crossentropy", metrics=["accuracy"])
model.fit(x_tr, y_tr, epochs=10, validation_split=0.1)
Explanation: Convolution layers learn local patterns (edges → textures → object parts), pooling shrinks the image and global average pooling feeds a softmax classifier. A small CNN like this typically reaches roughly 70–80% on CIFAR-10 in 10 epochs; transfer learning from a pre-trained model reaches much higher with less effort. Learn the layers in Introduction to CNN.
Your Own Dataset: Checklist
- Collect at least 100–500 images per class, in realistic conditions.
- Organise folders by class name; split train/validation/test (keep near-duplicates in the same split).
- Start with transfer learning (MobileNet, EfficientNet).
- Add augmentation.
- Check the confusion matrix and the misclassified images, then collect more of the hard cases.
Series
Computer vision series: OpenCV Intro · Image Processing · Image Classification · Data Augmentation · CNN · Transfer Learning · Object Detection (YOLO) · Image Segmentation · OCR · Face Detection
Interview Questions
Q: Why do CNNs beat flat-pixel models on photos?
Convolutions share weights across positions and learn local patterns, giving translation tolerance and far fewer parameters.
Q: How much data do you need?
With transfer learning, often a few hundred images per class; from scratch, many thousands.
Practice Exercises
- Show the four misclassified digits with matplotlib (reshape to 8×8).
- Train the Keras CNN on CIFAR-10 and plot training vs validation accuracy.
Summary
Flatten small images for classic models (SVM reaches 99% on digits), but use CNNs and transfer learning for real photos. Always study the errors.
Next: Image Data Augmentation
Machine Learning Tutorials, Courses and Certifications