Install the ultralytics package for YOLOv8 (if not already installed)
!pip install ultralytics
Import necessary libraries
import pandas as pd
import numpy as np
import torch
from torch.utils.data import Dataset, DataLoader
from tqdm.notebook import tqdm
from torchvision import transforms
from PIL import Image
import torch.nn as nn
Suppress warnings from YOLO and transformers
import warnings
warnings.filterwarnings("ignore")
Mount Google Drive if needed
from google.colab import drive
drive.mount('/content/drive')
Load the CSV file
csv_file = '/content/scenario32_dev.csv' # Replace with your actual path
df = pd.read_csv(csv_file)
can you modify this code to increace the accuracy of the beam prediction use can use google vit and yolo bigger version also make some other change which you think will impove the accuracy
and give full code in one block
Certainly! I've modified your code to improve the accuracy of the beam prediction. Changes include:
Switched to larger models: Using 'yolov8l-seg.pt' for the YOLO segmentation model and 'google/vit-large-patch16-384' for the ViT model, with image size adjusted accordingly.
Added data augmentation: Using the albumentations library to apply the same transformations to both images and segmentation masks.
Adjusted hyperparameters: Increased the number of epochs, adjusted learning rate, added weight decay, and included a learning rate scheduler.
Implemented model checkpointing: Saving the best model based on validation loss.
Below is the full updated code in one block:
python
# Install necessary packages
# !pip install ultralytics albumentations
# Suppress warnings
import warnings
warnings.filterwarnings("ignore")
# Import necessary libraries
import pandas as pd
import numpy as np
import torch
from torch.utils.data import Dataset, DataLoader
from torchvision import transforms
from PIL import Image
import torch.nn as nn
from tqdm.notebook import tqdm
import matplotlib.pyplot as plt
# Import YOLOv8
from ultralytics import YOLO
import logging
logging.getLogger('ultralytics').setLevel(logging.ERROR)
# Import ViT
from transformers import ViTModel, ViTImageProcessor
# Import albumentations
import albumentations as A
from albumentations.pytorch import ToTensorV2
# Load the CSV file
csv_file = '/content/scenario32_dev.csv' # Replace with your actual path
df = pd.read_csv(csv_file)
# Load the pre-trained YOLOv8 segmentation model
yolo_model = YOLO('yolov8l-seg.pt') # Using 'l'arge model for better accuracy
# Define the transforms using albumentations
# For ViT 'vit-large-patch16-384', we need to resize images to 384x384
image_size = 384
# Mean and std for normalization
model_name = 'google/vit-large-patch16-384'
image_processor = ViTImageProcessor.from_pretrained(model_name)
albumentations_transforms = A.Compose([
A.Resize(image_size, image_size),
A.HorizontalFlip(p=0.5),
A.RandomRotate90(p=0.5),
A.ColorJitter(p=0.5),
A.Normalize(mean=image_processor.image_mean, std=image_processor.image_std, max_pixel_value=255.0),
ToTensorV2()
])
# Create a custom dataset class
class BeamDataset(Dataset):
def __init__(self, dataframe, transform=None, label_mapping=None):
self.data = dataframe.reset_index(drop=True)
self.image_paths = self.data['unit1_rgb']
self.labels = self.data['unit1_beam']
self.transform = transform
self.label_mapping = label_mapping
# Map labels to indices
self.labels = self.labels.map(self.label_mapping).astype(int)
def __len__(self):
return len(self.data)
def __getitem__(self, idx):
img_path = self.image_paths.iloc[idx]
# Load image
image = np.array(Image.open(img_path).convert('RGB'))
# Perform YOLOv8 segmentation without verbose output
results = yolo_model(img_path, verbose=False)
# Get the segmentation mask
masks = results[0].masks.data.cpu().numpy() # Shape: (num_objects, H, W)
# If no objects detected, create an empty mask
if len(masks) == 0:
seg_mask = np.zeros((image.shape[0], image.shape[1]), dtype=np.uint8)
else:
# Combine all masks into a single mask
seg_mask = np.sum(masks, axis=0)
seg_mask = np.clip(seg_mask, 0, 1).astype(np.uint8)
# Ensure seg_mask is a single-channel image
# Convert segmentation mask to proper format
seg_mask = seg_mask * 255 # Scale to 0-255
# Apply transforms
if self.transform:
augmented = self.transform(image=image, mask=seg_mask)
image = augmented['image']
seg_mask = augmented['mask']
# For the mask, replicate the single channel to three channels
seg_mask = seg_mask.repeat(3, 1, 1) # Convert from (1, H, W) to (3, H, W)
else:
# Default transform
transform = transforms.Compose([
transforms.Resize((image_size, image_size)),
transforms.ToTensor(),
transforms.Normalize(mean=image_processor.image_mean, std=image_processor.image_std)
])
image = transform(Image.fromarray(image))
seg_mask = transform(Image.fromarray(seg_mask))
seg_mask = seg_mask.repeat(3, 1, 1)
label = self.labels.iloc[idx]
return {'image': image, 'seg_mask': seg_mask, 'label': label}
# Create label mapping
all_labels = df['unit1_beam'].unique()
label_mapping = {label: idx for idx, label in enumerate(sorted(all_labels))}
num_labels = len(label_mapping)
# Split the dataset into training and testing sets
from sklearn.model_selection import train_test_split
train_df, test_df = train_test_split(df, test_size=0.2, random_state=42, stratify=df['unit1_beam'])
train_dataset = BeamDataset(train_df, transform=albumentations_transforms, label_mapping=label_mapping)
test_dataset = BeamDataset(test_df, transform=albumentations_transforms, label_mapping=label_mapping)
train_loader = DataLoader(train_dataset, batch_size=8, shuffle=True, num_workers=2)
test_loader = DataLoader(test_dataset, batch_size=8, shuffle=False, num_workers=2)
# Load pre-trained ViT models for images and segmentation masks
vit_image = ViTModel.from_pretrained(model_name)
vit_segmentation = ViTModel.from_pretrained(model_name)
# Move models to device
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
vit_image.to(device)
vit_segmentation.to(device)
# Define the combined model
class BeamPredictionModel(nn.Module):
def __init__(self, num_labels):
super(BeamPredictionModel, self).__init__()
self.vit_image = vit_image
self.vit_segmentation = vit_segmentation
self.dropout = nn.Dropout(0.1)
self.classifier = nn.Linear(vit_image.config.hidden_size * 2, num_labels)
def forward(self, image, seg_mask):
# Pass through ViT models
image_outputs = self.vit_image(pixel_values=image)['pooler_output']
seg_outputs = self.vit_segmentation(pixel_values=seg_mask)['pooler_output']
# Concatenate embeddings
combined_representation = torch.cat(
(image_outputs, seg_outputs), dim=1
)
# Classification
x = self.dropout(combined_representation)
logits = self.classifier(x)
return logits
# Initialize the model
model = BeamPredictionModel(num_labels)
model.to(device)
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.AdamW(model.parameters(), lr=2e-5, weight_decay=0.01)
# Learning rate scheduler
scheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size=3, gamma=0.1)
# Use mixed precision
scaler = torch.cuda.amp.GradScaler()
# Initialize lists to store metrics
train_losses = []
val_losses = []
val_top1_accuracies = []
val_top2_accuracies = []
val_top3_accuracies = []
val_dba_scores = []
# Model checkpointing
best_val_loss = float('inf')
# Training loop
num_epochs = 10 # Adjust the number of epochs as needed
for epoch in range(num_epochs):
model.train()
total_loss = 0
progress_bar = tqdm(train_loader, desc=f"Epoch {epoch+1}/{num_epochs}")
for batch in progress_bar:
images = batch['image'].to(device)
seg_masks = batch['seg_mask'].to(device)
labels = batch['label'].to(device)
optimizer.zero_grad()
with torch.cuda.amp.autocast():
logits = model(images, seg_masks)
loss = criterion(logits, labels)
scaler.scale(loss).backward()
scaler.step(optimizer)
scaler.update()
total_loss += loss.item()
progress_bar.set_postfix(loss=loss.item())
avg_loss = total_loss / len(train_loader)
train_losses.append(avg_loss)
print(f"Epoch [{epoch+1}/{num_epochs}], Training Loss: {avg_loss:.4f}")
# Evaluate on the test set
model.eval()
total_correct_top1 = 0
total_correct_top2 = 0
total_correct_top3 = 0
total_samples = 0
total_dba = 0
total_val_loss = 0
with torch.no_grad():
for batch in test_loader:
images = batch['image'].to(device)
seg_masks = batch['seg_mask'].to(device)
labels = batch['label'].to(device)
logits = model(images, seg_masks)
val_loss = criterion(logits, labels)
total_val_loss += val_loss.item()
# Get top-k predictions
_, preds_topk = logits.topk(3, dim=1)
correct_topk = preds_topk.eq(labels.view(-1, 1)) # Shape: (batch_size, 3)
# Compute Top-1 accuracy
total_correct_top1 += correct_topk[:, 0].sum().item()
# Compute Top-2 accuracy
total_correct_top2 += correct_topk[:, :2].any(dim=1).sum().item()
# Compute Top-3 accuracy
total_correct_top3 += correct_topk.any(dim=1).sum().item()
# Compute DBA score
probs = torch.softmax(logits, dim=1)
batch_size = labels.size(0)
for i in range(batch_size):
prob = probs[i]
label = labels[i]
sorted_probs, indices = prob.sort(descending=True)
rank = (indices == label).nonzero(as_tuple=True)[0].item() + 1 # Rank starts from 1
total_dba += 1.0 / rank
total_samples += labels.size(0)
avg_val_loss = total_val_loss / len(test_loader)
val_losses.append(avg_val_loss)
top1_accuracy = total_correct_top1 / total_samples
top2_accuracy = total_correct_top2 / total_samples
top3_accuracy = total_correct_top3 / total_samples
avg_dba = total_dba / total_samples
val_top1_accuracies.append(top1_accuracy)
val_top2_accuracies.append(top2_accuracy)
val_top3_accuracies.append(top3_accuracy)
val_dba_scores.append(avg_dba)
print(f"Validation Loss: {avg_val_loss:.4f}")
print(f"Validation Top-1 Accuracy: {top1_accuracy:.4f}")
print(f"Validation Top-2 Accuracy: {top2_accuracy:.4f}")
print(f"Validation Top-3 Accuracy: {top3_accuracy:.4f}")
print(f"Validation DBA Score: {avg_dba:.4f}")
# Update the learning rate
scheduler.step()
# Save the best model
if avg_val_loss < best_val_loss:
best_val_loss = avg_val_loss
torch.save(model.state_dict(), 'best_model.pt')
print("Best model saved!")
# Plotting Training Loss over Epochs
plt.figure(figsize=(8, 6))
plt.plot(range(1, num_epochs+1), train_losses, label='Training Loss')
plt.plot(range(1, num_epochs+1), val_losses, label='Validation Loss')
plt.xlabel('Epoch')
plt.ylabel('Loss')
plt.title('Training and Validation Loss over Epochs')
plt.legend()
plt.grid(True)
plt.show()
# Plotting Top-1, Top-2, Top-3 Accuracy over Epochs
plt.figure(figsize=(8, 6))
plt.plot(range(1, num_epochs+1), val_top1_accuracies, label='Top-1 Accuracy')
plt.plot(range(1, num_epochs+1), val_top2_accuracies, label='Top-2 Accuracy')
plt.plot(range(1, num_epochs+1), val_top3_accuracies, label='Top-3 Accuracy')
plt.xlabel('Epoch')
plt.ylabel('Accuracy')
plt.title('Top-1, Top-2, Top-3 Accuracy over Epochs')
plt.legend()
plt.grid(True)
plt.show()
# Plotting DBA Score over Epochs
plt.figure(figsize=(8, 6))
plt.plot(range(1, num_epochs+1), val_dba_scores, label='DBA Score', marker='o')
plt.xlabel('Epoch')
plt.ylabel('DBA Score')
plt.title('DBA Score over Epochs')
plt.legend()
plt.grid(True)
plt.show()
Notes:
Ensure that you have the necessary packages installed (ultralytics, albumentations, and transformers).
Replace '/content/scenario32_dev.csv' with the actual path to your CSV file.
Make sure your dataset is properly formatted and that the image paths and labels are correctly specified.
The BeamDataset class now uses albumentations to apply the same random transformations to both the images and the segmentation masks.
The ViT model has been switched to a larger version ('google/vit-large-patch16-384') with an adjusted image size.
The number of epochs has been increased to 10, and learning rate adjustments have been made.
Model checkpointing saves the best model based on validation loss.
By making these changes, the model should achieve higher accuracy on the beam prediction task.