text_plain_output_1.png
from keras.layers import Input, Conv2D, MaxPooling2D, UpSampling2D, concatenate, Conv2DTranspose, BatchNormalization, Dropout, Lambda

from keras.models import Sequential, Model

from keras.regularizers import l2

from sklearn.utils import shuffle

from tensorflow.keras import Sequential

from tensorflow.keras import datasets, layers, models

from tensorflow.keras.callbacks import EarlyStopping,ReduceLROnPlateau

from tensorflow.keras.layers import Flatten, Dense,BatchNormalization,Dropout,Input

from tensorflow.keras.preprocessing.image import ImageDataGenerator

from tensorflow.keras.utils import to_categorical

import cv2

import matplotlib.pyplot as plt

import numpy as np

import os

seed = 42
np.random.seed = seed

labels = ['NORMAL', 'PNEUMONIA']
folders = ['train', 'test', 'val']
def load_images_from_directory(main_dirictory, foldername):
    total_labels = []
    images = []
    total_normal = 0
    total_pneumonia = 0
    path = os.path.join(main_dirictory, foldername)
    for lab in labels:
        full_path = os.path.join(path, lab)
        for image in os.listdir(full_path):
            img = cv2.imread(full_path + '/' + image)
            img = cv2.resize(img, (150, 150))
            images.append(img)
            if lab == 'NORMAL':
                label = 0
                total_normal += 1
            elif lab == 'PNEUMONIA':
                label = 1
                total_pneumonia += 1
            total_labels.append(label)
    return shuffle(images, total_labels, random_state=756349782)
def get_Label(number):
    labels = {0: 'NORMAL', 1: 'PNEUMONIA'}
    return labels[number]
def plot_predection(model_name):
    images = []
    count = 0
    for i, files in enumerate(val_images):
        img = cv2.resize(files, (150, 150))
        img = np.expand_dims(files, axis=0)
        feature = model_name.predict(img)
        predection = np.argmax(feature, axis=1)
        plt.xticks([])
        plt.yticks([])
        count += 1
        if count == 30:
            break
def freezing_layers(model_name):
    for layer in model_name.layers:
        layer.trainable = False

train_images = np.asarray(train_images, np.float32) / 255
train_labels = np.asarray(train_labels)

test_images = np.asarray(test_images, np.float32) / 255
test_labels = np.asarray(test_labels)

train_labels = to_categorical(train_labels, 2)
test_labels = to_categorical(test_labels, 2)

batch_size = 16
image_gen = ImageDataGenerator(shear_range=0.2, zoom_range=0.2, height_shift_range=0.2, width_shift_range=0.2, horizontal_flip=True, rotation_range=20)
test_data_gen = ImageDataGenerator()
val_data_gen = ImageDataGenerator()
train = image_gen.flow(train_images, train_labels, shuffle=True, batch_size=batch_size)
test = test_data_gen.flow(test_images, test_labels, shuffle=True, batch_size=batch_size)

cnn_model = Sequential()
cnn_model = models.Sequential()
cnn_model.add(layers.Conv2D(300, (5, 5), kernel_regularizer=l2(5e-05), padding='Same', activation='relu', input_shape=(150, 150, 3)))
cnn_model.add(BatchNormalization())
cnn_model.add(layers.MaxPooling2D(2, 2))
cnn_model.add(layers.Conv2D(200, (3, 3), kernel_regularizer=l2(5e-05), padding='same', activation='relu'))
cnn_model.add(BatchNormalization())
cnn_model.add(Dropout(0.2))
cnn_model.add(layers.MaxPooling2D(2, 2))
cnn_model.add(layers.Conv2D(100, (3, 3), kernel_regularizer=l2(5e-05), padding='same', activation='relu'))
cnn_model.add(BatchNormalization())
cnn_model.add(layers.MaxPooling2D(2, 2))
cnn_model.add(layers.Conv2D(64, (3, 3), kernel_regularizer=l2(5e-05), padding='same', activation='relu'))
cnn_model.add(BatchNormalization())
cnn_model.add(Dropout(0.2))
cnn_model.add(layers.MaxPooling2D(2, 2))

cnn_model.add(layers.Flatten())
cnn_model.add(layers.Dense(100, activation='relu'))
cnn_model.add(BatchNormalization())
cnn_model.add(layers.Dense(64, activation='relu'))
cnn_model.add(BatchNormalization())
cnn_model.add(Dropout(0.3))
cnn_model.add(layers.Dense(2, activation='sigmoid'))
cnn_model.summary()

cnn_model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])

from tensorflow.keras.callbacks import EarlyStopping, ReduceLROnPlateau
early = EarlyStopping(monitor='loss', mode='min', min_delta=0, patience=10, verbose=1, restore_best_weights=True)
learning_rate_reduction = ReduceLROnPlateau(monitor='loss', patience=2, verbose=1, factor=0.3, min_lr=1e-06)
callbacks_list = [early, learning_rate_reduction]

n_training_samples = len(train)
n_validation_samples = len(test)
history = cnn_model.fit(train, epochs=50, validation_data=test, validation_steps=n_validation_samples // batch_size, shuffle=True, callbacks=callbacks_list)

score, acc = cnn_model.evaluate(test, batch_size=batch_size)
print('Test score:', score)
print('Test accuracy:', acc)