how do i use this
how do I use ragavsachdeva/popmanga_test to train Dinov2 i am doing this on kaggle here code
from transformers import Dinov2Config, Dinov2ForImageClassification, Trainer, TrainingArguments
from datasets import load_dataset
from PIL import Image
import numpy as np
import torch
from torch.utils.data import Dataset
Preprocess images
def read_image(path_to_image):
with open(path_to_image, "rb") as file:
image = Image.open(file).convert("RGB")
image = np.array(image)
return image
Custom dataset class
class MangaDataset(Dataset):
def init(self, dataset_split, target_size=(224, 224)): # Specify target size
self.dataset_split = dataset_split
self.target_size = target_size # Target size for resizing
def __len__(self):
return len(self.dataset_split)
def __getitem__(self, idx):
example = self.dataset_split[idx]
image_path = example["image_path"]
text_classification = example.get("text_classification", [])
# Check if text_classification is not empty
if not text_classification:
# Handle missing labels gracefully
print(f"No classification labels found for index {idx}. Assigning default label.")
label = -1 # Or some other default value indicating no label
else:
label = text_classification[0] # Select the first label if it's multi-class
image = read_image(image_path)
# Resize image to target size
image = Image.fromarray(image) # Convert numpy array back to PIL Image for resizing
image = image.resize(self.target_size, Image.LANCZOS) # Resize with high-quality resampling
image_tensor = torch.tensor(np.array(image), dtype=torch.float32).permute(2, 0, 1) / 255.0
return {"pixel_values": image_tensor, "label": torch.tensor(label, dtype=torch.long)}
Main script
if name == "main":
# Load the dataset
dataset = load_dataset("ragavsachdeva/popmanga_test", trust_remote_code=True)
# Preprocess splits
train_dataset = MangaDataset(dataset["seen"], target_size=(224, 224))
eval_dataset = MangaDataset(dataset["unseen"], target_size=(224, 224))
# Debugging: Check for missing labels in the training set
for idx in range(len(train_dataset)):
example = train_dataset[idx]
if example['label'].item() == -1: # Assuming -1 is your default value for missing labels
print(f"Missing label at index {idx}: {example}")
config = Dinov2Config.from_pretrained("facebook/dinov2-base")
model = Dinov2ForImageClassification.from_pretrained("facebook/dinov2-base", config=config)
# Define training arguments
training_args = TrainingArguments(
output_dir='./results',
per_device_train_batch_size=8,
per_device_eval_batch_size=8,
num_train_epochs=3,
learning_rate=5e-5,
eval_strategy="epoch",
save_strategy="epoch",
logging_dir='./logs',
logging_steps=10,
)
# Initialize Trainer
trainer = Trainer(
model=model,
args=training_args,
train_dataset=train_dataset,
eval_dataset=eval_dataset,
)
# Start training
trainer.train()
Hi, could you describe specifically what problem you're running into?