0% found this document useful (0 votes)
11 views11 pages

Deep Neural Network for Image Classification

The document outlines a program to implement a deep neural network for a classification task using TensorFlow and Keras. It includes code for data preparation, model architecture using MobileNet, training, and evaluation of the model on a flower dataset with two classes. The model's performance is tracked through accuracy and loss metrics over several epochs.

Uploaded by

slakshmi.epcet
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views11 pages

Deep Neural Network for Image Classification

The document outlines a program to implement a deep neural network for a classification task using TensorFlow and Keras. It includes code for data preparation, model architecture using MobileNet, training, and evaluation of the model on a flower dataset with two classes. The model's performance is tracked through accuracy and loss metrics over several epochs.

Uploaded by

slakshmi.epcet
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Program-2

Write a program to demonstrate the working of a deep


neural network for classification task.

September 15, 2025

[13]: import sys


import os
from [Link] import Sequential
from [Link] import Dense, Conv2D , MaxPool2D , Flatten , Dropout
from [Link] import Adam
from [Link] import *
from [Link] import *
from [Link] import *
from [Link] import Model, Sequential, load_model
from [Link] import ImageDataGenerator
from [Link] import ModelCheckpoint, EarlyStopping
from [Link] import backend as k
from [Link] import classification_report,confusion_matrix
import tensorflow as tf
from [Link] import Activation
from [Link] import MobileNetV2
import [Link]
from [Link] import Adam, SGD
from [Link] import regularizers
from [Link] import BatchNormalization
from [Link] import plot_model
import cv2
import numpy as np
import seaborn as sns
from matplotlib.font_manager import FontProperties
import [Link] as plt
import seaborn as sns
import matplotlib as mpl
[Link]['[Link]'] = 80
import [Link] as plt
import seaborn as sns

[14]: path = '/Users/ssmie/OneDrive/Desktop/Flower/combination/class/'

1
[15]: train_path = '/Users/ssmie/OneDrive/Desktop/Flower/combination/class/train'
test_path = '/Users/ssmie/OneDrive/Desktop/Flower/combination/class/test'
train_flc1_dir = f'{train_path}class1/'
train_flc0_dir = f'{train_path}class0/'
test_flc1_dir = f'{test_path}class1/'
test_flc0_dir = f'{test_path}class0/'

[16]: print ('Training set Classes', len([Link](train_path)))


print ('Test set Classes', len([Link](test_path)))

Training set Classes 2


Test set Classes 2

[17]: import os
print([Link]('/Users/ssmie/OneDrive/Desktop/Flower/combination/class/'))

['test', 'train']

[18]: seed = 9
[Link](seed=seed)
[Link].set_seed(seed=seed)

# hyper parameters for model


nb_classes = 2
based_model_last_block_layer_number = 86
img_width, img_height = 150, 150
batch_size = 128 # try 4, 8, 16, 32, 64, 128, 256 dependent on CPU/GPU memory␣
,→capacity (powers of 2 values).

learn_rate = 1e-4 # sgd learning rate


momentum = .9 # sgd momentum to avoid local minimum
transformation_ratio = .2 # how aggressive will be the data augmentation/
,→transformation

[19]: data_dir = '/Users/ssmie/OneDrive/Desktop/Flower/combination/class/'


