Commit 98d4e718 authored by Rathnayake K.U.R.S.D's avatar Rathnayake K.U.R.S.D

deep transfer cnn completed

parent 219a6415
......@@ -130,6 +130,124 @@ class DeepCNNClassifier:
print("=========== Data Pre-Processing Completed ===========")
return (train_data_ , test_data_)
#----------------------------------------------------WILL_USE_BY_ANOTHER_FUNCTION-----------------------------------------------------------------------------
def create_model(self):
import tensorflow as tf
import tensorflow_hub as hub
from tensorflow.keras import layers
#Download the pretrained model and save it as a keras layer
feature_extractor_layer = hub.KerasLayer(self.transfer_model_url,
trainable = False, #freeze the already learned patterns
name = "feature_extraction_layer",
input_shape = (self.image_height, self.image_width, self.num_color_channels))
self.activation_func = 'sigmoid'
if(self.number_of_classes > 2):
self.activation_func = 'softmax'
model = tf.keras.Sequential([
feature_extractor_layer,
layers.Dense(self.number_of_classes , activation= self.activation_func , name="output_layer")
])
print("=========== Model is Created ==========")
return model
#---------------------------------------------------SHOULD_CALL_BY_USER------------------------------------------------------------------------------
def start_training(self , num_epochs = 5):
import tensorflow as tf
train_data_ , test_data_ = self.preprocess_dataset()
cnn_model = self.create_model()
self.loss_function = 'binary_crossentropy'
if(self.number_of_classes > 2):
self.loss_function = 'categorical_crossentropy'
cnn_model.compile(loss=self.loss_function,
optimizer = tf.keras.optimizers.Adam(),
metrics=["accuracy"])
print("=========== Model Compiled SuccessFully ==========")
model_hist = cnn_model.fit(train_data_,
epochs=num_epochs,
steps_per_epoch=len(train_data_),
validation_data = test_data_,
validation_steps = len(test_data_))
print("=========== Model Trained SuccessFully ==========")
self.trained_model = cnn_model
self.model_train_history = model_hist
return cnn_model
#---------------------------------------------------SHOULD_CALL_BY_USER------------------------------------------------------------------------------
def save_model(self, save_to_path = '/content'):
model_name = str(self.model_name)+".h5"
model = self.trained_model
model.save(model_name)
print("=========== Model Saved to --> {}".format(model_name))
#---------------------------------------------------SHOULD_CALL_BY_USER / Function------------------------------------------------------------------------------
def plot_loss_curves(self, ):
import matplotlib.pyplot as plt
history = self.model_train_history
loss = history.history["loss"]
val_loss = history.history["val_loss"]
accuracy = history.history["accuracy"]
val_accuracy = history.history["val_accuracy"]
#get the number of epochs that we run for
epochs = range(len(history.history["loss"]))
#Plot the lost
plt.plot(epochs , loss , label="Training Loss")
plt.plot(epochs , val_loss , label="Validation Loss")
plt.title("Loss")
plt.xlabel("Epochs")
plt.legend()
#Plot the accuracy
plt.figure()
plt.plot(epochs , accuracy , label="Training accuracy")
plt.plot(epochs , val_accuracy , label="Validation accuracy")
plt.title("accuracy")
plt.xlabel("Epochs")
plt.legend()
#----------------------------------------------------WILL_USE_BY_ANOTHER_FUNCTION-----------------------------------------------------------------------------
def load_and_prep_image(self, filename):
import tensorflow as tf
img = tf.io.read_file(filename)
img = tf.image.decode_image(img)
#Resiz the Image
img = tf.image.resize(img , size=[self.image_height , self.image_width])
#Re scale the image - get all values between 0 and 255
img = img/255.
return img
#---------------------------------------------------SHOULD_CALL_BY_USER------------------------------------------------------------------------------
def pred_and_plot(self, filename):
import tensorflow as tf
import matplotlib.pyplot as plt
import numpy as np
model = self.trained_model
class_names = self.class_names
img = self.load_and_prep_image(filename)
pred = model.predict(tf.expand_dims(img , axis=0))
pred_class = class_names[np.argmax(tf.round(pred))]
#Plot the image and the predicted class
plt.imshow(img)
plt.title(f"Prediction :{pred_class}")
plt.axis(False)
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment