skip to content

Spread the word.

Share the link on social media.

Share
  • Facebook
Have an account? Sign In Now

Sign Up


Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here


Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.


Have an account? Sign In Now

Sorry, you do not have permission to ask a question, You must login to ask a question.


Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

Analytics Jobs

Analytics Jobs Logo Analytics Jobs Logo
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Popular Course Rankings 2024
    • Best Data Science Course
    • Best Full Stack Developer Course
    • Best Product Management Courses
    • Best Data Analyst Course
    • Best UI UX Design Course
    • Best Web Designing Course
    • Best Cyber Security Course
    • Best Digital Marketing Course
    • Best Cloud Computing Courses
    • Best DevOps Course
    • Best Artificial Intelligence Course
    • Best Machine Learning Course
    • Best Front end-Development Courses
    • Best Back-end Development Courses
    • Best Mobile App Development Courses
    • Best Blockchain Development Courses
    • Best Game Designing/Development Courses
    • Best AR/VR Courses
  • Popular Career Tracks 2024
    • How to become a data scientist?
    • How to become a full stack developer?
    • how to become a product manager?
    • how to become a data analyst
    • how to become a ui ux designer
    • how to become a web designer?
    • how to become a cybersecurity professional?
    • how to become a digital marketing expert
    • how to become a cloud engineer?
    • how to become a DevOps engineer?
    • Career in artificial intelligence
    • how to become a machine learning engineer?
    • How to become a Front-end Developer
    • How to Become a Back-end Developer
    • How to become a mobile app developer?
  • Suggest Me a Course/Program
  • AJ Founders
  • Looking for Jobs?
    • Jobs in Data Science
    • Jobs in Javascript
    • Jobs in Python
    • Jobs in iOS
    • Jobs in Android

Analytics Jobs Latest Questions

Analytics Jobs
Analytics JobsEnlightened
Asked: January 12, 20242024-01-12T16:15:18+05:30 2024-01-12T16:15:18+05:30

How can I implement a binary image classification model using PyTorch and transfer learning with the Dogs vs. Cats dataset?

Welcome to our deep dive into binary image classification using PyTorch! In this tutorial, we’ll explore how to build and train a convolutional neural network (CNN) to distinguish between images of dogs and cats. We’ll adopt a transfer learning approach, leveraging a pre-trained network to boost our model’s performance. Our dataset for this adventure is the freely available ‘Dogs vs. Cats’ dataset from Kaggle.

Setting Up the Environment

Before we begin, ensure you have PyTorch installed. If not, you can install it via pip:

pip install torch torchvision

Also, download the ‘Dogs vs. Cats’ dataset from Kaggle and extract it into a folder named data.

Data Preparation

First, let’s prepare our dataset. We’ll split it into training and validation sets and apply the necessary transformations.

import os
import torch
from torchvision import datasets, transforms

# Define transformations
transform = transforms.Compose([
transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
])

# Load datasets
train_dataset = datasets.ImageFolder(root='data/train', transform=transform)
val_dataset = datasets.ImageFolder(root='data/val', transform=transform)

# Data loaders
train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=32, shuffle=True)
val_loader = torch.utils.data.DataLoader(val_dataset, batch_size=32, shuffle=False)

Transfer Learning with a Pre-trained Model

We’ll use a pre-trained model from torchvision’s models. Let’s choose ResNet-18 for its balance between performance and computational efficiency.

from torchvision import models

# Load pre-trained ResNet-18
model = models.resnet18(pretrained=True)

# Freeze parameters
for param in model.parameters():
param.requires_grad = False

# Modify the final layer for binary classification
num_ftrs = model.fc.in_features
model.fc = torch.nn.Linear(num_ftrs, 2)

Training the Model

Now, let’s train our model. We’ll use the cross-entropy loss and an optimizer.

import torch.optim as optim
from torch.optim import lr_scheduler

criterion = torch.nn.CrossEntropyLoss()
optimizer = optim.Adam(model.fc.parameters(), lr=0.001)
scheduler = lr_scheduler.StepLR(optimizer, step_size=7, gamma=0.1)

def train_model(model, criterion, optimizer, scheduler, num_epochs=25):
for epoch in range(num_epochs):
# Training phase
model.train()
running_loss = 0.0
running_corrects = 0

for inputs, labels in train_loader:
optimizer.zero_grad()
outputs = model(inputs)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()

running_loss += loss.item() * inputs.size(0)
_, preds = torch.max(outputs, 1)
running_corrects += torch.sum(preds == labels.data)

scheduler.step()
epoch_loss = running_loss / len(train_dataset)
epoch_acc = running_corrects.double() / len(train_dataset)

print(f'Epoch {epoch}/{num_epochs - 1}, Loss: {epoch_loss:.4f}, Acc: {epoch_acc:.4f}')

# Train the model
train_model(model, criterion, optimizer, scheduler)

Evaluating the Model

After training, let’s evaluate the model on the validation set.

def evaluate_model(model, val_loader):
model.eval()
running_corrects = 0

with torch.no_grad():
for inputs, labels in val_loader:
outputs = model(inputs)
_, preds = torch.max(outputs, 1)
running_corrects += torch.sum(preds == labels.data)

acc = running_corrects.double() / len(val_dataset)
print(f'Validation Acc: {acc:.4f}')

# Evaluate the model
evaluate_model(model, val_loader)

Inference on New Images

Finally, let’s use our trained model to predict new images.

from PIL import Image

def predict_image(image_path, model, transform):
image = Image.open(image_path)
image = transform(image).unsqueeze(0)

