<jupyter_start><jupyter_text>Step 1: Design the CNN architecture. After designing the architecture, print it in iPython Notebook.<jupyter_code>model = Sequential()

#Convolution and Max Pooling layers
model.add(Conv2D(32, (3,3), input_shape=(128,128,3), activation="relu"))
model.add(MaxPooling2D(pool_size = (2,2)))
model.add(Conv2D(32, (3,3), activation = "relu") )
model.add(MaxPooling2D(pool_size = (2,2)))
model.add(Conv2D(32, (3,3), activation = "relu") )
model.add(MaxPooling2D(pool_size = (2,2)))
model.add(Conv2D(32, (3,3), activation = "relu") )
model.add(MaxPooling2D(pool_size = (2,2)))

#Flattening layer.
model.add(Flatten ())

#Fully Connected Hidden Layer
model.add(Dense(units=128, activation='relu',kernel_regularizer=regularizers.l2(0.01)))
#Fully Connected Output Layer
model.add(Dense(units=1, activation='sigmoid', kernel_regularizer=regularizers.l2(0.01)))
model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
#Summary of the Architecture
model.summary()<jupyter_output>_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
conv2d_5 (Conv2D)            (None, 126, 126, 32)      896       
_________________________________________________________________
max_pooling2d_5 (MaxPooling2 (None, 63, 63, 32)        0         
_________________________________________________________________
conv2d_6 (Conv2D)            (None, 61, 61, 32)        9248      
_________________________________________________________________
max_pooling2d_6 (MaxPooling2 (None, 30, 30, 32)        0         
_________________________________________________________________
conv2d_7 (Conv2D)            (None, 28, 28, 32)        9248      
_________________________________________________________________
max_pooling2d_7 (MaxPooling2 (None, 14, 14, 32)        0         
_________________________________________________________________
conv2d_8 ([...]<jupyter_text>Step 2: Load Images and Prepare the Network for training<jupyter_code>#Training dataset generator
train_datagen = image.ImageDataGenerator(rescale=1./255, 
                                   shear_range = 0.2,
                                   zoom_range = 0.2,
                                   horizontal_flip = True)

# Validation dataset generator
validation_datagen = image.ImageDataGenerator(rescale = 1./255)

# Loading the training set
training_set = train_datagen.flow_from_directory('./dataset/training_set',target_size=(128,128), batch_size=32, class_mode='binary')

# Loading the validation dataset 
validation_set = validation_datagen.flow_from_directory('./dataset/validation_set',target_size=(128,128), batch_size=32, class_mode='binary')<jupyter_output>Found 25000 images belonging to 2 classes.
Found 3200 images belonging to 2 classes.<jupyter_text>Step 3: Run the CNN Network<jupyter_code># Steps_per_epoch = 718 because there are 23000 training images and a batch size of 32.
# To ensure we run through the entire training set in one epoch, we need to run 23000/32 = 718 
# different batches.
#
# Validation_steps = 63 because we have 2000 validation images and a batch size of 32,
# To ensure that we run through the entire validation set at the end of each epoch we need
# to run 2000/32 = 63 batches.   

history = model.fit_generator(training_set, steps_per_epoch=782, epochs=40, validation_data = validation_set, validation_steps=100, verbose=1)
model.save('Cat-Dog-128x128-3layer-maxpooling.h5')
print("Saved model to disk")
model.save('Cat-Dog-128x128-3layer-maxpooling.h5')
model.save_weights('Cat-Dog-128x128-3layer-maxpooling.h5')
print("Saved model to disk")<jupyter_output>Saved model to disk<jupyter_text>Step 5: Plot the training and Validation Loss/Accuracy<jupyter_code>y1 = history.history['acc']
y2 = history.history['val_acc']
y3 = history.history['loss']
y4 = history.history['val_loss']
x = range(0, len(y1))

fig, ax1 = plt.subplots()
ax2 = ax1.twinx()
ax1.plot(x, y1, 'g-')
ax2.plot(x, y2, 'b-')

ax1.set_xlabel('Epoch')
ax1.set_ylabel('Training Accuracy', color='g')
ax2.set_ylabel('Validation Accuracy', color='b')
plt.show()

fig, ax1 = plt.subplots()
ax2 = ax1.twinx()
ax1.plot(x, y3, 'g-')
ax2.plot(x, y4, 'b-')

ax1.set_xlabel('Epoch')
ax1.set_ylabel('Training Loss Function Value', color='g')
ax2.set_ylabel('Validation Loss Function Accuracy', color='b')

plt.plot()<jupyter_output><empty_output><jupyter_text>Step 6: Predict Dog/Cat using the Trained Model<jupyter_code>model=load_model('Cat-Dog-128x128-3layer-maxpooling.h5')

correct = 0
wrong = 0
images = [os.path.basename(x) for x in glob.glob('dataset/test_set/cats/*.jpg')]
length = len(images)
for i in range(0,length):
    pic = 'dataset/test_set/cats/' + images[i]
    test_image=image.load_img(pic, target_size=(128,128))
    test_image=image.img_to_array(test_image)
    test_image=np.expand_dims(test_image, axis=0)
    result=model.predict(test_image)
    if (result[0][0] < 0.5):
        correct=correct+1
    else:
        wrong=wrong+1
        
images = [os.path.basename(x) for x in glob.glob('dataset/test_set/dogs/*.jpg')]
length = len(images)
for i in range(0,length):
    pic = 'dataset/test_set/dogs/' + images[i]
    test_image=image.load_img(pic, target_size=(128,128))
    test_image=image.img_to_array(test_image)
    test_image=np.expand_dims(test_image, axis=0)
    result=model.predict(test_image)
    if (result[0][0] > 0.5):
        correct=correct+1
    else:
        wrong=wrong+1
        
print(correct/(correct + wrong))<jupyter_output>0.7633333333333333
{'fraction_non_alphanumeric': 0.13220940550133098, 'fraction_numerical': 0.05625554569653948, 'mean_word_length': 4.810309278350515, 'pattern_counts': {'":': 0, '<': 18, '<?xml version=': 0, '>': 18, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 1, 'word_list_counts': {'cursed_substrings.json': 3, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '5', 'dir': 'jupyter-structured-clean-dedup', 'id': '46399', 'license': 'MIT', 'n_tokens_mistral': 2031, 'n_tokens_neox': 1828, 'n_words': 396, 'path': 'Convolutional Neural Network/Convolutional Neural Network for Cat:Dog pictures.ipynb', 'repo_name': 'samgermain/ArtificialIntelligence', 'size': '5635'}