This panda_cat_dog_classification app classifies between panda, cat, or dog. So the input field is going to take input an image of one of three classes of dog, cat and panda.Then as output, it is going to show the name of the animal to which it belongs. It first processes the data and resizes it. Then custom CNN model is developed. The loss function and optimizer are calculated.
After that, the custom model is trained and tested then the app is launched using gradio in Hugging Face.
Data Preprocessing
The image dataset is preprocessed with the following portion:
transforms.Resize((224,224)) resizes the input image to (224, 224) pixels.
transforms.ToTensor() converts the input image into a PyTorch tensor. Neural networks typically operate on tensors, so this transformation converts the image into a format suitable for further processing.
transforms.Normalize(()) normalizes the tensor image with mean and standard deviation. The values provided are mean and standard deviation values for each channel in the tensor.
Model Architecture
The model was trained with custom CNN() model. this CNN architecture consists of two convolutional layers followed by two fully connected layers, and it is designed for a classification task with three classes.
bash
1class CNN(nn.Module):
2 def __init__(self):
3 super(CNN, self).__init__()4 self.conv1 = nn.Conv2d(3, 6, 5)5 self.conv2 = nn.Conv2d(6, 16, 5)6 self.pool = nn.MaxPool2d(2, 2)7 self.fc1 = nn.Linear(16 * 53 * 53, 120)8 self.fc2 = nn.Linear(120, 84)9 self.fc3 = nn.Linear(84, 3)1011 def forward(self, x):
12 x = self.conv1(x)13 x = self.pool(x)14 x = self.conv2(x)15 x = self.pool(x)16 x = x.view(-1, 16 * 53 * 53)17 x = self.fc1(x)18 x = self.fc2(x)19 x = self.fc3(x)20return x
21
Then used batch_size = 8 and CrossEntropyLoss() for loss function. Then used Adam optimizer with a learning rate 0.001 for optimization process.
Loading the data then breaking it into mini batches. Then forward pass and loss function calculation. After that backward propagation and optimization.
Backward Propagation and Optimization:
This portion is going to create an interface for taking the image input. Then example images and output is defined to be the classes from cat, dog and panda.
Now with the following the interface of the app is loaded.
iface.launch()
The app interface looks like this:
image/png
Project Structure
bash
1|2|---app_data
3||---images(used for examples)4|5|---models
6||---cat_dog_cnn.pt
7|8|---train(image dataset for training)9|10|---test(image dataset for testing)11|12|---Readme.md(about project)13|14|---app.py(the interface for project)15|16|---requirements.txt(libraries needed for project)17|18|---main.ipynb(project code)