Skip to content

Aaronrao989/Image-Classification-using-CNN

Repository files navigation

🔮 CIFAR-10 Image Classifier

Deep Learning Powered Image Recognition

Streamlit App TensorFlow Python License

Accuracy Model Dataset

Live DemoReport BugRequest Feature


🎯 Overview

A production-ready Convolutional Neural Network (CNN) application that classifies images into 10 distinct categories using the CIFAR-10 dataset. Built with TensorFlow and deployed with a sleek Streamlit interface for real-time predictions.

📊 Supported Classes

✈️ Airplane 🚗 Automobile 🐦 Bird 🐱 Cat 🦌 Deer
🐕 Dog 🐸 Frog 🐴 Horse 🚢 Ship 🚚 Truck

✨ Key Features

🧠 Machine Learning

  • Custom CNN architecture optimized for CIFAR-10
  • Data augmentation for better generalization
  • Training/validation visualization
  • Model checkpointing and export

🎨 User Interface

  • Intuitive Streamlit web application
  • Drag-and-drop image upload
  • Real-time predictions with confidence scores
  • Responsive design for all devices

🚀 Quick Start

Prerequisites

  • Python 3.8 or higher
  • pip package manager
  • (Optional) Virtual environment

Installation

  1. Clone the repository

    git clone https://github.com/yourusername/image-classification-using-cnn.git
    cd image-classification-using-cnn
  2. Create a virtual environment (recommended)

    # macOS/Linux
    python3 -m venv venv
    source venv/bin/activate
    
    # Windows
    python -m venv venv
    .\venv\Scripts\activate
  3. Install dependencies

    pip install -r requirements.txt
  4. Launch the application

    streamlit run app.py

The app will automatically open in your default browser at http://localhost:8501


📁 Project Structure

image-classification-using-cnn/
│
├── 📄 app.py                    # Streamlit web application
├── 📓 model.ipynb               # Model training notebook
├── 🧠 cifar10_cnn.h5           # Pre-trained model weights
├── 🔧 inference.py              # Prediction logic
├── 📋 requirements.txt          # Python dependencies
├── 🙈 .gitignore               # Git ignore rules
└── 📖 README.md                # Project documentation

🎓 Training Your Own Model

Want to train from scratch or fine-tune the model? Follow these steps:

1. Open the Training Notebook

jupyter notebook model.ipynb

2. Training Pipeline

# Load CIFAR-10 dataset (60,000 training images)
(X_train, y_train), (X_test, y_test) = cifar10.load_data()

# Normalize pixel values to [0, 1]
X_train = X_train / 255.0
X_test = X_test / 255.0

# Build CNN architecture
model = Sequential([
    Conv2D(32, (3,3), activation='relu', input_shape=(32,32,3)),
    MaxPooling2D(2,2),
    Conv2D(64, (3,3), activation='relu'),
    MaxPooling2D(2,2),
    Conv2D(64, (3,3), activation='relu'),
    Flatten(),
    Dense(64, activation='relu'),
    Dense(10, activation='softmax')
])

# Train the model
history = model.fit(X_train, y_train, 
                   validation_split=0.2,
                   epochs=20, 
                   batch_size=64)

# Save the trained model
model.save('cifar10_cnn.h5')

3. Evaluate Performance

The notebook includes visualization tools to analyze:

  • Training vs validation accuracy curves
  • Loss progression over epochs
  • Confusion matrix for test predictions
  • Per-class performance metrics

💻 Usage Examples

Web Interface

  1. Navigate to the live demo
  2. Upload an image (JPG, JPEG, or PNG)
  3. Click "Predict" to see classification results
  4. View the predicted class and confidence percentage

Programmatic Inference

from tensorflow.keras.models import load_model
from tensorflow.keras.preprocessing import image
import numpy as np

# Load pre-trained model
model = load_model("cifar10_cnn.h5")

# Load and preprocess image
img = image.load_img("sample.png", target_size=(32, 32))
img_array = image.img_to_array(img)
img_array = np.expand_dims(img_array, axis=0) / 255.0

# Make prediction
predictions = model.predict(img_array)
class_names = ['airplane', 'automobile', 'bird', 'cat', 'deer', 
               'dog', 'frog', 'horse', 'ship', 'truck']

predicted_class = class_names[np.argmax(predictions)]
confidence = np.max(predictions) * 100

print(f"Prediction: {predicted_class}")
print(f"Confidence: {confidence:.2f}%")

🛠️ Technical Stack

Framework Library Purpose
TensorFlow 2.x Keras API Model training & inference
Streamlit Web framework Interactive UI
NumPy Array processing Data manipulation
Pillow Image processing Image loading & preprocessing
Matplotlib Visualization Training metrics plotting

📈 Model Performance

Metric Score
Training Accuracy ~88%
Validation Accuracy ~85%
Test Accuracy ~83%
Inference Time <100ms
Model Size ~2.5MB

Results may vary based on training configuration and hardware


🐛 Troubleshooting

macOS Apple Silicon (M1/M2/M3)

If you encounter TensorFlow installation issues on Apple Silicon:

# Install using conda (recommended)
conda install -c apple tensorflow-deps
pip install tensorflow-macos
pip install tensorflow-metal

Or visit the official Apple TensorFlow guide

Common Issues

Issue: Model file not found
Solution: Ensure cifar10_cnn.h5 is in the project root directory

Issue: Low accuracy predictions
Solution: Model performs best on 32x32 images similar to CIFAR-10 training data

Issue: Streamlit won't start
Solution: Check that port 8501 is not in use: lsof -i :8501


🤝 Contributing

Contributions are welcome! Here's how you can help:

  1. 🍴 Fork the repository
  2. 🌿 Create a feature branch (git checkout -b feature/AmazingFeature)
  3. 💾 Commit your changes (git commit -m 'Add some AmazingFeature')
  4. 📤 Push to the branch (git push origin feature/AmazingFeature)
  5. 🎉 Open a Pull Request

Ideas for Contributions

  • Add more CNN architectures (ResNet, VGG, etc.)
  • Implement transfer learning
  • Add model explainability (Grad-CAM)
  • Support for additional image datasets
  • Mobile app version
  • Docker containerization

📜 License

This project is licensed under the MIT License - see the LICENSE file for details.


🙏 Acknowledgments

  • CIFAR-10 Dataset: Created by Alex Krizhevsky, Vinod Nair, and Geoffrey Hinton
  • TensorFlow Team: For the excellent deep learning framework
  • Streamlit: For making web app development effortless
  • Community: All contributors and users of this project

⭐ If you found this project helpful, please give it a star!


Built with ❤️ using TensorFlow and Streamlit

About

This project is a simple image classification web app built using Streamlit and a TensorFlow/Keras model. It allows users to upload an image, processes it using Pillow, and predicts the class using a pre-trained model. The project demonstrates the integration of a deep learning model with an interactive web UI for quick and easy deployment.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors