Professional Documents
Culture Documents
Pytorch Waste Classification Using Densenet Jupyter Notebook
Pytorch Waste Classification Using Densenet Jupyter Notebook
Introduction
Waste disposal is often a concern for various reasons including eutrophication, toxic
waste consumption by animals and land, air or water pollution. Segregating the waste
into organic waste and recyclable waste is a good practice to follow. But, manually
performing the task is very cumbersome. Hence, the dataset
(https://www.kaggle.com/techsash/waste-classification-data) suggests the use of ML to
automate the classification process.
PyTorch Basics
PyTorch is very popular because of its ease of use and applications in numerous fields of
machine learning. In simple terms, PyTorch is basically a python framework that allows
tensor computation with strong GPU acceleration for constructing deep neural networks.
It provides flexibility and stability for deep learning.
import torch
from torch import nn
from torch import optim
import torch.nn.functional as F
from torchvision import datasets, transforms, models
if not train_on_gpu:
print('CUDA is not available. Training on CPU ...')
else:
print('CUDA is available! Training on GPU ...')
http://localhost:8889/notebooks/pytorch-waste-classification-using-densenet.ipynb Page 1 of 14
pytorch-waste-classification-using-densenet - Jupyter Notebook 10/05/24, 9:45 AM
test_transforms = transforms.Compose([transforms.Resize(255),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize([0.485, 0.45
[0.229, 0.22
In deep learning, often the training set is split into train samples and validation samples
to cross check accuracies. This is done using SubsetRandomSampler.
http://localhost:8889/notebooks/pytorch-waste-classification-using-densenet.ipynb Page 2 of 14
pytorch-waste-classification-using-densenet - Jupyter Notebook 10/05/24, 9:45 AM
The DataLoader takes a dataset (such as you would get from ImageFolder) and returns
batches of images and the corresponding labels. You can set various parameters like the
batch size and if the data is shuffled after each epoch.
In [19]: print(len(train_loader))
565
classes=['O','R']
Plotting the images to understand the data. O= Organic Waste R= Recyclable Waste
# plot the images in the batch, along with the corresponding labels
fig = plt.figure(figsize=(25, 4))
# display 20 images
http://localhost:8889/notebooks/pytorch-waste-classification-using-densenet.ipynb Page 3 of 14
pytorch-waste-classification-using-densenet - Jupyter Notebook 10/05/24, 9:45 AM
Clipping input data to the valid range for imshow with RGB data ([
0..1] for floats or [0..255] for integers).
Clipping input data to the valid range for imshow with RGB data ([
0..1] for floats or [0..255] for integers).
Clipping input data to the valid range for imshow with RGB data ([
0..1] for floats or [0..255] for integers).
Clipping input data to the valid range for imshow with RGB data ([
0..1] for floats or [0..255] for integers).
Clipping input data to the valid range for imshow with RGB data ([
0..1] for floats or [0..255] for integers).
Clipping input data to the valid range for imshow with RGB data ([
0..1] for floats or [0..255] for integers).
Clipping input data to the valid range for imshow with RGB data ([
0..1] for floats or [0..255] for integers).
Clipping input data to the valid range for imshow with RGB data ([
0..1] for floats or [0..255] for integers).
Clipping input data to the valid range for imshow with RGB data ([
0..1] for floats or [0..255] for integers).
Clipping input data to the valid range for imshow with RGB data ([
0..1] for floats or [0..255] for integers).
Clipping input data to the valid range for imshow with RGB data ([
0..1] for floats or [0..255] for integers).
Clipping input data to the valid range for imshow with RGB data ([
0..1] for floats or [0..255] for integers).
Clipping input data to the valid range for imshow with RGB data ([
0..1] for floats or [0..255] for integers).
Clipping input data to the valid range for imshow with RGB data ([
0..1] for floats or [0..255] for integers).
Clipping input data to the valid range for imshow with RGB data ([
0..1] for floats or [0..255] for integers).
Clipping input data to the valid range for imshow with RGB data ([
0..1] for floats or [0..255] for integers).
Clipping input data to the valid range for imshow with RGB data ([
0..1] for floats or [0..255] for integers).
Clipping input data to the valid range for imshow with RGB data ([
0..1] for floats or [0..255] for integers).
Clipping input data to the valid range for imshow with RGB data ([
0..1] for floats or [0..255] for integers).
Clipping input data to the valid range for imshow with RGB data ([
0..1] for floats or [0..255] for integers).
http://localhost:8889/notebooks/pytorch-waste-classification-using-densenet.ipynb Page 4 of 14
pytorch-waste-classification-using-densenet - Jupyter Notebook 10/05/24, 9:45 AM
Clipping input data to the valid range for imshow with RGB data ([
0..1] for floats or [0..255] for integers).
http://localhost:8889/notebooks/pytorch-waste-classification-using-densenet.ipynb Page 5 of 14
pytorch-waste-classification-using-densenet - Jupyter Notebook 10/05/24, 9:45 AM
Transfer Learning
Transfer Learning refers to the process of using already existing pre-trained models for
other applications by tweaking the last few layers and using it to classify our desired
classes. Once trained, these models work astonishingly well as feature detectors for
images they weren't trained on. Using a pre-trained network on images not in the training
set is called transfer learning. Here we'll use transfer learning to train a network that can
classify our organic and recyclable waste photos with near perfect accuracy.
Here, the DenseNet121 is used. DenseNet is a very powerful model with 121 layers. For
more information about densenet, Click Here
(https://www.kaggle.com/pytorch/densenet121).
http://localhost:8889/notebooks/pytorch-waste-classification-using-densenet.ipynb Page 6 of 14
pytorch-waste-classification-using-densenet - Jupyter Notebook 10/05/24, 9:45 AM
Densenet architecture
Img source:https://pytorch.org/hub/pytorch_vision_densenet/
(https://pytorch.org/hub/pytorch_vision_densenet/)
Dense Convolutional Network (DenseNet), connects each layer to every other layer in a
feed-forward fashion. The 1-crop error rates on the imagenet dataset with the pretrained
model are 25.35 for top-1 error and 7.83 for top-5 error.
http://localhost:8889/notebooks/pytorch-waste-classification-using-densenet.ipynb Page 7 of 14
pytorch-waste-classification-using-densenet - Jupyter Notebook 10/05/24, 9:45 AM
C:\Users\pintoo\AppData\Local\Programs\Python\Python312\Lib\site
-packages\torchvision\models\_utils.py:208: UserWarning: The par
ameter 'pretrained' is deprecated since 0.13 and may be removed
in the future, please use 'weights' instead.
warnings.warn(
C:\Users\pintoo\AppData\Local\Programs\Python\Python312\Lib\site
-packages\torchvision\models\_utils.py:223: UserWarning: Argumen
ts other than a weight enum or `None` for 'weights' are deprecat
ed since 0.13 and may be removed in the future. The current beha
vior is equivalent to passing `weights=DenseNet121_Weights.IMAGE
NET1K_V1`. You can also use `weights=DenseNet121_Weights.DEFAULT
` to get the most up-to-date weights.
warnings.warn(msg)
Downloading: "https://download.pytorch.org/models/densenet121-a6
39ec97.pth" to C:\Users\pintoo/.cache\torch\hub\checkpoints\dens
enet121-a639ec97.pth
100.0%
Out[26]: DenseNet(
(features): Sequential(
model = models.densenet121(pretrained=True)
criterion = nn.NLLLoss()
model.to(device);
http://localhost:8889/notebooks/pytorch-waste-classification-using-densenet.ipynb Page 8 of 14
pytorch-waste-classification-using-densenet - Jupyter Notebook 10/05/24, 9:45 AM
Training the model for desired number of epochs and keeping track of train loss and
validation loss. If the validation loss decreases, the model is saved.The simplest thing to
do is simply save the state dict with torch.save .
###################
# train the model #
###################
model.train()
for data, target in train_loader:
# move tensors to GPU if CUDA is available
if train_on_gpu:
data, target = data.cuda(), target.cuda()
# clear the gradients of all optimized variables
optimizer.zero_grad()
# forward pass: compute predicted outputs by passing inputs to
output = model(data)
# calculate the batch loss
loss = criterion(output, target)
# backward pass: compute gradient of the loss with respect to m
loss.backward()
# perform a single optimization step (parameter update)
optimizer.step()
# update training loss
train_loss += loss.item()*data.size(0)
######################
# validate the model #
######################
model.eval()
for data, target in valid_loader:
# move tensors to GPU if CUDA is available
if train_on_gpu:
data, target = data.cuda(), target.cuda()
# forward pass: compute predicted outputs by passing inputs to
output = model(data)
# calculate the batch loss
loss = criterion(output, target)
# update average validation loss
valid_loss += loss.item()*data.size(0)
http://localhost:8889/notebooks/pytorch-waste-classification-using-densenet.ipynb Page 9 of 14
pytorch-waste-classification-using-densenet - Jupyter Notebook 10/05/24, 9:45 AM
train_loss = train_loss/len(train_loader.sampler)
valid_loss = valid_loss/len(valid_loader.sampler)
http://localhost:8889/notebooks/pytorch-waste-classification-using-densenet.ipynb Page 10 of 14
pytorch-waste-classification-using-densenet - Jupyter Notebook 10/05/24, 9:45 AM
In [29]: model.load_state_dict(torch.load('model_waste.pt'))
http://localhost:8889/notebooks/pytorch-waste-classification-using-densenet.ipynb Page 11 of 14
pytorch-waste-classification-using-densenet - Jupyter Notebook 10/05/24, 9:45 AM
model.eval()
# iterate over test data
for data, target in test_loader:
# move tensors to GPU if CUDA is available
if train_on_gpu:
data, target = data.cuda(), target.cuda()
# forward pass: compute predicted outputs by passing inputs to the
output = model(data)
# calculate the batch loss
loss = criterion(output, target)
# update test loss
test_loss += loss.item()*data.size(0)
# convert output probabilities to predicted class
_, pred = torch.max(output, 1)
# compare predictions to true label
correct_tensor = pred.eq(target.data.view_as(pred))
correct = np.squeeze(correct_tensor.numpy()) if not train_on_gpu el
# calculate test accuracy for each object class
for i in range(2):
label = target.data[i]
class_correct[label] += correct[i].item()
class_total[label] += 1
for i in range(2):
if class_total[i] > 0:
print('Test Accuracy of %5s: %2d%% (%2d/%2d)' % (
classes[i], 100 * class_correct[i] / class_total[i],
np.sum(class_correct[i]), np.sum(class_total[i])))
else:
print('Test Accuracy of %5s: N/A (no training examples)' % (cla
http://localhost:8889/notebooks/pytorch-waste-classification-using-densenet.ipynb Page 12 of 14
pytorch-waste-classification-using-densenet - Jupyter Notebook 10/05/24, 9:45 AM
The model has 91% accuracy for Recyclable waste. But, a whopping 98% accuracy for
organic waste.
# plot the images in the batch, along with predicted and true labels
fig = plt.figure(figsize=(25, 4))
for idx in np.arange(20):
ax = fig.add_subplot(2, int(20/2), idx+1, xticks=[], yticks=[])
imshow(images.cpu()[idx])
ax.set_title("{} ({})".format(classes[preds[idx]], classes[labels[i
color=("green" if preds[idx]==labels[idx].item() else
Clipping input data to the valid range for imshow with RGB data ([
0..1] for floats or [0..255] for integers).
Clipping input data to the valid range for imshow with RGB data ([
0..1] for floats or [0..255] for integers).
Clipping input data to the valid range for imshow with RGB data ([
0..1] for floats or [0..255] for integers).
Clipping input data to the valid range for imshow with RGB data ([
0..1] for floats or [0..255] for integers).
Clipping input data to the valid range for imshow with RGB data ([
0..1] for floats or [0..255] for integers).
Clipping input data to the valid range for imshow with RGB data ([
0..1] for floats or [0..255] for integers).
Clipping input data to the valid range for imshow with RGB data ([
0..1] for floats or [0..255] for integers).
Clipping input data to the valid range for imshow with RGB data ([
0..1] for floats or [0..255] for integers).
Clipping input data to the valid range for imshow with RGB data ([
0..1] for floats or [0..255] for integers).
Clipping input data to the valid range for imshow with RGB data ([
0..1] for floats or [0..255] for integers).
Clipping input data to the valid range for imshow with RGB data ([
http://localhost:8889/notebooks/pytorch-waste-classification-using-densenet.ipynb Page 13 of 14
pytorch-waste-classification-using-densenet - Jupyter Notebook 10/05/24, 9:45 AM
In [ ]:
http://localhost:8889/notebooks/pytorch-waste-classification-using-densenet.ipynb Page 14 of 14