♻️ AI Trash Sorter

An image classification system that identifies the material type of a waste item and recommends how it should be disposed of.

Upload an image of an item such as a plastic bottle, glass container, cardboard box, electronic device, or piece of clothing. The model predicts its waste category, provides confidence scores, and maps the prediction to a recommended disposal method.

The project was built to explore how computer vision can be applied to a practical environmental problem while also investigating the challenges involved in building and deploying a real-world ML system.

🚀 Demo

The model is deployed as a Gradio application on Hugging Face Spaces.

Upload an image to the application to test the classifier.


What it does

  • Classifies an image into one of 8 waste categories
  • Displays prediction confidence
  • Recommends a corresponding recycling or disposal category
  • Runs through a browser-based Gradio interface
  • Uses a pretrained ResNet50 model fine-tuned for waste classification

Supported categories

Waste Type Recommended Disposal
Plastic 🟡 Plastic Recycling
Glass 🟢 Glass Recycling
Metal ⚪ Metal Recycling
Paper 🔵 Paper Recycling
Cardboard 🔵 Paper/Cardboard Recycling
Organic 🟤 Organic / Compost
Textile 🟣 Textile Collection
E-Waste 🔴 Electronic Waste Collection

Disposal and recycling systems vary by location. The recommendations shown by the application are general categories rather than location-specific waste-management instructions.


🧠 Model

The classifier was built using FastAI with a pretrained ResNet50 convolutional neural network.

The ResNet50 backbone was initially pretrained on ImageNet and then fine-tuned on the waste classification dataset.

Performance

  • Validation accuracy: approximately 94%
  • Validation loss: approximately 0.17
  • Architecture: ResNet50
  • Framework: FastAI / PyTorch
  • Task: Multi-class image classification

The validation accuracy is useful as an overall metric, but it does not tell the whole story. Some categories are visually much harder to distinguish than others, which is why the confusion matrix and per-class behavior were also considered during development.


📊 Dataset

The final dataset contains eight material-based categories:

cardboard
e-waste
glass
metal
organic
paper
plastic
textile

The classes were approximately balanced, with roughly 850–1,000 usable images per class after filtering and selection.

Rather than simply selecting random images, the dataset was balanced using a cluster-based sampling approach:

  1. A pretrained ResNet50 was used as a feature extractor.
  2. Each image was converted into a high-dimensional feature representation.
  3. MiniBatchKMeans clustering was applied to the feature vectors.
  4. Representative images were selected from the resulting clusters.

This approach was used to reduce visual redundancy and retain a broader range of appearances within each class.


🔬 Development Process

This project was not built by simply training a model once and accepting the first accuracy number. Several decisions were made based on the behavior of the dataset and model.

1. Rethinking the waste categories

The original dataset contained a broad trash category.

This created a fundamental classification problem: "trash" is not a material. An item classified as trash could potentially be plastic, paper, metal, organic waste, or another material.

The class was therefore removed and replaced with more meaningful material categories, including organic waste and e-waste.

This made the classification task more consistent with the actual purpose of the application: determining what an item is made of and how it should be handled.

2. Class imbalance and dataset diversity

The original dataset contained different numbers of images across classes.

Instead of simply taking a random subset from each class, representative images were selected using pretrained ResNet50 features and MiniBatchKMeans clustering.

The goal was not only to balance the number of images but also to preserve visual diversity within each class.

3. Model experimentation

Different model configurations were tested during development, including ResNet34 and ResNet50.

The final system uses ResNet50, which provided strong validation performance while remaining practical enough for deployment.

4. Similar-looking materials

The confusion matrix revealed that some materials were significantly more difficult to distinguish than others.

In particular, visually similar materials such as glass and metal could be confused, while the heterogeneous trash category also caused significant ambiguity before it was removed.

This demonstrated an important limitation of using overall accuracy alone: a model can achieve high accuracy while still having specific classes that consistently cause problems.


🛠️ Engineering Challenges

Building the model was only part of the project. Getting the trained model into a usable application introduced several additional engineering problems.

Cross-platform model loading

The model was trained in a Linux/WSL environment and later loaded in a Windows development environment.

Because the FastAI .pkl file contained a serialized PosixPath, loading the model directly on Windows produced a platform-specific error:

NotImplementedError: cannot instantiate 'PosixPath' on your system

The issue was solved by handling the path representation when loading the model on Windows.

This was a useful reminder that serialized Python objects can contain environment-specific information even when the underlying ML model itself is portable.

CUDA compatibility