model.eval()
with torch.no_grad():
outputs = model(image)
_, preds = torch.max(outputs, 1)

return 'Cat' if preds[0] == 0 else 'Dog'

# Example usage
image_path = 'path_to_your_image.jpg'
print(predict_image(image_path, model, transform))

Congratulations! You’ve successfully trained a convolutional neural network for binary image classification using PyTorch and transfer learning. This tutorial is just the beginning of your journey in deep learning. Explore further by tweaking the model, experimenting with different pre-trained networks, and adjusting hyperparameters.

This article provides a step-by-step guide on building and training a CNN for binary image classification using PyTorch, with practical code snippets for each step. It’s designed to be informative and accessible, suitable for learners and practitioners in the field of machine learning and computer vision.

Help me with your thoughts on this.

  • 1 1 Answer
  • 30 Views
  • 0 Followers
  • 0
    • Report
  • Share
    Share
    • Share on Facebook
    • Share on Twitter
    • Share on LinkedIn
    • Share on WhatsApp

You must login to add an answer.


Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Analytics Jobs
    Analytics Jobs Enlightened
    2024-01-12T17:39:48+05:30Added an answer on January 12, 2024 at 5:39 pm

    The above content provides a comprehensive guide on using PyTorch to develop a binary image classification model. The tutorial focuses on distinguishing between images of dogs and cats using the ‘Dogs vs. Cats’ dataset from Kaggle. Key steps include setting up the environment, preparing the data, employing a pre-trained model (ResNet-18) for transfer learning, training the model, and evaluating its performance. It also covers how to use the trained model for inference on new images. The guide is designed to be accessible and practical, offering step-by-step instructions and code snippets, making it suitable for learners and practitioners in machine learning and computer vision.

    • 1
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Suggest Me a Course
top-10-data-science-machine-learning-institutes-in-india-ranking
top-30-companies-in-india-to-work-for-in-data-science-and-machine-learning
data-science-b-tech-colleges-in-india
  • Popular
  • Answers
  • Subhash Kumar

    Henry Harvin Reviews - Career Tracks, Courses, Learning Mode, Fee, ...

    • 84 Answers
  • Analytics Jobs

    Scaler Academy Reviews – Career Tracks, Courses, Learning Mode, Fee, ...

    • 44 Answers
  • Analytics Jobs

    UpGrad Reviews - Career Tracks, Courses, Learning Mode, Fee, Reviews, ...

    • 42 Answers
  • AJ Guru
    AJ Guru added an answer Hey junior, great question! "Who is the Father of AI… December 22, 2025 at 1:26 pm
  • AJ Guru
    AJ Guru added an answer Primary and secondary technical domain skills are simply two different… December 20, 2025 at 9:03 pm
  • AJ Mentor
    AJ Guru added an answer If you are looking for only genuine UpGrad reviews of… December 20, 2025 at 1:38 pm

Category

  • Accounting and Finance
  • AJ Finance
  • AJ Tech
  • Banking
  • Big Data
  • Blockchain
  • Blog
  • Business
  • Cloud Computing
  • Coding
  • Coding / Development
  • Course Review & Ranking
  • Cyber Security
  • Data Science & AI
  • Data Science, Artificial Intelligence, Analytics
  • DevOps
  • Digital Marketing
  • Grow My Business
  • Leadership
  • My StartUp Story
  • Product Management
  • Robotic Process Automation (RPA)
  • Software Testing
  • Start My Business
  • Wealth Management

Explore

  • Popular Course Rankings 2024
    • Best Data Science Course
    • Best Full Stack Developer Course
    • Best Product Management Courses
    • Best Data Analyst Course
    • Best UI UX Design Course
    • Best Web Designing Course
    • Best Cyber Security Course
    • Best Digital Marketing Course
    • Best Cloud Computing Courses
    • Best DevOps Course
    • Best Artificial Intelligence Course
    • Best Machine Learning Course
    • Best Front end-Development Courses
    • Best Back-end Development Courses
    • Best Mobile App Development Courses
    • Best Blockchain Development Courses
    • Best Game Designing/Development Courses
    • Best AR/VR Courses
  • Popular Career Tracks 2024
    • How to become a data scientist?
    • How to become a full stack developer?
    • how to become a product manager?
    • how to become a data analyst
    • how to become a ui ux designer
    • how to become a web designer?
    • how to become a cybersecurity professional?
    • how to become a digital marketing expert
    • how to become a cloud engineer?
    • how to become a DevOps engineer?
    • Career in artificial intelligence
    • how to become a machine learning engineer?
    • How to become a Front-end Developer
    • How to Become a Back-end Developer
    • How to become a mobile app developer?
  • Suggest Me a Course/Program
  • AJ Founders
  • Looking for Jobs?
    • Jobs in Data Science
    • Jobs in Javascript
    • Jobs in Python
    • Jobs in iOS
    • Jobs in Android
aalan

Footer

Social media

About Analytics Jobs

  • About Us
  • Videos
  • FAQs
  • Careers
  • Contact Us
  • Press
  • Sitemap

Our Services

  • Advertise with us
  • Upcoming Awards & Rankings
  • Write for us

Our Brands

  • AJ Founders
  • Aj Tech
  • AJ Finance
  • AJ Entertainment

Terms

  • Terms of Use
  • Privacy Policy
  • Disclaimer

Footer 1

Copyright © , Analytics Jobs. All right reserved.

Get Free Career
Counselling from
Experts

Book a Session with an
Industry Professional today!
By continuing you agree to our Terms of Service and Privacy Policy, and you consent to receive offers and opportunities from the Analytics Jobs platform listed EdTech’s by telephone, text message, and email.