Classifying Fruits and Vegetables with Machine Learning

A multiclass classification walkthrough with code

Code AI Blogs
CodeAI
2 min readAug 23, 2021

--

Photo by Yu Hosoi on Unsplash

Introduction

What’s the visual difference between Braeburn and Crimson Snow apples? What about Pink Lady and Granny Smith? If you’re like me and don’t know off the top of your head, here’s where machine learning can help.

My goal is to build a classifier that can predict what fruit or vegetable variety a food item is based on its image.

As with my previous articles on Pokémon and waste classification, I’ll do this using a convolutional neural network.

Data Source

I’ll be using this dataset from Kaggle:

It contains 90483 images of 131 fruits and vegetables, including different varieties of apples, tangelo, and different varieties of plums.

Setup

First things first, we’ll import the necessary Python libraries.

Now, we’ll take a look at some of the characteristics of our dataset as well as a sample image.

Note: I’ve uploaded the fruits-360 folder into a directory called data.

Results:

Sample image

Data Preprocessing

To prepare our dataset for training a machine learning model, we’ll set up image generators:

Training the Model

We’re now ready to train our machine learning model!

Following the general structure of a CNN, we’ll have convolutional layers with pooling layers in-between, and relu as our activation function.

Results

We can now take a look at the accuracy of our classifier during training:

As hoped, both training and testing accuracy increased with the number of epochs.

We’ve successfully trained a machine learning model to classify fruits and vegetables!

--

--