The development machine uses an RTX 5060 Laptop GPU. An initial PyTorch CUDA build did not properly support the GPU's compute capability.

The environment was subsequently configured with a compatible CUDA-enabled PyTorch build, allowing the GPU to be used for model development and testing.

Separating training from deployment

Training was performed in the Linux/WSL environment, while application development and deployment preparation were moved to native Windows.

This separation avoided unnecessary retraining while making the deployment workflow simpler to manage.


🖥️ Application

The web application is built with Gradio.

The application loads the trained FastAI learner and performs inference on uploaded images.

The general pipeline is:

User uploads image
        ↓
Gradio interface
        ↓
FastAI Learner
        ↓
ResNet50 inference
        ↓
Predicted waste category
        ↓
Confidence scores
        ↓
Disposal recommendation

📁 Project Structure

trash_sorting_v2/
│
├── app.py                       # Gradio application
├── requirements.txt             # Python dependencies
├── README.md                    # Project documentation
│
└── models/
    └── waste_classifier_v2.pkl  # Trained FastAI model

💻 Running Locally

1. Clone the repository

git clone <repository-url>
cd trash_sorting_v2

2. Create a virtual environment

python -m venv .venv

3. Activate the environment

Windows:

.venv\Scripts\activate

Linux / macOS:

source .venv/bin/activate

4. Install dependencies

pip install -r requirements.txt

5. Start the application

python app.py

The application will be available locally at:

http://127.0.0.1:7860

⚠️ Limitations

This is an image classification system rather than an object detection system.

It works best when the image contains a relatively clear view of a single waste item. It is not currently designed to reliably identify several different objects in the same image.

Other limitations include:

  • Similar materials can be visually difficult to distinguish.
  • The model may perform worse on images that differ significantly from the training dataset.
  • Mixed or heavily contaminated waste can be ambiguous.
  • The disposal recommendations are general and may not match local recycling infrastructure.
  • A confidence score should not be interpreted as a guarantee that a prediction is correct.

Most importantly, the model should be treated as an assistance tool rather than an authoritative waste-management system.


🔮 Future Improvements

The current system provides a foundation for a more capable waste-sorting application.

Potential improvements include:

Object detection

Replace single-image classification with object detection so that multiple waste items can be identified in the same image.

For example:

       📦 Cardboard
              ↓
🧴 Plastic → Camera ← 🥫 Metal
              ↓
        📱 E-Waste

Live camera inference

Add webcam support so that waste can be classified in real time rather than requiring individual image uploads.

Better uncertainty handling

Instead of always returning a prediction, the application could detect low-confidence cases and respond with something such as:

"I'm not confident enough to classify this item."

This would be more appropriate for ambiguous real-world waste.

More real-world training data

Collect photographs taken in real environments rather than relying primarily on curated dataset images.

This could improve robustness to:

  • different lighting conditions
  • cluttered backgrounds
  • unusual camera angles
  • partially visible objects
  • damaged or dirty materials

Per-class evaluation

Expand evaluation beyond overall accuracy by tracking:

  • precision
  • recall
  • F1-score
  • confusion matrices
  • per-class performance

This would make it easier to identify which materials require additional data or model improvements.

Location-aware recycling recommendations

Connect predictions to local waste-management systems so that recommendations can reflect the actual recycling infrastructure available in a user's region.


🧰 Built With

  • Python 3.12
  • FastAI
  • PyTorch
  • ResNet50
  • Gradio
  • Pillow
  • Hugging Face Spaces

🎯 Why I Built This

Recycling often requires answering a surprisingly simple question:

"What should I do with this?"

That question becomes difficult when different materials look similar, waste categories are poorly defined, or local disposal rules are unclear.

This project explores whether computer vision can make that decision easier by turning a photograph into an immediate material classification and disposal recommendation.

More importantly, the project was an opportunity to work through the full ML workflow:

Dataset
   ↓
Data analysis
   ↓
Class definition
   ↓
Dataset balancing
   ↓
Model selection
   ↓
Training
   ↓
Evaluation
   ↓
Debugging
   ↓
Application development
   ↓
Deployment

The result is not intended to be a perfect waste-management system. It is a practical experiment in taking a computer vision model from a dataset all the way to a usable application.


📌 Project Status

Current version: v2

The current version supports eight waste categories and achieves approximately 94% validation accuracy.

The next major technical step would be moving from image classification to multi-object detection and real-time camera inference.

Downloads last month

-

Downloads are not tracked for this model. How to track
Inference Providers NEW
This model isn't deployed by any Inference Provider. 🙋 Ask for provider support