Hashwanth Gogineni's other Models Reports

Major Concepts

 

Sign-Up/Login to access Several ML Models and also Deploy & Monetize your own ML solutions for free

Models Home » Domain Usecases » Others » Stale Food Detection

Stale Food Detection

Models Status

Model Overview

Stale Food


The behaviour of eating leftover meals the next day is widespread in most households. Without giving it a second thought, the meal has gone stale. 


We end up making a little extra veggie or rice and storing it in the fridge for 1 or 2 days later use. I'm not talking about preservative-laden foods or junk food; I'm talking about home-cooked meals that might upset the stomach if eaten the next day. Eating stale food or reheating it repeatedly is bad for your health, and this way of living may be highly dangerous in the long term.


 


Life is too hectic, and there is seldom enough time to prepare a healthy dinner regularly. We cook an extra serving of vegetables to take to work the next day because we are short on time in the morning. Even morning vegetables are eaten late at night. If the meal smells good, we will gobble it down. Out of respect, some individuals do not want to toss food. It is not even considered a harmful habit to eat stale food. Stale or reheated food not only delights your taste buds but can also make you sick. If we continue to eat stale food, we will confront the following issues:


Home for Bacteria:


We chill the meal before putting it in the fridge after being cooked. This produces bacteria and germs, which ferment the food and create various health problems.


High Chance of Food Poisoning:


Food sickness in the stomach is more likely when you eat stale food. 


This is because we keep the meal in the fridge for several hours after being cooked. 


Food spoils due to the growth of microorganisms, especially during the summer, resulting in food poisoning. 


We frequently blame junk food for creating gastrointestinal problems. 


However, eating stale food daily might make you unwell.


Zero nutritional value:


Many health experts recommend that people consume fresh food, i.e., create fresh food and eat fresh food. 


The salad should be sliced as soon as possible before serving. 


This can cause bad digestion and, after a while, has little nutritional benefit.


Liver issues:


Nobody can conceive how the wonderful rajma, Pao bhaji, or shahi paneer they ate the day before may impact their liver the next day. 


The meal that is left over is more filling than it was before, making digestion more challenging. 


At the same time, the germs in our meals might destroy our liver.


 


Why Stale Produce Detection?


The project can be helpful for food companies to detect stale or rotten food products.


Dataset


The dataset includes two classes, i.e., "Healthy" and "Rotten." Each class includes 5,894 images in each of the classes, making up 11,788 images.


The dataset includes multiple fresh and rotten fruits images.



MobileNet


The MobileNet model, as its name implies, is intended for usage in mobile applications and is TensorFlow's first mobile computer vision model.


MobileNet uses Depthwise separable convolutions. Compared to a network with normal convolutions of the same depth in the nets, it dramatically reduces the number of parameters. As a consequence, lightweight deep neural networks are created.


Two procedures are used to create a depthwise separable convolution.


1)Depthwise convolution.


2)Pointwise convolution.


MobileNet is a CNN class that Google open-sourced, and it provides us with an ideal starting point for training our ultra-small and ultra-fast classifiers.

Understanding Code
First, let us import the required libraries for our project.


import os
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from pathlib import Path
from tensorflow.keras.preprocessing import image_dataset_from_directory
import tensorflow as tf
import cv2
from keras.layers import Input, Lambda, Dense, Flatten,GlobalAveragePooling2D, Dropout, Activation
from keras.models import Model
from keras.preprocessing.image import ImageDataGenerator
from keras.models import Sequential
from tensorflow.python.keras.preprocessing.image import ImageDataGenerator
from sklearn.metrics import classification_report, log_loss, accuracy_score


Now, let us load the data into our system and convert the data into a dataframe.


image_dir = Path('/content/sample_data/data/train')

# Get filepaths and labels
filepaths = list(image_dir.glob(r'**/*.png'))
labels = list(map(lambda x: os.path.split(os.path.split(x)[0])[1], filepaths))

filepaths = pd.Series(filepaths, name='Filepaths').astype(str)
labels = pd.Series(labels, name='Labels')

# Concatenate filepaths and labels
image_df = pd.concat([filepaths, labels], axis=1)

# Shuffle the DataFrame and reset index
image_df = image_df.sample(frac=1).reset_index(drop = True)

# Show the result
image_df.head()

 As you can see, we extracted data from the data's directory and concatenated 'filepaths' and 'labels' into a dataframe.

Let us also split the dataframe for testing and training purposes.


# Separating train and test data
from sklearn.model_selection import train_test_split

train_df, test_df = train_test_split(image_df, train_size=0.85, shuffle=True, random_state=1)

As you can see, I used the "train_test_split" function to split the dataframe.


train_datagen = ImageDataGenerator(rescale=1./255, validation_split=0.15)

test_datagen = ImageDataGenerator(rescale=1./255)

As you can see, I used the 'ImageDataGenerator' function for data augmentation purposes.


train_images = train_datagen.flow_from_dataframe(
dataframe=train_df,
x_col='Filepaths',
y_col='Labels',
target_size=(224, 224),
color_mode='rgb',
class_mode='categorical',
batch_size=64,
shuffle=True,
seed=42,
subset='training'
)

val_images = train_datagen.flow_from_dataframe(
dataframe=train_df,
x_col='Filepaths',
y_col='Labels',
target_size=(224, 224),
color_mode='rgb',
class_mode='categorical',
batch_size=64,
shuffle=True,
seed=42,
subset='validation'
)

test_images = test_datagen.flow_from_dataframe(
dataframe=test_df,
x_col='Filepaths',
y_col='Labels',
target_size=(224, 224),
color_mode='rgb',
class_mode='categorical',
batch_size=32,
shuffle=False
)

Also, I loaded train and test data using the 'flow_from_dataframe' function into the kernel.

Next, let us get into the modelling part of the project.


from tensorflow.keras.applications import MobileNetV2
mblnet = MobileNetV2(include_top=False, weights='imagenet', input_shape=(224,224,3))
mblnet.summary()

for layer in mblnet.layers:
layer.trainable=False

So, I chose the 'MobileNet' model to get the best out of our data.
I used 'imagenet' as weights for our model.


x = Flatten()(mblnet.output)
x = Dense(512,activation='relu')(x)
x = Dense(512,activation='relu')(x)
prediction = Dense(2,activation='softmax')(x)
model = Model(inputs=mblnet.input, outputs=prediction)
model.summary()

I also added a few extra layers to the model for efficient results.

As our model is ready, let us now compile our model.


model.compile(optimizer='adam',loss='categorical_crossentropy',metrics=['accuracy'])

callback = tf.keras.callbacks.EarlyStopping(monitor='accuracy', patience=2)


Now let us fit our data into our model.


history = model.fit_generator(train_images, validation_data=val_images, epochs=25, callbacks=callback)


Finally, let us have a look at our model's performance.


 get_acc = history.history['accuracy']
value_acc = history.history['val_accuracy']
get_loss = history.history['loss']
validation_loss = history.history['val_loss']

epochs = range(len(get_acc))
plt.plot(epochs, get_acc, 'r', label='Accuracy of Training data')
plt.plot(epochs, value_acc, 'b', label='Accuracy of Validation data')
plt.title('Training vs validation accuracy')
plt.legend(loc=0)
plt.figure()
plt.show()


# Classification Report

from sklearn.metrics import classification_report

test_labels=test_images.classes
predictions=model.predict_generator(test_images, verbose=1)
y_pred = np.argmax(predictions, axis=-1)
print(classification_report(test_labels, y_pred))


Here in the classification report '0' represents 'Healthy' and '1' represents 'Rotten' 



Thank you for your time.










0 comments