region:us
# Fruit Classification Using Deep Learning

## Introduction
Welcome to the fascinating world of "Fruit Classification using Deep Learning"! Our project harnesses the power of convolutional neural networks, specifically the MobileNetV2 architecture within the TensorFlow framework, to classify various types of fruits with remarkable accuracy. With a meticulously curated dataset comprising a wide array of fruit images, our model achieves an impressive 99.9% accuracy during training and maintains a robust 99.5% accuracy in testing. Beyond its performance, this project extends its accessibility by offering a Gradio-based machine learning application. This intuitive application allows users to effortlessly input images of fruits, receiving swift and accurate predictions regarding their classification. In this fusion of technology and nature, our project not only showcases the capabilities of deep learning in image recognition but also opens doors for broader applications in agriculture, food industry, and education.

## Dataset
For this project, we gathered a comprehensive dataset from [https://www.kaggle.com/datasets/moltean/fruits], encompassing a diverse range of fruit images. The dataset consists of training, testing, and validation sets, each containing high-resolution images of fruits in JPEG format with dimensions of 224 x 224 pixels.

## Model Architecture
We employed the MobileNetV2 architecture to train our model. Utilizing the Adam optimizer with a learning rate of 0.0001, our model exhibits exceptional performance. Below is a summary of the model architecture:
![image/png](https://cdn-uploads.huggingface.co/production/uploads/65ad4ee914e6582c30cf70f1/Y2dOLjpD0HmNpnmP7xNqj.png)e metrics were achieved during training and validation:

- Training accuracy: 99.9%
- Validation accuracy: 99.5%

![image/png](https://cdn-uploads.huggingface.co/production/uploads/65ad4ee914e6582c30cf70f1/hnwotvIP_xV7rs-vEiQ-i.png)

## Gradio-based ML App
The project involves creating a Gradio app for fruits classification. It utilizes a pre-trained fruit classification model (model.h5) and class labels stored in a CSV file (classLabel1.csv). Users can upload images of fruits to the app, and it provides real-time predictions for the fruits's class label.Users can upload images of fruits to the app, and it provides real-time predictions for the fruits's class label. The code integrates Gradio, TensorFlow, and pandas to create an interactive and user-friendly interface for fruit classification.
Here's a step-by-step description of how the code sets up a Gradio app for fruit classification:

### 1. Importing Libraries:
The code starts by importing the necessary libraries:

```python
import gradio as gr
import tensorflow as tf
from tensorflow.keras.models import load_model
from tensorflow.keras.preprocessing import image
from tensorflow.keras.applications.mobilenet_v2 import preprocess_input
import pandas as pd
import numpy as np
```

### 2. Loading the Trained Model:
The code loads the pre-trained fruit classification model (model.h5) using TensorFlow's `load_model` function.

```python
model_path = 'model.h5'
model = load_model(model_path)
```

### 3. Loading Class Labels from CSV:
The code reads class labels from a CSV file (classLabels.csv) using the `pd.read_csv` function and converts them to a Python list.

```python
csv_file_path = 'classLabels.csv'
df_class_labels = pd.read_csv(csv_file_path)
class_labels = df_class_labels['ClassLabel'].tolist()
```

### 4. Defining the Prediction Function:
The `predict_fruit` function is defined to take an image as input, preprocess it, make predictions using the loaded model, and return the predicted class label.

```python
def predict_fruit(img):
    # Preprocess the image
    img_array = image.img_to_array(img)
    img_array = np.expand_dims(img_array, axis=0)
    img_array = preprocess_input(img_array)

    # Make predictions using the loaded model
    predictions = model.predict(img_array)

    # Custom decoding based on model's classes
    top_prediction_index = np.argmax(predictions)
    top_prediction = class_labels[top_prediction_index]

    return top_prediction
```

### 5. Creating Gradio Interface:
The `gr.Interface` class is used to create the Gradio interface:

```python
iface = gr.Interface(
    fn=predict_fruit,
    inputs=gr.Image(),
    outputs=gr.Textbox(),
    live=True,
    title='Fruit Classification App',
    description='Upload an image of a fruit to get the predicted class label.'
)
```

- `fn`: Specifies the prediction function.
- `inputs`: Set to `gr.Image()` to accept an image as input.
- `outputs`: Set to `gr.Textbox()` to display the predicted class label as text.
- `live`: Set to `True` for live updates.
- `title`: Sets the title of the Gradio interface.
- `description`: Provides a description of the interface.

### 6. Launching the Gradio App:
The `iface.launch()` method is called to launch the Gradio app, providing a link to the app.

```python
iface.launch()
```

### 7. Running the Code:
After running the code, users can click on the provided link to open the Gradio app in a new tab. The app allows users to upload an image of a fruit, and it provides real-time predictions for the fruit's class label.


### Sample Code (main.py)

```python
import gradio as gr
import tensorflow as tf
from tensorflow.keras.models import load_model
from tensorflow.keras.preprocessing import image
from tensorflow.keras.applications.mobilenet_v2 import preprocess_input
import pandas as pd
import numpy as np

# Load the pre-trained model
model_path = 'model.h5'
model = load_model(model_path)

# Load class labels from CSV
csv_file_path = 'classLabels.csv'
df_class_labels = pd.read_csv(csv_file_path)
class_labels = df_class_labels['ClassLabel'].tolist()

# Define prediction function
def predict_fruit(img):
    # Preprocess the image
    img_array = image.img_to_array(img)
    img_array = np.expand_dims(img_array, axis=0)
    img_array = preprocess_input(img_array)

    # Make predictions using the loaded model
    predictions = model.predict(img_array)

    # Custom decoding based on model's classes
    top_prediction_index = np.argmax(predictions)
    top_prediction = class_labels[top_prediction_index]

    return top_prediction

# Create Gradio interface
iface = gr.Interface(
    fn=predict_fruit,
    inputs=gr.Image(),
    outputs=gr.Textbox(),
    live=True,
    title='Fruit Classification App',
    description='Upload an image of a fruit to get the predicted class label.'
)

# Launch the Gradio app
iface.launch()
```

## Conclusion
This project demonstrates the seamless integration of deep learning techniques with user-friendly interfaces to solve real-world problems. By harnessing the power of convolutional neural networks and tools like Gradio, we can create efficient solutions for image classification tasks. The provided Gradio app empowers users to effortlessly classify fruits, showcasing the potential of AI in various domains. We invite you to explore our project repository and experience the magic of fruit classification with deep learning!


## Contributor
Asraf Ullah Rahat ( asrafullahrahat@gmail.com )