0
$\begingroup$

I am trying to build an image classification model to classify whether Thistle Caterpillar is present in an image or not. The classification is a single label classification. The dataset and the code for the same is attached below. The problem is that using the sequential model created I am getting a validation accuracy of zero.

DATASET LINK : https://www.kaggle.com/drravirsaxena/pest-identification

# Dimension of resized image
DEFAULT_IMAGE_SIZE = tuple((256, 256))

# Number of images used to train the model
N_IMAGES = 1000

# Path to the dataset folder
root_dir = '/content/drive/MyDrive/Thistle_Caterpillar '

train_dir = os.path.join(root_dir, 'train')
val_dir = os.path.join(root_dir, 'val')
def convert_image_to_array(image_dir):
    try:
        image = cv2.imread(image_dir)
        if image is not None:
            image = cv2.resize(image, DEFAULT_IMAGE_SIZE)   
            return img_to_array(image)
        else:
            return np.array([])
    except Exception as e:
        print(f"Error : {e}")
        return None
image_list, label_list = [], []

try:
    print("[INFO] Loading images ...")
    thistle_caterpillar_folder_list = listdir(train_dir)

    for thistle_caterpillar_folder in thistle_caterpillar_folder_list:
        print(f"[INFO] Processing {thistle_caterpillar_folder} ...")
        thistle_caterpillar_image_list = listdir(f"{train_dir}/{thistle_caterpillar_folder}")

        for image in thistle_caterpillar_image_list[:N_IMAGES]:
            image_directory = f"{train_dir}/{thistle_caterpillar_folder}/{image}"
            if image_directory.endswith(".jpeg")==True or image_directory.endswith(".JPEG")==True:
                image_list.append(convert_image_to_array(image_directory))
                label_list.append(thistle_caterpillar_folder)

    print("[INFO] Image loading completed")  
except Exception as e:
    print(f"Error : {e}")

# Transform the loaded training image data into numpy array
np_image_list = np.array(image_list, dtype=np.float16) / 225.0
print()

# Check the number of images loaded for training
image_len = len(image_list)
print(f"Total number of images: {image_len}")
label_binarizer = LabelBinarizer()
image_labels = label_binarizer.fit_transform(label_list)

pickle.dump(label_binarizer,open('/content/drive/MyDrive/Thistle_Caterpillar /thistle_caterpillar.pkl', 'wb'))
n_classes = len(label_binarizer.classes_)

print("Total number of classes: ", n_classes)
augment = ImageDataGenerator(rotation_range=25, width_shift_range=0.1,
                             height_shift_range=0.1, shear_range=0.2, 
                             zoom_range=0.2, horizontal_flip=True, 
                             fill_mode="nearest")
print("[INFO] Splitting data to train and test...")
x_train, x_test, y_train, y_test = train_test_split(np_image_list, image_labels, test_size=0.2, random_state = 42)
EPOCHS = 25
STEPS = 100
LR = 1e-3
BATCH_SIZE = 64
WIDTH = 256
HEIGHT = 256
DEPTH = 3
model = Sequential()
inputShape = (HEIGHT, WIDTH, DEPTH)
chanDim = -1

if K.image_data_format() == "channels_first":
    inputShape = (DEPTH, HEIGHT, WIDTH)
    chanDim = 1

model.add(Conv2D(32, (3, 3), padding="same",input_shape=inputShape))
model.add(Activation("sigmoid"))
model.add(BatchNormalization(axis=chanDim))
model.add(MaxPooling2D(pool_size=(3, 3)))
model.add(Dropout(0.25))
model.add(Conv2D(64, (3, 3), padding="same"))
model.add(Activation("sigmoid"))
model.add(BatchNormalization(axis=chanDim))
model.add(Conv2D(64, (3, 3), padding="same"))
model.add(Activation("sigmoid"))
model.add(BatchNormalization(axis=chanDim))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
model.add(Conv2D(128, (3, 3), padding="same"))
model.add(Activation("sigmoid"))
model.add(BatchNormalization(axis=chanDim))
model.add(Conv2D(128, (3, 3), padding="same"))
model.add(Activation("sigmoid"))
model.add(BatchNormalization(axis=chanDim))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(1024))
model.add(Activation("sigmoid"))
model.add(BatchNormalization())
model.add(Dropout(0.5))
model.add(Dense(n_classes))
model.add(Activation("softmax"))

model.summary()
# Initialize optimizer
opt = Adam(lr=LR, decay=LR / EPOCHS)

# Compile model
model.compile(loss="sparse_categorical_crossentropy", optimizer=opt, metrics=["accuracy"])

# Train model
print("[INFO] Training network...")
history = model.fit_generator(augment.flow(x_train, y_train, batch_size=BATCH_SIZE),
                              validation_data=(x_test, y_test),
                              steps_per_epoch=len(x_train) // BATCH_SIZE,
                              epochs=EPOCHS, 
                              verbose=1)
```
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.