text_plain_output_1.png
from keras.layers import Dropout, Flatten, Dense, GlobalAveragePooling2D,Conv2D,MaxPooling2D,BatchNormalization

from keras.models import Sequential, Model

from keras.preprocessing import image

from keras.utils import np_utils

from sklearn.metrics import confusion_matrix

from sklearn.preprocessing import LabelEncoder

from tqdm import tqdm

import cv2

import matplotlib.pyplot as plt

import os

import os

import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)

import seaborn as sns

import numpy as np
import pandas as pd
import os
imagePaths = []
for dirname, _, filenames in os.walk('/kaggle/input'):
    for filename in filenames:
        if filename[-3:] == 'png':
            imagePaths.append(os.path.join(dirname, filename))

image = cv2.imread(imagePaths[0])

image.shape

Data = []
Target = []
resize = 224
for imagePath in tqdm(imagePaths):
    label = imagePath.split(os.path.sep)[-2]
    image = cv2.imread(imagePath)
    image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
    image = cv2.resize(image, (resize, resize)) / 255
    Data.append(image)
    Target.append(label)

df = pd.DataFrame(Target, columns=['Labels'])

encoder = LabelEncoder()
encoder.fit(Target)
encoded_Target = encoder.transform(Target)
encoded_Target = np_utils.to_categorical(encoded_Target)

encoder.classes_

X_train.shape

X_cv.shape

X_test.shape

img_width = img_height = 224
if K.image_data_format() == 'channels_first':
    input_shape = (3, img_width, img_height)
    X_train = X_train.reshape(X_train.shape[0], 3, img_width, img_height)
    X_cv = X_cv.reshape(X_cv.shape[0], 3, img_width, img_height)
    X_test = X_test.reshape(X_test.shape[0], 3, img_width, img_height)
else:
    input_shape = (img_width, img_height, 3)
    X_train = X_train.reshape(X_train.shape[0], img_width, img_height, 3)
    X_cv = X_cv.reshape(X_cv.shape[0], img_width, img_height, 3)
    X_test = X_test.reshape(X_test.shape[0], img_width, img_height, 3)

def plt_dynamic(x, vy, ty, ax, colors=['b']):
    pass

epoch = 25
batch = 32
num_classes = 3

model = Sequential()
model.add(Conv2D(32, kernel_size=(3, 3), activation='relu', input_shape=input_shape, kernel_initializer='he_normal'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Conv2D(64, kernel_size=(3, 3), activation='relu', kernel_initializer='he_normal'))
model.add(MaxPooling2D(pool_size=(3, 3)))
model.add(Conv2D(64, kernel_size=(3, 3), activation='relu', kernel_initializer='he_normal'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Flatten())
model.add(Dense(512, activation='relu', kernel_initializer='he_normal'))
model.add(Dropout(0.25))
model.add(Dense(256, activation='relu', kernel_initializer='he_normal'))
model.add(Dropout(0.4))
model.add(Dense(128, activation='relu', kernel_initializer='he_normal'))
model.add(Dropout(0.3))
model.add(BatchNormalization())
model.add(Dense(64, activation='relu', kernel_initializer='he_normal'))
model.add(Dropout(0.5))
model.add(Dense(num_classes, activation='softmax', kernel_initializer='glorot_normal'))
model.summary()

model.compile(loss='categorical_crossentropy', optimizer='Adam', metrics=['accuracy'])
his = model.fit(X_train, y_train, batch_size=batch, epochs=epoch, verbose=1, validation_data=(X_cv, y_cv))

#Plotting Train and Validation Loss
fig,ax=plt.subplots(1,1)
ax.set_xlabel('Epochs')
ax.set_ylabel('Binary Cross Entropy')

x=list(range(1,epoch+1))

vy=his.history['val_loss']
ty=his.history['loss']
plt_dynamic(x,vy,ty,ax)

score = model.evaluate(X_test, y_test, verbose=0)

y_pred = model.predict(X_test).round()

encoder.classes_

x = confusion_matrix(y_test.argmax(axis=1), y_pred.argmax(axis=1))
Cm_df = pd.DataFrame(x, index=encoder.classes_, columns=encoder.classes_)
sns.set(font_scale=1.5, color_codes=True, palette='deep')
sns.heatmap(Cm_df, annot=True, annot_kws={'size': 16}, fmt='d', cmap='YlGnBu')
plt.ylabel('True Label')
plt.xlabel('Predicted Label')
plt.title('Confusion Matrix')