import tensorflow as tf
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.utils import to_categorical
Load class names
classfile = ‘/content/drive/Shareddrives/Machine_Learning/bird_dataset/CUB_200_2011/birdspecies.names’
with open(classfile, ‘r’) as f:
class_names = f.read().splitlines()
#num_classes = len(class_names) # Update the number of classes
Define the paths to the training and validation datasets
train_data_dir = ‘/content/drive/Shareddrives/Machine_Learning/bird_dataset/CUB_200_2011’
validation_data_dir = ‘/content/drive/Shareddrives/Machine_Learning/bird_dataset/CUB_200_2011/images’
num_classes = len(os.listdir(train_data_dir))
Define the image dimensions and batch size
img_width, img_height = 224, 224
batch_size = 32
Create an instance of the ImageDataGenerator class for data augmentation
train_datagen = ImageDataGenerator(
rescale=1./255,
shear_range=0.2,
zoom_range=0.2,
horizontal_flip=True
)
Load the training dataset
train_generator = train_datagen.flow_from_directory(
train_data_dir,
target_size=(img_width, img_height),
batch_size=batch_size,
class_mode=‘categorical’
)
Create an instance of the ImageDataGenerator class for validation data
validation_datagen = ImageDataGenerator(rescale=1./255)
Load the validation dataset
validation_generator = validation_datagen.flow_from_directory(
validation_data_dir,
target_size=(img_width, img_height),
batch_size=batch_size,
class_mode=‘categorical’
)
Define the CNN model architecture
model = tf.keras.models.Sequential([
tf.keras.layers.Conv2D(32, (3, 3), activation=‘relu’, input_shape=(img_width, img_height, 3)),
tf.keras.layers.MaxPooling2D(pool_size=(2, 2)),
tf.keras.layers.Conv2D(64, (3, 3), activation=‘relu’),
tf.keras.layers.MaxPooling2D(pool_size=(2, 2)),
tf.keras.layers.Conv2D(128, (3, 3), activation=‘relu’),
tf.keras.layers.MaxPooling2D(pool_size=(2, 2)),
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(128, activation=‘relu’),
tf.keras.layers.Dropout(0.5),
tf.keras.layers.Dense(num_classes, activation=‘softmax’) # Use num_classes instead of hardcoding the number of classes
])
Compile the model
model.compile(optimizer=‘adam’, loss=‘categorical_crossentropy’, metrics=[‘accuracy’])
Train the model
model.fit(
train_generator,
steps_per_epoch=train_generator.samples // batch_size,
validation_data=validation_generator,
validation_steps=validation_generator.samples // batch_size,
epochs=10
)