Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Last Updated: Mar 27, 2024

Gender Classification Using CNN

Leveraging ChatGPT - GenAI as a Microsoft Data Expert
Speaker
Prerita Agarwal
Data Specialist @
23 Jul, 2024 @ 01:30 PM

Introduction

In recent years, Deep Learning has garnered significant attention due to advances in technology that can efficiently handle and implement Deep Learning algorithms. CNNs are widely used today for image detection due to their high accuracy. In this article, we’ll dive into a practical use case of CNN for gender classification. This project would give a good insight into the working and development of CNNs. Gender Classification is one of the most common real-world use cases of CNNs and is a very beginner-friendly task since it’s just a binary classification.

Prerequisites 

Before going further in the blog, readers are expected to have a fair idea about CNNs and ANNs. You may head out to our Machine Learning blogs vertical if you wish to know more about them. 

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Dataset

The dataset contains over 200k image samples and can be downloaded from here

Implementation

We start by importing the necessary libraries. 

import os
from tensorflow.keras import layers
from tensorflow.keras import Model
from tensorflow.keras.preprocessing.image import ImageDataGenerator
import tensorflow as tf

 

We are importing and loading the dataset. The ImageDataGenerator is a Keras class that will run through the dataset applying random transformations to every image passed so the same image is never seen again to avoid overfitting. These transformations are parameters and include operations like zoom, shear etc. 

train_datagen = ImageDataGenerator(rescale = 1./255,
  rotation_range=40,
      width_shift_range=0.2,
      height_shift_range=0.2,
      shear_range=0.2,
      zoom_range=0.2,
      horizontal_flip=True,
      fill_mode='nearest')

test_datagen = ImageDataGenerator( rescale = 1.0/255)

train_generator = train_datagen.flow_from_directory("gender-recognition-200k-images-celeba/Dataset/Train/",batch_size =256 ,class_mode = 'binary', target_size = (64, 64))     

validation_generator =  test_datagen.flow_from_directory( "gender-recognition-200k-images-celeba/Dataset/Validation/",batch_size  = 256,class_mode  = 'binary', target_size = (64, 64))

 

Now is the time to train the Neural network. We’ll be using Adam, an optimization algorithm provided by Keras for stochastic gradient descent for training deep learning models. 

We’ll use the sequential model since it’s most suitable for single input and single output models. Remember, the weights are assigned after the model gets some information. The loss function used is Binary cross entropy which is ideal for binary classification. Expression for which is given by: - 

Source  - link

Here y is the label(1 is a positive class and 0 is a negative class), and p(y) is the predicted probability of point belonging to the positive class for N points.  

from keras.optimizers import Adam
model = tf.keras.models.Sequential([
    # 1st conv
  tf.keras.layers.Conv2D(96, (11,11),strides=(4,4), activation='relu', input_shape=(64, 64, 3)),
  tf.keras.layers.BatchNormalization(),
  tf.keras.layers.MaxPooling2D(2, strides=(2,2)),
    # 2nd conv
  tf.keras.layers.Conv2D(256, (11,11),strides=(1,1), activation='relu',padding="same"),
  tf.keras.layers.BatchNormalization(),
    # 3rd conv
  tf.keras.layers.Conv2D(384, (3,3),strides=(1,1), activation='relu',padding="same"),
  tf.keras.layers.BatchNormalization(),
    # 4th conv
  tf.keras.layers.Conv2D(384, (3,3),strides=(1,1), activation='relu',padding="same"),
  tf.keras.layers.BatchNormalization(),
    # 5th Conv
  tf.keras.layers.Conv2D(256, (3, 3), strides=(1, 1), activation='relu',padding="same"),
  tf.keras.layers.BatchNormalization(),
  tf.keras.layers.MaxPooling2D(2, strides=(2, 2)),
  # To Flatten layer
  tf.keras.layers.Flatten(),
  # To FC layer 1
  tf.keras.layers.Dense(4096, activation='relu'),
  tf.keras.layers.Dropout(0.5),
  #To FC layer 2
  tf.keras.layers.Dense(4096, activation='relu'),
  tf.keras.layers.Dropout(0.5),
  tf.keras.layers.Dense(1, activation='sigmoid') 
])
model.compile(
    optimizer=Adam(lr=0.001), loss='binary_crossentropy', metrics=['accuracy'])
hist = model.fit_generator(generator=train_generator,
                    validation_data=validation_generator,
                    steps_per_epoch=256,
                    validation_steps=256,
                    epochs=50)

 

Now, we’ll evaluate the accuracy of the model. 

import matplotlib.pyplot as plt
acc = hist.history['accuracy']
val_acc = hist.history['val_accuracy']
loss = hist.history['loss']
val_loss = hist.history['val_loss']

epochs = range(len(acc))

plt.plot(epochs, acc, 'r', label='Training accuracy')
plt.plot(epochs, val_acc, 'b', label='Validation accuracy')
plt.title('Training and validation accuracy')
plt.legend(loc=0)
plt.figure()
plt.show()
import numpy as np

from keras.preprocessing import image
# predicting images
path = "gender-recognition-200k-images-celeba/Dataset/Test/Female/128402.jpg"
img = image.load_img(path, target_size=(64, 64))
x = image.img_to_array(img)
x = np.expand_dims(x, axis=0)

images = np.vstack([x])
classes = model.predict(images, batch_size=1)
print(classes[0])
if classes[0]>0.5:
    print("is a man")
else:
    print(" is a female")
plt.imshow(img)

The model has learned gender classification with considerable validation accuracy. 

Frequently Asked Questions

Briefly explain CNNs 

CNN's are widely used in the domain of image learning. They use filters that are essentially just feature detectors based on which classifications can be done.

What are the disadvantages of the Sequential model? 

The sequential model isn’t an ideal choice in case, the model has multiple inputs or multiple outputs, the model needs to do layer sharing. It would be best if you had a non-linear topology. 

Is gender nominal or ordinal data?

Gender is nominal data. Some other examples of nominal data are; the country, gender, race, hair color, etc., of a group of people. Note that the nominal data examples are nouns with no order, while ordinal data examples come with a hierarchy level. 

Conclusion

In this article, we have extensively discussed Gender Classification using CNN and its implementation in python. We hope that this blog has helped you enhance your knowledge regarding Gender Classification using CNN and if you would like to learn more, check out our articles here. Do upvote our blog to help other ninjas grow. Happy Coding!

Topics covered
1.
Introduction
2.
Prerequisites 
3.
Dataset
4.
Implementation
5.
Frequently Asked Questions
5.1.
Briefly explain CNNs 
5.2.
What are the disadvantages of the Sequential model? 
5.3.
Is gender nominal or ordinal data?
6.
Conclusion