0% found this document useful (0 votes)
21 views3 pages

Training MobileNetV2 on HAM10000

The document outlines a PyTorch implementation for training a MobileNetV2 model on the HAM10000 dataset for multi-class classification. It includes data preprocessing, model modification, loss function and optimizer setup, and a training loop with validation. Finally, it visualizes the training and validation accuracy over epochs.

Uploaded by

Smita Konda
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views3 pages

Training MobileNetV2 on HAM10000

The document outlines a PyTorch implementation for training a MobileNetV2 model on the HAM10000 dataset for multi-class classification. It includes data preprocessing, model modification, loss function and optimizer setup, and a training loop with validation. Finally, it visualizes the training and validation accuracy over epochs.

Uploaded by

Smita Konda
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

import torch

import [Link] as nn
import [Link] as optim
from [Link] import DataLoader
from torchvision import transforms, models
import kagglehub

# Load and preprocess the HAM10000 dataset


from [Link] import ImageFolder

# Define data transformations


transform = [Link]([
[Link]((224, 224)), # Resize images to match
MobileNetV2 input size
[Link](),
[Link](mean=[0.485, 0.456, 0.406], std=[0.229, 0.224,
0.225]) # Normalize using ImageNet mean and std
])

# Load the dataset


train_dataset =
ImageFolder(root='[Link]
3Ppzke-My_iHbbqziMSNd-z/[Link]', transform=transform)
val_dataset =
ImageFolder(root='[Link]
3Ppzke-My_iHbbqziMSNd-z/[Link]', transform=transform)

# Create DataLoaders
train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)
val_loader = DataLoader(val_dataset, batch_size=32, shuffle=False)

# Load the pre-trained MobileNetV2 model


model = models.mobilenet_v2(pretrained=True)

# Modify the final layer for multi-class classification


num_classes = len(train_dataset.classes) # Get the number of classes
[Link][1] = [Link]([Link][1].in_features,
num_classes)

# Define loss function and optimizer


criterion = [Link]()
optimizer = [Link]([Link](), lr=0.001)

# Training loop
num_epochs = 30 # Adjust as needed
train_losses = []
train_accuracies = []
val_losses = []
val_accuracies = []

for epoch in range(num_epochs):


[Link]()
running_loss = 0.0
correct = 0
total = 0
for images, labels in train_loader:
optimizer.zero_grad()
outputs = model(images)
loss = criterion(outputs, labels)
[Link]()
[Link]()

running_loss += [Link]() * [Link](0)


_, predicted = [Link]([Link], 1)
total += [Link](0)
correct += (predicted == labels).sum().item()

epoch_loss = running_loss / len(train_loader.dataset)


epoch_acc = correct / total
train_losses.append(epoch_loss)
train_accuracies.append(epoch_acc)

# Validation
[Link]()
with torch.no_grad():
running_loss = 0.0
correct = 0
total = 0
for images, labels in val_loader:
outputs = model(images)
loss = criterion(outputs, labels)
running_loss += [Link]() * [Link](0)
_, predicted = [Link]([Link], 1)
total += [Link](0)
correct += (predicted == labels).sum().item()

epoch_loss = running_loss / len(val_loader.dataset)


epoch_acc = correct / total
val_losses.append(epoch_loss)
val_accuracies.append(epoch_acc)

print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss:


{epoch_loss:.4f}, Train Acc: {epoch_acc:.4f}, Val Loss: {val_losses[-
1]:.4f}, Val Acc: {val_accuracies[-1]:.4f}')

# Plot training and validation accuracy


[Link](train_accuracies, label='train')
[Link](val_accuracies, label='val')
[Link]('epoch')
[Link]('accuracy')
[Link]('Model Accuracy')
[Link]()
[Link](

You might also like