Machine Learning project 03
Machine Learning Image Classification Project
Build and evaluate a complete image classification 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 built-in handwritten digits: 1,797 labelled 8×8 grayscale images represented as 64 pixel features.
Skills practised
- Flattened image features
- Feature scaling
- K-nearest neighbours
- Per-class evaluation
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
- Data: Scikit-learn’s built-in handwritten digits: 1,797 labelled 8×8 grayscale images represented as 64 pixel features.
- Preprocessing: A stratified train/test split preserves digit proportions and StandardScaler is fitted within the pipeline.
- Model: KNeighborsClassifier predicts a digit from the five closest training samples in scaled feature space.
- Evaluation: Holdout accuracy plus per-class precision, recall, and F1 scores.
Complete Python code
Save the code as ml_image_classification.py. The random state and data handling are included so the result can be reproduced and reviewed.
"""Classify 8x8 handwritten digit images with k-nearest neighbours."""
from __future__ import annotations
from sklearn.datasets import load_digits
from sklearn.metrics import accuracy_score, classification_report
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.neighbors import KNeighborsClassifier
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(), KNeighborsClassifier(n_neighbors=5))
model.fit(x_train, y_train)
predictions = model.predict(x_test)
return model, x_test, y_test, predictions
def main() -> None:
model, x_test, y_test, predictions = train_model()
print("Handwritten Image Classification with KNN")
print(f"Holdout accuracy: {accuracy_score(y_test, predictions):.3f}\n")
print(classification_report(y_test, predictions, zero_division=0))
sample = 0
print(f"Example prediction: {model.predict(x_test[[sample]])[0]}; actual: {y_test[sample]}")
print("The built-in images are 8x8 grayscale teaching samples, not arbitrary photos.")
if __name__ == "__main__":
main()
How the pipeline works
A stratified train/test split preserves digit proportions and StandardScaler is fitted within the pipeline.
KNeighborsClassifier predicts a digit from the five closest training samples in scaled feature space. Holdout accuracy plus per-class precision, recall, and F1 scores.
Run the project
- Create and activate a virtual environment.
- Install the dependencies with
python -m pip install scikit-learn. - Run
python ml_image_classification.py. - 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
This model accepts the same 8×8 feature format as the teaching dataset. It is not a general photo classifier and should not be compared directly with modern large-image systems.
Ways to extend the project
Tune the neighbour count, display mistakes with Matplotlib, try PCA, compare SVC, or create a careful preprocessing step for a user-drawn 8×8 digit.
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.