BEH41803. Using Google Colab To Train Image From Folder. Dog Vs Cat Step 1: Connect To Google Drive
BEH41803. Using Google Colab To Train Image From Folder. Dog Vs Cat Step 1: Connect To Google Drive
ipynb - Colaboratory
BEH41803. Using google colab to train image from folder. Dog vs Cat
from google.colab import drive
drive.mount('/content/gdrive')
import os
os.chdir("/content/gdrive/My Drive/Colab Notebooks/dataset")
os.getcwd()
#path = "/content/gdrive/My Drive/Colab Notebooks/dataset/train"
train_dir ='/content/gdrive/My Drive/Colab Notebooks/dataset/train'
pet_train_dir='/content/gdrive/My Drive/Colab Notebooks/dataset/train/pet'
can_train_dir='/content/gdrive/My Drive/Colab Notebooks/dataset/train/can'
validation_dir ='/content/gdrive/My Drive/Colab Notebooks/dataset/Val'
pet_val_dir='/content/gdrive/My Drive/Colab Notebooks/dataset/Val/pet'
can_val_dir='/content/gdrive/My Drive/Colab Notebooks/dataset/Val/can'
test_dir='/content/gdrive/My Drive/Colab Notebooks/dataset/test'
print('pet train length :',len(os.listdir(pet_train_dir)))
print('can train length :',len(os.listdir(can_train_dir)))
print('pet val length :',len(os.listdir(pet_val_dir)))
print('can val length :',len(os.listdir(can_val_dir)))
i t t fl tf
https://colab.research.google.com/drive/1X2RGJ3zd5dSwAcwYXo3J6eBVKco7zI8k?usp=sharing#scrollTo=6sDTfLQ_xcDT&uniqifier=2&printMode=true 1/7
6/27/2021 Cat and Dog Classification.ipynb - Colaboratory
import tensorflow as tf
from tensorflow.keras.optimizers import RMSprop
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from keras.applications import vgg16
model = tf.keras.models.Sequential([
tf.keras.layers.Conv2D(32, (3, 3), activation='relu', input_shape=(150, 150, 3)),
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.Flatten(),
tf.keras.layers.Dense(512, activation='relu'),
tf.keras.layers.Dense(1, activation='sigmoid')
])
#form architecture
model.compile(optimizer=RMSprop(lr=0.001), loss='binary_crossentropy', metrics=['acc'])
model.summary()
Model: "sequential"
_________________________________________________________________
=================================================================
_________________________________________________________________
_________________________________________________________________
_________________________________________________________________
_________________________________________________________________
_________________________________________________________________
_________________________________________________________________
_________________________________________________________________
_________________________________________________________________
=================================================================
Non-trainable params: 0
_________________________________________________________________
/usr/local/lib/python3.7/dist-packages/tensorflow/python/keras/optimizer_v2/optimizer_v
"The `lr` argument is deprecated, use `learning_rate` instead.")
https://colab.research.google.com/drive/1X2RGJ3zd5dSwAcwYXo3J6eBVKco7zI8k?usp=sharing#scrollTo=6sDTfLQ_xcDT&uniqifier=2&printMode=true 2/7
6/27/2021 Cat and Dog Classification.ipynb - Colaboratory
Step 4 Construct pretrained model with VGG ( you can use with or without pretrained model)
conv_base = tf.keras.applications.VGG16(weights='imagenet',include_top=False, input_shape=(15
#print(conv_base.summary())
conv_base.trainable=False
conv_base.summary()
Model: "vgg16"
_________________________________________________________________
=================================================================
_________________________________________________________________
_________________________________________________________________
_________________________________________________________________
_________________________________________________________________
_________________________________________________________________
_________________________________________________________________
_________________________________________________________________
_________________________________________________________________
_________________________________________________________________
_________________________________________________________________
_________________________________________________________________
_________________________________________________________________
_________________________________________________________________
_________________________________________________________________
_________________________________________________________________
_________________________________________________________________
_________________________________________________________________
_________________________________________________________________
=================================================================
Trainable params: 0
https://colab.research.google.com/drive/1X2RGJ3zd5dSwAcwYXo3J6eBVKco7zI8k?usp=sharing#scrollTo=6sDTfLQ_xcDT&uniqifier=2&printMode=true 3/7
6/27/2021 Cat and Dog Classification.ipynb - Colaboratory
_________________________________________________________________
model = tf.keras.models.Sequential([
conv_base,
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(512, activation='relu'),
tf.keras.layers.Dense(1, activation='sigmoid')
])
#form architecture
model.compile(optimizer=RMSprop(lr=0.001), loss='binary_crossentropy', metrics=['acc'])
model.summary()
Model: "sequential_1"
_________________________________________________________________
=================================================================
_________________________________________________________________
_________________________________________________________________
_________________________________________________________________
=================================================================
_________________________________________________________________
/usr/local/lib/python3.7/dist-packages/tensorflow/python/keras/optimizer_v2/optimizer_v
"The `lr` argument is deprecated, use `learning_rate` instead.")
# All images will be rescaled by 1./255
train_datagen = ImageDataGenerator(rescale=1./255) # rescale factor, will be multiply buy thi
test_datagen = ImageDataGenerator(rescale=1./255)
#has three methods flow(),flow_from_directory() and flow_from_dataframe()
train_generator = train_datagen.flow_from_directory(
# This is the target directory
train_dir,
# All images will be resized to 150x150
target_size=(150, 150),
batch_size=20,
# Since we use binary crossentropy loss, we need binary labels
https://colab.research.google.com/drive/1X2RGJ3zd5dSwAcwYXo3J6eBVKco7zI8k?usp=sharing#scrollTo=6sDTfLQ_xcDT&uniqifier=2&printMode=true 4/7
6/27/2021 Cat and Dog Classification.ipynb - Colaboratory
# Since we use binary_crossentropy loss, we need binary labels
class_mode='binary')
validation_generator = test_datagen.flow_from_directory(
validation_dir,
target_size=(150, 150),
batch_size=20,
class_mode='binary')
for data_batch, labels_batch in train_generator:
print('data batch shape:', data_batch.shape)
print('labels batch shape:', labels_batch.shape)
break
history =model.fit(
train_generator,
steps_per_epoch=len(train_generator),
epochs=10,
validation_data=validation_generator,
validation_steps=len(validation_generator))
Epoch 1/10
https://colab.research.google.com/drive/1X2RGJ3zd5dSwAcwYXo3J6eBVKco7zI8k?usp=sharing#scrollTo=6sDTfLQ_xcDT&uniqifier=2&printMode=true 5/7
6/27/2021 Cat and Dog Classification.ipynb - Colaboratory
import matplotlib.pyplot as plt
acc = history.history['acc']
val_acc = history.history['val_acc']
loss = history.history['loss']
val_loss = history.history['val_loss']
epochs = range(len(acc))
plt.plot(epochs, acc, 'bo', label='Training acc')
plt.plot(epochs, val_acc, 'b', label='Validation acc')
plt.title('Training and validation accuracy')
plt.legend()
plt.figure()
plt.plot(epochs, loss, 'bo', label='Training loss')
plt.plot(epochs, val_loss, 'b', label='Validation loss')
plt.title('Training and validation loss')
plt.legend()
plt.show()
https://colab.research.google.com/drive/1X2RGJ3zd5dSwAcwYXo3J6eBVKco7zI8k?usp=sharing#scrollTo=6sDTfLQ_xcDT&uniqifier=2&printMode=true 6/7
6/27/2021 Cat and Dog Classification.ipynb - Colaboratory
https://colab.research.google.com/drive/1X2RGJ3zd5dSwAcwYXo3J6eBVKco7zI8k?usp=sharing#scrollTo=6sDTfLQ_xcDT&uniqifier=2&printMode=true 7/7