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 TensorFlow, Microsoft Cognitive Toolkit, Theano, or PlaidML. Designed to enable fast experimentation with deep neural networks, it focuses on being user-friendly, modular, and extensible.
Wikipedia
Keras contains numerous implementations of commonly used neural-network building blocks such as layers, objectives, activation functions, optimizers, 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

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:
- Import TensorFlow and Keras
- Build a model and config layers
- Train the model
- 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.compile(optimizer=tf.keras.optimizers.Adam(0.01),
loss='categorical_crossentropy',
metrics=['accuracy'])
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.