I am trying to save my CNN to a file every at every checkpoint. However which extension should I use as my file directory? Also would I need to call model.save(filepath)
at the end of the code or would my model be saved automatically by ModelCheckpoint()
?
I have my model saved as a .h5 file but I don't know whether I should change it.
from keras import Sequential
from keras_preprocessing.image import ImageDataGenerator
from keras.layers import *
from keras.callbacks import ModelCheckpoint
import numpy as np
import os
img_size = 500 # number of pixels for width and height
#Random Seed
np.random.seed(12321)
training_path = os.getcwd() + "/cats and dogs images/train"
testing_path = os.getcwd() + "/cats and dogs images/test"
#Defines the Model
model = Sequential([
Conv2D(filters=64, kernel_size=(3,3), activation="relu", padding="same", input_shape=(img_size,img_size,3)),
MaxPool2D(pool_size=(2,2), strides=2),
Conv2D(filters=64, kernel_size=(3,3), activation="relu", padding="same"),
MaxPool2D(pool_size=(2,2), strides=2),
Flatten(),
Dense(32, activation="relu"),
Dense(1, activation="sigmoid")
])
#Scales the pixel values to between 0 to 1
datagen = ImageDataGenerator(rescale=1.0/255.0)
#Prepares Training Data
training_dataset = datagen.flow_from_directory(directory = training_path, target_size=(img_size,img_size), classes = ["cat","dog"], batch_size = 19)
#Prepares Testing Data
testing_dataset = datagen.flow_from_directory(directory = testing_path, target_size=(img_size,img_size), classes = ["cat","dog"], batch_size = 19)
#Compiles the model
model.compile(loss="binary_crossentropy", optimizer="adam", metrics=['accuracy'])
#Checkpoint
checkpoint = ModelCheckpoint("trained_model.h5", monitor='loss', verbose=1, save_best_only=True, mode='min', period=1)
#Fitting the model to the dataset (Training the Model)
model.fit(x = training_dataset, steps_per_epoch = 658, validation_data=testing_dataset, validation_steps=658, epochs = 10, callbacks=[checkpoint], verbose = 1)
# evaluate model on training dataset
acc = model.evaluate_generator(training_dataset, steps=len(training_dataset), verbose=0)
print("Accuracy on training dataset:")
print('> %.3f' % (acc * 100.0))
#evaluate model on testing dataset
acc = model.evaluate_generator(testing_dataset, steps=len(testing_dataset), verbose=0)
print("Accuracy on testing dataset:")
print('> %.3f' % (acc * 100.0))
##Saving the Model:
#model.save("trained model.h5")
#print("Saved model to disk")