Install necessary library if not already installed
!pip install tensorflow
import tensorflow as tf from tensorflow.keras.preprocessing.image import ImageDataGenerator import os
Directory paths
train_dir = '/content/dataset'
Image data generator with augmentation
train_datagen = ImageDataGenerator( rescale=1./255, # Rescale pixel values to [0, 1] shear_range=0.2, # Shear transformation zoom_range=0.2, # Random zoom horizontal_flip=True # Random horizontal flip )
Flow training images in batches of 32 using train_datagen generator
train_generator = train_datagen.flow_from_directory( train_dir, classes=['cats_set', 'dogs_set'], target_size=(224, 224), # Resize images to 224x224 (required input size for many pretrained models) batch_size=32, class_mode='binary' # Since we have two classes (cats and dogs) )
Print the number of images found
print(f"Found {train_generator.samples} images belonging to {train_generator.num_classes} classes.")
Load a pretrained model
base_model = tf.keras.applications.MobileNetV2(input_shape=(224, 224, 3), include_top=False, weights='imagenet')
Freeze the pretrained layers
base_model.trainable = False
Create a new model on top of the pretrained base model
model = tf.keras.Sequential([ base_model, tf.keras.layers.GlobalAveragePooling2D(), tf.keras.layers.Dense(1, activation='sigmoid') # Binary classification (cats vs dogs) ])
Compile the model
model.compile(optimizer=tf.keras.optimizers.Adam(), loss='binary_crossentropy', metrics=['accuracy'])
Calculate steps_per_epoch
steps_per_epoch = train_generator.samples // train_generator.batch_size
Train the model
history = model.fit(train_generator, epochs=10, # Increase epochs as needed steps_per_epoch=steps_per_epoch, verbose=1)
Evaluate the model
train_loss, train_accuracy = model.evaluate(train_generator) print(f"Training Accuracy: {train_accuracy}")