A.I, Data and Software Engineering

A.I in agriculture – Fruit Grading with Keras (part 2)


In part 1, we introduced fruit classification with pure python implementation. In this part, we will use the Keras library instead.

What is Keras

Keras is an open-sourceneural-network library written in Python. It is capable of running on top of TensorFlowMicrosoft Cognitive ToolkitTheano, or PlaidML. Designed to enable fast experimentation with deep neural networks, it focuses on being user-friendly, modular, and extensible. 


Keras contains numerous implementations of commonly used neural-network building blocks such as layers, objectivesactivation functionsoptimizers, and a host of tools to make working with image and text data easier.  If you compare this to part 1, you will find the implementation with Keras much more simple and faster.

Data and features

Apple grading

We need relevant data to build the fruit grading model. As shown in Fig 1, the data of fruit can include colours, shapes, weight, etc. Also, we need data with labels. It means that given an apple in the sample set, we should know its grade, e.g grade 1 or 2, or 3.

There are several techniques to grade fruit. For example, if we want to identify green or ripped fruits, we can use a computer vision approach, in which photos of them are the input data (this paper). Sometimes, we want to sort fruit based on sizes and weight, then shapes and weights will be used as input data.

Similar to previous articles, we will use generated data. But it does not affect the application of it. Namely, the approach should also work with real data.

Implementation with Keras

Keras is convenient for building a deep learning model. Here are some steps:

  1. Import TensorFlow and Keras
  2. Build a model and config layers
  3. Train the model
  4. Evaluate the model

Below, we show some code snippet for each step.

#1 Import
from __future__ import absolute_import, division, print_function, unicode_literals
import tensorflow as tf
from tensorflow import keras
#2 Build a sequential model
from tensorflow.keras import layers
model = tf.keras.Sequential()
# Adds a densely-connected layer with 64 units to the model:
model.add(layers.Dense(64, activation='relu'))
# 3 Build and Train
model.fit(data, labels, epochs=10, batch_size=32)
# 4 Evaluate
model.evaluate(data, labels, batch_size=32)

full example code in jupyter

This jupyter notebook is implemented on Google Colab. We also skipped the output (7000 epochs) by using the option “verbose=0” when training.

Scroll down for more related posts.

Add comment


A.I, Data and Software Engineering

PetaMinds focuses on developing the coolest topics in data science, A.I, and programming, and make them so digestible for everyone to learn and create amazing applications in a short time.