0
$\begingroup$
from keras.layers.core import Dropout
from tensorflow import keras
from keras.models import Sequential, load_model
from keras.layers import Dense, Flatten, BatchNormalization
from keras.layers import Conv2D, MaxPooling2D
from keras.optimizers import Adam
from tensorflow.keras.preprocessing.image import load_img, img_to_array
import tensorflow as tf
import matplotlib.pyplot as mp
import numpy as np 
import cv2 
import os
 
dir1 = r"E:\\Dataset\\Train"
dir2 = r"E:\\Dataset\\Test"
catg = ["Deepshika", "Kuldeep", "Lokesh", "Neelu", "ojasvi"]

dic = {
    "Deepshika" : 0,
    "Kuldeep"   : 1,
    "Lokesh"    : 2,
    "Neelu"     : 3, 
    "ojasvi"    : 4
}

train_data = [ ]
train_labels = [ ]


test_data = [ ]
test_labels = [ ]


def creat_train_dataset( ):
    
    for cat in catg :
        path = os.path.join(dir1, cat)
        for img in os.listdir(path):
            image = load_img(os.path.join(path, img),target_size= (120, 120) )
            image = img_to_array(image)
            image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

            train_data.append(image)
            train_labels.append(dic[cat])

def creat_test_dataset( ):
    
    for cat in catg :
        path = os.path.join(dir2, cat)
        for img in os.listdir(path):
            image = load_img(os.path.join(path, img),target_size= (120, 120) )
            image = img_to_array(image)
            image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

            test_data.append(image)
            test_labels.append(dic[cat])


creat_train_dataset( )
creat_test_dataset( )

# dataset generation 

x_train = np.array(train_data[0:150], dtype = 'float32')/255
y_train = np.array(train_labels[0:150], dtype = 'int') 
y_train = keras.utils.to_categorical(train_labels[0:150], 5)
print("x train shape: ", x_train.shape)

x_test = np.array(test_data[0:50], dtype = 'float32')/255 
y_test = np.array(test_labels[0:50], dtype = 'int') 
y_test = keras.utils.to_categorical(test_labels[0:50], 5)
print("x test shape: ", x_test.shape)

mp.imshow(x_train[121])
print(y_train[121])
mp.show( )

batch_size = 3
im_shape = (120, 120, 1)

x_train = x_train.reshape(x_train.shape[0], *im_shape)
x_test = x_test.reshape(x_test.shape[0], *im_shape)

print('x_train shape:' , x_train.shape)
print('x_test shape:' , x_test.shape)

print('y_train shape:' , y_train.shape)
print('y_test shape:' , y_test.shape)
#creating the architecture 

cnn_radheKrishna = Sequential()
cnn_radheKrishna.add(Conv2D(filters = 64, kernel_size = 5, activation = 'relu', input_shape = im_shape))
cnn_radheKrishna.add(MaxPooling2D(pool_size = 2))
cnn_radheKrishna.add(BatchNormalization( ))

cnn_radheKrishna.add(Conv2D(filters = 32, kernel_size = 3, activation = 'relu'))
cnn_radheKrishna.add(MaxPooling2D(pool_size = 2))
cnn_radheKrishna.add(BatchNormalization( ))

cnn_radheKrishna.add(Conv2D(filters = 16, kernel_size = 3, activation = 'relu'))
cnn_radheKrishna.add(MaxPooling2D(pool_size = 3))
cnn_radheKrishna.add(BatchNormalization( ))

cnn_radheKrishna.add(Dense(2048, activation = 'relu'))
cnn_radheKrishna.add(Dropout(0.5))


cnn_radheKrishna.add(Dense(1024, activation = 'relu'))
cnn_radheKrishna.add(Dropout(0.5))

cnn_radheKrishna.add(Dense(512, activation = 'relu'))
cnn_radheKrishna.add(Dense(256, activation = 'relu'))
cnn_radheKrishna.add(Dense(128, activation = 'relu'))
cnn_radheKrishna.add(Dense(64, activation = 'relu'))
cnn_radheKrishna.add(Dense(5, activation = 'softmax'))

optimiser = keras.optimizers.Adam(learning_rate= 0.0001)

cnn_radheKrishna.compile(optimizer = optimiser, loss = 'categorical_crossentropy', metrics=['accuracy'])

cnn_radheKrishna.summary( )

info = cnn_radheKrishna.fit(np.array(x_train), np.array(y_train), batch_size= 3, epochs= 100)

cnn_radheKrishna.save('hari.h5')

score = cnn_radheKrishna.evaluate(x_test, y_test)

print('test los {}'.format(score[0]))
print('test acc {}'.format(score[1]))

enter image description here

$\endgroup$
0
$\begingroup$

In case of image classification one of the important thing to remember while connecting Convolutional layer output to Dense layer is to make sure Flatten the output of the Convolutional layer then pass it to Dense layer. Just add following code snippets just before your 1st Dense layer containing 2048 neurons.

cnn_radheKrishna.add(BatchNormalization( ))

cnn_radheKrishna.add(Flatten( )) # As your import statement contains Flatten layer

cnn_radheKrishna.add(Dense(2048, activation = 'relu'))
```
$\endgroup$
8
  • $\begingroup$ thankyou very much for helping me out $\endgroup$ Aug 24 at 12:59
  • $\begingroup$ can you please tell me that when i am using same model for predicting using single image array then it is showing ValueError: Input 0 of layer sequential is incompatible with the layer: : expected min_ndim=4, found ndim=3, i have saved the trained model and loaded it and then used predict for one image $\endgroup$ Aug 24 at 13:36
  • $\begingroup$ test = load_model('hari.h5') x_test = x_test.reshape(-1, 120, 120, 1) y = test.predict(x_test[21]) so for this above error is coming $\endgroup$ Aug 24 at 13:59
  • $\begingroup$ Tensorflow expect input always in batch format even in prediction time too. So even if you want to pass single image from array of multiple images use like this y = test.predict(x_test[21:22]) $\endgroup$ Aug 24 at 15:03
  • $\begingroup$ If you load single image into numpy array make sure to reshape into batch format with shape of (1, 120, 120, 1) $\endgroup$ Aug 24 at 15:05

Not the answer you're looking for? Browse other questions tagged or ask your own question.