text_plain_output_1.png
from keras.preprocessing.image import ImageDataGenerator

from sklearn.metrics import confusion_matrix,classification_report

import itertools

import keras

import matplotlib.image as img

import matplotlib.pyplot as plt

import numpy as np

import pathlib

path = pathlib.Path('/kaggle/input/5-flower-types-classification-dataset/flower_images')

lilly = list(path.glob('Lilly/*'))[:1000]
lotus = list(path.glob('Lotus/*'))[:1000]
orchid = list(path.glob('Orchid/*'))[:1000]
sunflower = list(path.glob('Sunflower/*'))[:1000]
tulip = list(path.glob('Tulip/*'))[:1000]

data = {'lilly': lilly, 'lotus': lotus, 'orchid': orchid, 'sunflower': sunflower, 'tulip': tulip}
flower_labels = {k: v for k, v in enumerate(data.keys())}

fig, ax = plt.subplots(5,5, figsize=(30,25))
fig.suptitle('Flower Category',color='magenta',fontsize=40)
for i in range(5):
    for j in range(5):
        image = img.imread(data.get(flower_labels.get(i))[j])
        ax[i, j].imshow(image)
        ax[i, j].set_title(flower_labels.get(i))

train_gen = ImageDataGenerator(rotation_range=10, rescale=1.0 / 255, width_shift_range=0.1, height_shift_range=0.1, horizontal_flip=True, vertical_flip=False, zoom_range=0.1, shear_range=0.1, brightness_range=[0.8, 1.2], fill_mode='nearest', validation_split=0.2)
train_data = train_gen.flow_from_directory('/kaggle/input/5-flower-types-classification-dataset/flower_images', target_size=(224, 224), batch_size=32, class_mode='categorical', shuffle=True, subset='training')
test_data = train_gen.flow_from_directory('/kaggle/input/5-flower-types-classification-dataset/flower_images', target_size=(224, 224), batch_size=1, shuffle=False, subset='validation')

def plot(c):
    pass

cnn = keras.models.Sequential()
cnn.add(keras.layers.Conv2D(filters=32, kernel_size=3, padding='valid', activation='relu', input_shape=(224, 224, 3)))
cnn.add(keras.layers.MaxPool2D(pool_size=2, strides=2))
cnn.add(keras.layers.Flatten())
cnn.add(keras.layers.Dense(45, activation='relu'))
cnn.add(keras.layers.Dense(15, activation='relu'))
cnn.add(keras.layers.Dropout(rate=0.1, seed=100))
cnn.add(keras.layers.Dense(units=5, activation='sigmoid'))

cnn.summary()

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

cnn.fit(train_data, epochs=20, validation_data=test_data, shuffle=True, callbacks=keras.callbacks.EarlyStopping(monitor='val_loss', patience=10))

y_pred = cnn.predict(test_data)
main_y_pred = np.argmax(y_pred, axis=1)

test_steps_per_epoch = np.math.ceil(test_data.samples / test_data.batch_size)
predictions = cnn.predict_generator(test_data, steps=test_steps_per_epoch)
predicted_classes = np.argmax(predictions, axis=1)

true_classes = test_data.classes
class_labels = list(test_data.class_indices.keys())
report = classification_report(true_classes, predicted_classes, target_names=class_labels)

cm = confusion_matrix(test_data.classes, predicted_classes)
d1 = test_data.class_indices
classes = list(d1.keys())
cmap = plt.cm.YlGnBu
plt.figure(figsize=(6, 6))
plt.imshow(cm, interpolation='nearest', cmap=cmap)
plt.title('Confusion Matrix')
plt.colorbar(shrink=True)
tick_marks = np.arange(len(classes))
plt.xticks(tick_marks, classes, rotation=90)
plt.yticks(tick_marks, classes)
thresh = cm.max() / 2.0
for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
    plt.text(j, i, cm[i, j], horizontalalignment='center', color='aqua' if cm[i, j] > thresh else 'red')
plt.tight_layout()
plt.ylabel('True Label')
plt.xlabel('Predicted Label')
cm