Convolutional Neural Network (CNN)

this post will describe what is CNN, how it works and common usecases of CNN
Author

Sulthan A. Karimov

Published

July 2, 2024

Open In Colab

import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '1' 
import tensorflow as tf
print(tf.__version__)
try:
  import google.colab
  IN_COLAB = True
except:
  IN_COLAB = False

IN_COLAB
import zipfile, os

local_zip = (
    'datasets/images/archive.zip' if IN_COLAB == False
    else '/content/drive/MyDrive/datasets/images/archive.zip'
)
zip_ref = zipfile.ZipFile(local_zip, 'r')
zip_ref.extractall('datasets/images/messy_clean_room/')
zip_ref.close()

base_dir = 'datasets/images/messy_clean_room/images'
train_dir = os.path.join(base_dir, 'train')
validation_dir = os.path.join(base_dir, 'val')
os.listdir(base_dir+'/train')
os.listdir(base_dir+'/val')
from tensorflow.keras.preprocessing.image import ImageDataGenerator

train_datagen = ImageDataGenerator(
    rescale = 1./255,
    rotation_range = 20,
    horizontal_flip = True,
    shear_range = 0.2,
    fill_mode = 'nearest')

test_datagen = ImageDataGenerator(
    rescale = 1./255)
train_generator = train_datagen.flow_from_directory(
    train_dir,
    target_size = (150,150),
    batch_size = 4,
    class_mode = 'binary')

validation_generator = test_datagen.flow_from_directory(
    validation_dir,
    target_size = (150,150),
    batch_size = 4,
    class_mode = 'binary')
dir(train_generator)
model = tf.keras.models.Sequential([
    tf.keras.Input(shape = (150, 150, 3)),
    tf.keras.layers.Conv2D(32, (3,3), activation = 'relu'),
    tf.keras.layers.MaxPooling2D(2,2),
    tf.keras.layers.Conv2D(64, (3,3), activation = 'relu'),
    tf.keras.layers.MaxPooling2D(2,2),
    tf.keras.layers.Conv2D(128, (3,3), activation = 'relu'),
    tf.keras.layers.MaxPooling2D(2,2),
    tf.keras.layers.Conv2D(512, (3,3), activation = 'relu'),
    tf.keras.layers.MaxPooling2D(2,2),
    tf.keras.layers.Flatten(),
    tf.keras.layers.Dense(512, activation = 'relu'),
    tf.keras.layers.Dense(1, activation = 'sigmoid')
])
model = tf.keras.models.Sequential()
model.add(tf.keras.Input(shape = (150, 150, 3))),
model.add(tf.keras.layers.Conv2D(32, (3,3), activation = 'relu'))
model.add(tf.keras.layers.MaxPooling2D((2,2)))
model.add(tf.keras.layers.Conv2D(64, (3,3), activation = 'relu'))
model.add(tf.keras.layers.MaxPooling2D((2,2)))
model.add(tf.keras.layers.Conv2D(128, (3,3), activation = 'relu'))
model.add(tf.keras.layers.MaxPooling2D((2,2)))
model.add(tf.keras.layers.Conv2D(512, (3,3), activation = 'relu'))
model.add(tf.keras.layers.MaxPooling2D((2,2)))
model.add(tf.keras.layers.Flatten())
model.add(tf.keras.layers.Dense(512, activation = 'relu'))
model.add(tf.keras.layers.Dense(1, activation = 'sigmoid'))
model.summary()
model.compile(loss = 'binary_crossentropy',
              optimizer = tf.optimizers.Adam(),
              metrics = ['accuracy'])

model.fit( train_generator, epochs = 40, validation_data = validation_generator, validation_steps = 5, verbose = 2)

from tensorflow.keras.applications import ResNet50
from tensorflow.keras.applications import ResNet152V2
transfer = tf.keras.models.Sequential([
    ResNet152V2(
        weights = "imagenet", 
        include_top = False, 
        input_tensor = tf.keras.layers.Input(shape = (150,150,3))),
    tf.keras.layers.Flatten(),
    tf.keras.layers.Dense(128, activation = 'relu'),
    tf.keras.layers.Dense(1, activation = 'softmax')
])
transfer.compile(loss = 'binary_crossentropy',
              optimizer = tf.optimizers.Adam(),
              metrics = ['accuracy'])
transfer.fit(
    train_generator,
    epochs = 40,
    validation_data = validation_generator,
    validation_steps = 5,
    verbose = 2)
Back to top