Skip to content
Permalink
main
Switch branches/tags

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Go to file
 
 
Cannot retrieve contributors at this time
from google.colab import drive
drive.mount('/content/drive')
import os
import PIL
import glob
import cv2
import numpy as np
import pathlib
import matplotlib.pyplot as plt
import tensorflow as tf # version 2.5
from tensorflow import keras
from tensorflow.keras.layers import Softmax
from tensorflow.keras.layers import Dense, Flatten, Dropout, Activation
from tensorflow.keras.models import Sequential
from tensorflow.keras.optimizers import Adam
dir = '/content/drive/MyDrive/2dayprediction'
dataset = pathlib.Path(dir)
positives = (list(dataset.glob('2daynegative/*')))
negatives = (list(dataset.glob('2daypositive/*')))
"""Training and Testing + some preprocessing"""
# Splitting the dataset into training and testing and doing some preproessing
#training part
height = 512
width = 512
batch_size = 4
learning_rate_base = 0.001
epochs = 25
#training and validation split, 80% is training, 20% for validation
#first subset is training for training
#label mode is categorical because this requires category as in positive or negative
#equal all the images resized to this dimnention
train_dataset = tf.keras.preprocessing.image_dataset_from_directory(dataset,validation_split = 0.2, subset = "training", seed = 123, label_mode = 'categorical', image_size = (height, width), batch_size = batch_size)
#code for the validation part
#same code, with diff subset
#subset is validation
val_dataset = tf.keras.preprocessing.image_dataset_from_directory(dataset, validation_split = 0.2, subset = "validation", seed = 123, label_mode = "categorical", image_size = (height, width), batch_size = batch_size )
#printing the different classes inside the datset
class_names = train_dataset.class_names
print(class_names)
#names of all the folders in the dataset
#getting the model and tuning it
resnet50_structure = Sequential() #creating an empty neural network model, initilizing this by calling sequential function.
#this makes sure that layers added will be added in a sequence
#calling resnet50
#top = false means that i am going to use my own input and output layer, why? bc the original resnset model might have been trained in diff image dimention, unlike mine.
model_pretrained = tf.keras.applications.ResNet50(include_top = False, input_shape = (height,width,3), pooling = 'avg', classes = 2, weights = 'imagenet') #using imagenet for it's weight
#we can obtain this code from keras application documentation, under ResNet50
for each_layer in model_pretrained.layers:
each_layer.trainable = False #for every layer inside that pretrained model is false bc the resnset50 model has learned do not learn the weights again.
resnet50_structure.add(model_pretrained) #adding the pretrained model to the resnet model that we just created
resnet50_structure.add(Flatten())#flattening whatever the model gave into one dimention
resnet50_structure.add(Dense(512,activation='relu')) #using fully connected layer here at the end
#512 neurons for learning
#The final output will have 2 neurons for the 2 output
resnet50_structure.add(Dense(2, activation = 'softmax'))
resnet50_structure.summary()
#when the model is ready, now I have to compile it. I provider an optimizer of adam.
resnet50_structure.compile(optimizer = Adam(lr=learning_rate_base), loss = 'categorical_crossentropy', metrics = ['accuracy'])
#now I have to fit the model
#provide the training and val data seta, and specify the # of epocs
#monitoring the accuracy, validation and loss.
history = resnet50_structure.fit(train_dataset, validation_data = val_dataset, epochs = epochs)
fig1 = plt.gcf()
plt.plot(history.history['accuracy']) #store the models' logs in a history variable.
plt.plot(history.history['val_accuracy'])
plt.axis(ymin=0.4, ymax=1)
plt.grid() # labeling
plt.title('Model Accuracy')
plt.ylabel('Accuracy')
plt.xlabel('Epochs')
plt.legend(['Train', 'Validation'])
plt.show()
plt.plot(history.history['loss'])
plt.plot(history.history['val_loss'])
plt.grid()
plt.title('Model Loss')
plt.xlabel('loss')
plt.ylabel('Epochs')
plt.legend(['train', 'validation'])
plt.show()
#Model is ready
import random
import cv2 #used to read images
image = cv2.imread(str(negatives[0]))
resize_img = cv2.resize(image, (height, width)) #resizing it to 512x512
image = np.expand_dims(resize_img, axis = 0) #expanding the dimention of the image to 4D to input into the CNN
#print(image.shape)
pred = resnet50_structure.predict(image) #passing image to model to test
output_Class = class_names[np.argmax(pred)]
print("The predicted classification for this image is: ", output_Class)