<jupyter_start><jupyter_text>Importing Libraries<jupyter_code># import the libraries as shown below

from tensorflow.keras.layers import Input, Lambda, Dense, Flatten,Conv2D
from tensorflow.keras.models import Model
from tensorflow.keras.applications.vgg19 import VGG19
from tensorflow.keras.applications.resnet50 import preprocess_input
from tensorflow.keras.preprocessing import image
from tensorflow.keras.preprocessing.image import ImageDataGenerator,load_img
from tensorflow.keras.models import Sequential
import numpy as np
from glob import glob
import matplotlib.pyplot as plt
# re-size all the images to this
IMAGE_SIZE = [224, 224]

train_path = "E:\Malaria Dataset\Dataset\Train"
valid_path = "E:\Malaria Dataset\Dataset\Test"<jupyter_output><empty_output><jupyter_text>Importing VGG-19 Library and model<jupyter_code># Import the Vgg 19 library as shown below and add preprocessing layer to the front of VGG
# Here we will be using imagenet weights

vgg19 = VGG19(input_shape=IMAGE_SIZE + [3], weights='imagenet', include_top=False)
# don't train existing weights
for layer in vgg19.layers:
    layer.trainable = False
# useful for getting number of output classes
folders = glob("E:\Malaria Dataset\Dataset\Train\*")
folders
# our layers - you can add more if you want
x = Flatten()(vgg19.output)
prediction = Dense(len(folders), activation='softmax')(x)

# create a model object
model = Model(inputs=vgg19.input, outputs=prediction)
# view the structure of the model
model.summary()
# tell the model what cost and optimization method to use
model.compile(
  loss='categorical_crossentropy',
  optimizer='adam',
  metrics=['accuracy']
)<jupyter_output><empty_output><jupyter_text>Data Preprocessing of training set and testing set<jupyter_code># Use the Image Data Generator to import the images from the dataset
from tensorflow.keras.preprocessing.image import ImageDataGenerator

train_datagen = ImageDataGenerator(rescale = 1./255,
                                   shear_range = 0.2,
                                   zoom_range = 0.2,
                                   horizontal_flip = True)

test_datagen = ImageDataGenerator(rescale = 1./255)
# Make sure you provide the same target size as initialied for the image size
training_set = train_datagen.flow_from_directory(train_path,
                                                 target_size = (224, 224),
                                                 batch_size = 64,
                                                 class_mode = 'categorical')
test_set = test_datagen.flow_from_directory(valid_path,
                                            target_size = (224, 224),
                                            batch_size = 64,
                                            class_mode = 'categorical')
# fit the model
# Run the cell. It will take some time to execute
his = model.fit_generator(
  training_set,
  validation_data=test_set,
  epochs=25,
  steps_per_epoch=len(training_set),
  validation_steps=len(test_set)
)
#plot the training and validation accuracy and loss at each epoch
loss = his.history['loss']
val_loss = his.history['val_loss']
epochs = range(1, len(loss) + 1)
plt.plot(epochs, loss, 'y', label='Training loss')
plt.plot(epochs, val_loss, 'r', label='Validation loss')
plt.title('Training and validation loss')
plt.xlabel('Epochs')
plt.ylabel('Loss')
plt.legend()
plt.show()


acc = his.history['accuracy']
val_acc = his.history['val_accuracy']
plt.plot(epochs, acc, 'y', label='Training acc')
plt.plot(epochs, val_acc, 'r', label='Validation acc')
plt.title('Training and validation accuracy')
plt.xlabel('Epochs')
plt.ylabel('Accuracy')
plt.legend()
plt.show()<jupyter_output><empty_output><jupyter_text>Image prediction<jupyter_code># save it as a h5 file


from tensorflow.keras.models import load_model

model.save('model_VGG16_CNN_Malaria.h5')
y_pred = model.predict(test_set)

import numpy as np
y_pred = np.argmax(y_pred, axis=1)
y_pred
from tensorflow.keras.models import load_model
from tensorflow.keras.preprocessing import image

model=load_model('model_VGG16_CNN_Malaria.h5')
img_path = r"E:\Malaria Dataset\cell_images\Test\Parasitized\C39P4thinF_original_IMG_20150622_110115_cell_136.png"
img=image.load_img(img_path,target_size=(224,224))
x=image.img_to_array(img)
x
x.shape
x=x/255
x=np.expand_dims(x,axis=0)
img = np.reshape(x,[1,224,224,3])
img.shape
model.predict(img)
a=np.argmax(model.predict(img), axis=1)
if(a==1):
    print("Uninfected")
else:
    print("Infected")<jupyter_output>Infected<jupyter_text>Confusion Matrix<jupyter_code>from mlxtend.plotting import plot_confusion_matrix
from sklearn.metrics import confusion_matrix


#rounded_predictions = model.predict(test_set, batch_size=128, verbose=0)

import numpy as np
#rounded_labels=np.argmax(test_set.classes, axis=1)


from sklearn.metrics import confusion_matrix
cm = confusion_matrix(test_set.classes, y_pred)
plot_confusion_matrix(conf_mat=cm)

plt.show()<jupyter_output><empty_output>
StarcoderdataJupyterStructuredCleanDedup