TDS Archive

An archive of data science, data analytics, data engineering, machine learning, and artificial intelligence writing from the former Towards Data Science Medium publication.

Hands-on Tutorials

Lego Minifigure Gender Classification Using Deep Learning

6 min readOct 12, 2020

--

Photo by James Pond on Unsplash
Instagram: @Let_It_Lego

Why use transfer learning?

Adding and training a fully-connected layer at the end of the neural network. Source: Udacity

Gathering the data

Capes, costumes, weird hats, etc.
SpongeBob!
Snippet of photo dataset.

The code

%matplotlib inline
%config InlineBackend.figure_format = 'retina'
import matplotlib.pyplot as plt
import numpy as np
import torch
from torch import nn
from torch import optim
import torch.nn.functional as F
from torchvision import datasets, transforms, models
train_on_gpu = torch.cuda.is_available()if not train_on_gpu:
print('CUDA is not available. Training on CPU ...')
else:
print('CUDA is available! Training on GPU ...')

Loading and transforming the dataset

data_dir = 'Lego (compressed pics)'# VGG-16 Takes 224x224 images as input, so we resize all of them
data_transform = transforms.Compose([transforms.Resize((224, 224)),
transforms.ToTensor()])
train_data = datasets.ImageFolder(data_dir + '/Train',
transform=data_transform)
test_data = datasets.ImageFolder(data_dir + '/Test',
transform=data_transform)
Number of train and test images.
# how many samples per batch to load
batch_size = 20
# number of subprocesses to use for data loading
num_workers = 0
train_loader = torch.utils.data.DataLoader(train_data,
batch_size=batch_size, num_workers=num_workers, shuffle=True)
test_loader = torch.utils.data.DataLoader(test_data,
batch_size=batch_size, num_workers=num_workers, shuffle=True)
# specify the image classes
classes = ['Boy', 'Girl']
# obtain one batch of training images
dataiter = iter(train_loader)
images, labels = dataiter.next()
images = images.numpy() # convert images to numpy for display
# plot the images in the batch, along with the corresponding labels
fig = plt.figure(figsize=(25,4))
for idx in np.arange(20):
ax = fig.add_subplot(2, 20/2, idx+1, xticks=[], yticks=[])
plt.imshow(np.transpose(images[idx], (1, 2, 0)))
ax.set_title(classes[labels[idx]])
Visualize a batch of training data.

Define the model

# Load the pretrained model from PyTorch
vgg16 = models.vgg16(pretrained=True)
# Freeze training for all feature layers so the model doesn't change # the parameters it was pre-trained on
for param in vgg16.features.parameters():
param.requires_grad = False
n_inputs = vgg16.classifier[6].in_features
last_layer = nn.Linear(n_inputs, len(classes))
vgg16.classifier[6] = last_layerif train_on_gpu:
vgg16.cuda()
criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(vgg16.classifier.parameters(), lr=0.001)

Training the network

Training the network.

Testing

Determining testing accuracy.

Visualize test results

Visualize the test results for a sample.
Sample results!

Conclusion

--

--

TDS Archive
TDS Archive

An archive of data science, data analytics, data engineering, machine learning, and artificial intelligence writing from the former Towards Data Science Medium publication.

No responses yet