Machine Learning Handwritten Digit Recognition Project

Machine Learning project 13

Machine Learning Handwritten Digit Recognition Project

Build and evaluate a complete handwritten digit recognition workflow with reproducible Python code, explicit metrics, and honest limitations.

Explore Machine Learning training in VizagView all project ideas

Dataset and objective

Scikit-learn’s 1,797 labelled 8×8 handwritten digit images flattened to 64 features.

Skills practised

  • Support-vector machines
  • RBF kernels
  • Pixel features
  • Multiclass errors

Requirements

  • Python 3.10 or later
  • A terminal or command prompt
  • python -m pip install scikit-learn
  • About 45-60 minutes to build and review

Machine Learning workflow

  1. Data: Scikit-learn’s 1,797 labelled 8×8 handwritten digit images flattened to 64 features.
  2. Preprocessing: A stratified holdout split and pipeline-based StandardScaler keep class proportions and avoid leakage.
  3. Model: An RBF-kernel support-vector classifier separates nonlinear digit patterns.
  4. Evaluation: Holdout accuracy, a 10-class confusion matrix, and several example predictions.

Complete Python code

Save the code as ml_handwritten_digit_recognition.py. The random state and data handling are included so the result can be reproduced and reviewed.

"""Recognise 8x8 handwritten digits with a support-vector classifier."""

from __future__ import annotations

from sklearn.datasets import load_digits
from sklearn.metrics import accuracy_score, confusion_matrix
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC


def train_model(random_state: int = 42):
    digits = load_digits()
    x_train, x_test, y_train, y_test = train_test_split(
        digits.data,
        digits.target,
        test_size=0.25,
        random_state=random_state,
        stratify=digits.target,
    )
    model = make_pipeline(StandardScaler(), SVC(kernel="rbf", gamma="scale", C=5))
    model.fit(x_train, y_train)
    predictions = model.predict(x_test)
    return model, digits, x_test, y_test, predictions


def main() -> None:
    model, digits, x_test, y_test, predictions = train_model()
    print("Handwritten Digit Recognition with SVC")
    print(f"Holdout accuracy: {accuracy_score(y_test, predictions):.3f}")
    print("Confusion matrix:")
    print(confusion_matrix(y_test, predictions))
    for index in range(5):
        print(f"Sample {index}: predicted {model.predict(x_test[[index]])[0]}, actual {y_test[index]}")
    print(f"Dataset: {len(digits.images)} images, each {digits.images.shape[1]}x{digits.images.shape[2]} pixels.")


if __name__ == "__main__":
    main()

How the pipeline works

A stratified holdout split and pipeline-based StandardScaler keep class proportions and avoid leakage.

An RBF-kernel support-vector classifier separates nonlinear digit patterns. Holdout accuracy, a 10-class confusion matrix, and several example predictions.

Run the project

  1. Create and activate a virtual environment.
  2. Install the dependencies with python -m pip install scikit-learn.
  3. Run python ml_handwritten_digit_recognition.py.
  4. Review every printed metric together with the limitation below; a single score never proves deployment readiness.

How to interpret the evaluation

Classification projects report class-aware metrics so majority classes do not hide weak performance. Regression projects report errors in target units and include R-squared or a simple baseline where appropriate. Always verify the split strategy matches how new data will arrive.

Accuracy, ethics, and safety limits

The model expects the teaching dataset’s exact 8×8 preprocessing. Arbitrary drawings or camera images require matching normalisation, centring, resolution, and validation.

Ways to extend the project

Visualise confused pairs, tune C and gamma with cross-validation, add a drawing canvas, and compare against KNN and a small neural network.

Continue learning Machine Learning

Try the next project, return to the Softenant project library, or explore the Machine Learning course in Vizag for guided data preparation, model evaluation, and portfolio feedback.