train_data_dir = [Link]('/Users/ssmie/OneDrive/Desktop/Flower/
,→combination/class/train') # Inside, each class should have it's own folder
test_data_dir = [Link]('/Users/ssmie/OneDrive/Desktop/Flower/
,→combination/class/test') # each class should have it's own folder
model_path = '/Users/ssmie/OneDrive/Desktop/Flower/combination/class/'

[20]: train_datagen = ImageDataGenerator(rescale=1. / 255,


shear_range=transformation_ratio,
zoom_range=transformation_ratio,
rotation_range=20,
width_shift_range=transformation_ratio,
height_shift_range=transformation_ratio,
cval=transformation_ratio,
horizontal_flip=True,

2
vertical_flip=True)

test_datagen = ImageDataGenerator(rescale=1. / 255)

train_generator = train_datagen.flow_from_directory(train_data_dir,
target_size=(img_width,␣
,→img_height),

batch_size=batch_size,
class_mode='categorical')
labels = (train_generator.class_indices)
print(labels)

test_generator = test_datagen.flow_from_directory(test_data_dir,

,→target_size=(img_width, img_height),


,→batch_size=batch_size,


,→class_mode='categorical')

Found 59 images belonging to 2 classes.


{'class0': 0, 'class1': 1}
Found 15 images belonging to 2 classes.

[21]: img_width, img_height = 224, 224

[22]: train_data_dir = '/Users/ssmie/OneDrive/Desktop/Flower/combination/class/train'


test_data_dir = '/Users/ssmie/OneDrive/Desktop/Flower/combination/class/test'

nb_train_samples =59
nb_test_samples = 15
epochs = 10
batch_size = 32

[23]: if k.image_data_format() == 'channels_first':


input_shape = (3, img_width, img_height)
else:
input_shape = (img_width, img_height, 3)

[24]: kernel_size = (2, 2)


n_classes = 2 # Specify number of output categories
filters = 32 # Specify number of filters per layer

[25]: data_shape = (224, 224, 3)

[26]: base_model = [Link](include_top = False,␣


,→input_shape=(224,224,3))

3
new_model = Sequential()
new_model.add(base_model)
new_model.add(Conv2D(32, (2, 2), input_shape=input_shape))
new_model.add(BatchNormalization())
new_model.add(MaxPooling2D(pool_size=(2, 2)))
new_model.add([Link].GlobalAveragePooling2D())
new_model.add(Dense(256))
new_model.add(Activation ('relu'))
new_model.add(Dropout(0.075))
new_model.add(Dense(1))
new_model.add(Activation('sigmoid'))
new_model.compile(optimizer=RMSprop(lr=0.001), loss = 'binary_crossentropy',␣
,→metrics = ['accuracy'])

new_model.summary()

WARNING:absl:`lr` is deprecated in Keras optimizer, please use `learning_rate`


or use the legacy optimizer, e.g.,[Link].
Model: "sequential"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
mobilenet_1.00_224 (Functi (None, 7, 7, 1024) 3228864
onal)

conv2d (Conv2D) (None, 6, 6, 32) 131104

batch_normalization (Batch (None, 6, 6, 32) 128


Normalization)

max_pooling2d (MaxPooling2 (None, 3, 3, 32) 0


D)

global_average_pooling2d ( (None, 32) 0


GlobalAveragePooling2D)

dense (Dense) (None, 256) 8448

activation (Activation) (None, 256) 0

dropout (Dropout) (None, 256) 0

dense_1 (Dense) (None, 1) 257

activation_1 (Activation) (None, 1) 0

=================================================================
Total params: 3368801 (12.85 MB)

4
Trainable params: 3346849 (12.77 MB)
Non-trainable params: 21952 (85.75 KB)
_________________________________________________________________

[27]: train_datagen = ImageDataGenerator(


rescale=1. / 255,
shear_range=0.2,
zoom_range=0.2,
horizontal_flip=True)

test_datagen = ImageDataGenerator(rescale=1. / 255)

train_generator = train_datagen.flow_from_directory(
train_data_dir,
target_size=(img_width, img_height),
batch_size=batch_size,
class_mode='binary')

validation_generator = test_datagen.flow_from_directory(
test_data_dir,
target_size=(img_width, img_height),
batch_size=batch_size,
class_mode='binary')

new_model.fit_generator(
train_generator,
steps_per_epoch=nb_train_samples // batch_size,
epochs=epochs,
validation_data=validation_generator,
validation_steps=nb_test_samples // batch_size)

Found 59 images belonging to 2 classes.


Found 15 images belonging to 2 classes.
C:\Users\ssmie\AppData\Local\Temp\ipykernel_19520\[Link]: UserWarning:
`Model.fit_generator` is deprecated and will be removed in a future version.
Please use `[Link]`, which supports generators.
new_model.fit_generator(
Epoch 1/10
1/1 [==============================] - 35s 35s/step - loss: 0.6625 - accuracy:
0.6562
Epoch 2/10
1/1 [==============================] - 6s 6s/step - loss: 0.6142 - accuracy:
0.7500
Epoch 3/10
1/1 [==============================] - 6s 6s/step - loss: 0.4259 - accuracy:
0.8750
Epoch 4/10

5
1/1 [==============================] - 5s 5s/step - loss: 0.2669 - accuracy:
0.9259
Epoch 5/10
1/1 [==============================] - 6s 6s/step - loss: 0.2047 - accuracy:
0.9688
Epoch 6/10
1/1 [==============================] - 5s 5s/step - loss: 0.1724 - accuracy:
0.9630
Epoch 7/10
1/1 [==============================] - 6s 6s/step - loss: 0.1601 - accuracy:
0.9688
Epoch 8/10
1/1 [==============================] - 6s 6s/step - loss: 0.1698 - accuracy:
0.9688
Epoch 9/10
1/1 [==============================] - 5s 5s/step - loss: 0.0825 - accuracy:
1.0000
Epoch 10/10
1/1 [==============================] - 6s 6s/step - loss: 0.1127 - accuracy:
0.9688

[27]: <[Link] at 0x14acc449b40>

[28]: history = new_model.[Link]


for key in [Link]():
print(key)

loss
accuracy

[29]: font = FontProperties()


font.set_family('serif')
font.set_name('Times New Roman')
font.set_style('oblique')
font.set_style('normal')

[Link](figsize=(5,3))
fontsize = 12

[Link](history["accuracy"],marker="o",color = 'teal')
[Link](history['loss'],marker=".",color = 'black')
[Link]("Model Accuracy",fontproperties=font,fontsize=16)
[Link]("Accuracy / Epoch",fontproperties=font,fontsize=16)
[Link]("Epoch",fontproperties=font,fontsize=16)
[Link](["Accuracy","Loss"],loc = 'best')
[Link]()

6
plt.minorticks_on()
[Link](fontsize=fontsize)
[Link](fontsize=fontsize)
[Link]()

[30]: new_model.evaluate(train_generator)

2/2 [==============================] - 5s 865ms/step - loss: 0.3066 - accuracy:


0.9153

[30]: [0.3065969944000244, 0.9152542352676392]

[31]: STEP_SIZE_TEST=train_generator.n//train_generator.batch_size
validation_generator.reset()
preds = new_model.predict(train_generator,
verbose=1)

2/2 [==============================] - 6s 1s/step

[32]: results = new_model.evaluate(train_generator)

2/2 [==============================] - 3s 1s/step - loss: 0.4356 - accuracy:


0.8814

[33]: pred = new_model.predict(train_generator)


pred[:4,:]

2/2 [==============================] - 3s 1s/step

7
[33]: array([[0.99998546],
[0.9999459 ],
[0.02316042],
[0.96236557]], dtype=float32)

[34]: pred = new_model.predict(train_generator)


print(new_model.evaluate(train_generator))

2/2 [==============================] - 3s 1s/step


2/2 [==============================] - 3s 1s/step - loss: 0.3860 - accuracy:
0.8814
[0.3860180377960205, 0.8813559412956238]

[35]: import [Link] as plt


(new_model.predict(train_generator) > 0.5).astype("int32")

2/2 [==============================] - 3s 1s/step

[35]: array([[1],
[1],
[0],
[1],
[1],
[1],
[1],
[0],
[1],
[1],
[0],
[1],
[1],
[1],
[1],
[0],
[1],
[1],
[1],
[1],
[1],
[0],
[0],
[1],
[0],
[0],
[1],
[0],
[0],
[0],

8
[1],
[0],
[1],
[1],
[1],
[1],
[1],
[1],
[0],
[1],
[1],
[0],
[1],
[1],
[0],
[0],
[1],
[1],
[1],
[0],
[0],
[1],
[0],
[0],
[1],
[1],
[1],
[1],
[1]])

[36]: [Link](new_model.predict(train_generator), axis=-1)

2/2 [==============================] - 3s 1s/step

[36]: array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], dtype=int64)

[37]: labels = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1,␣


,→1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1]

predictions = [1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0,␣


,→1, 1,0, 0, 1, 1, 1, 0, 1, 0, 1, 1]

[38]: from [Link] import recall_score


print(recall_score(labels,predictions))

0.75

9
[39]: from [Link] import accuracy_score
print(accuracy_score(labels , predictions)*100)

64.70588235294117

[40]: from [Link] import precision_score


print(precision_score(labels,predictions)*100)

80.76923076923077

[41]: from [Link] import f1_score


print(f1_score(labels, predictions))

0.7777777777777779

[42]: fontsize = 16
fig, ax = [Link](figsize=(4, 4))
confusion = confusion_matrix(labels, predictions)
FN = confusion[1][0]
TN = confusion[0][0]
TP = confusion[1][1]
FP = confusion[0][1]
[Link].set_label_position("top")

plt.tight_layout()
[Link](fontsize=fontsize)
[Link](fontsize=fontsize)
[Link](confusion , annot=True,fmt='d',cmap="YlGnBu")

[Link]('Predicted Flower : Class:0',fontsize=16)


[Link]('Observed Flower : Class:1',fontsize=16)

[42]: Text(7.3055555555555625, 0.5, 'Observed Flower : Class:1')

10
[ ]:

11

You might also like