game_classifier.py
Below is the complete Python code for the video game screenshot classifier. This code implements a PyTorch neural network using transfer learning with a pre-trained model (ResNet50), data augmentation, and a custom classifier head. The code is structured for modularity, reproducibility, and ease of use.
import torch
import torch.nn as nn
import torch.optim as optim
from torch.optim import lr_scheduler
from torchvision import models, transforms, datasets
from torch.utils.data import DataLoader
import numpy as np
import matplotlib.pyplot as plt
from sklearn.metrics import confusion_matrix, classification_report
import seaborn as sns
import os
import argparse
# Set random seed for reproducibility
torch.manual_seed(42)
np.random.seed(42)
# Check if GPU is available
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
print(f"Using device: {device}")
# 1. Data Preparation and Augmentation
def create_data_loaders(data_dir, batch_size=32, img_size=(224, 224)):
"""
Creates data loaders for training, validation, and test sets with data augmentation.
Args:
data_dir (str): Root directory of the dataset.
batch_size (int): Batch size for the data loaders.
img_size (tuple): Size to which the images will be resized.
Returns:
train_loader, val_loader, test_loader, class_names: Data loaders and class names.
"""
# Data augmentation and normalization for training
# Just normalization for validation and testing
data_transforms = {
'train': transforms.Compose([
transforms.RandomResizedCrop(img_size[0], scale=(0.8, 1.0)),
transforms.RandomHorizontalFlip(),
transforms.RandomRotation(10),
transforms.ColorJitter(brightness=0.2, contrast=0.2, saturation=0.2, hue=0.1),
transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
]),
'val': transforms.Compose([
transforms.Resize(img_size),
transforms.CenterCrop(img_size),
transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
]),
'test': transforms.Compose([
transforms.Resize(img_size),
transforms.CenterCrop(img_size),
transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
]),
}
# Datasets
image_datasets = {
x: datasets.ImageFolder(os.path.join(data_dir, x), data_transforms[x])
for x in ['train', 'val', 'test']
}
# DataLoaders
data_loaders = {
x: DataLoader(image_datasets[x], batch_size=batch_size, shuffle=True if x == 'train' else False, num_workers=4)
for x in ['train', 'val', 'test']
}
class_names = image_datasets['train'].classes
dataset_sizes = {x: len(image_datasets[x]) for x in ['train', 'val', 'test']}
print(f"Class Names: {class_names}")
print(f"Dataset Sizes: {dataset_sizes}")
return data_loaders, class_names, dataset_sizes
# 2. Model Definition
class GameClassifier(nn.Module):
def __init__(self, num_classes, base_model_name="resnet50", use_pretrained=True, feature_extract=True):
"""
Initializes the game classifier model using a pre-trained CNN as a feature extractor.
Args:
num_classes (int): Number of game classes.
base_model_name (str): Name of the base pre-trained model (e.g., 'resnet50', 'efficientnet_b0').
use_pretrained (bool): Whether to use pre-trained weights.
feature_extract (bool): Whether to freeze the pre-trained model weights.
"""
super(GameClassifier, self).__init__()
# Load the pre-trained model
if base_model_name == "resnet50":
self.base_model = models.resnet50(pretrained=use_pretrained)
elif base_model_name == "efficientnet_b0":
from torchvision.models import efficientnet_b0
self.base_model = efficientnet_b0(pretrained=use_pretrained)
else:
raise ValueError(f"Model {base_model_name} not supported.")
# Freeze the pre-trained model weights if feature_extract is True
if feature_extract:
for param in self.base_model.parameters():
param.requires_grad = False
# Get the number of features from the base model
if base_model_name == "resnet50":
self.num_features = self.base_model.fc.in_features
# Remove the last fully connected layer
self.base_model.fc = nn.Identity()
elif base_model_name == "efficientnet_b0":
self.num_features = self.base_model.classifier.in_features
# Remove the last fully connected layer
self.base_model.classifier = nn.Identity()
# Define the custom classifier head
self.classifier = nn.Sequential(
nn.Linear(self.num_features, 512),
nn.ReLU(),
nn.Dropout(0.3),
nn.Linear(512, num_classes),
nn.Softmax(dim=1)
)
def forward(self, x):
# Pass the input through the base model to get the features
features = self.base_model(x)
# Pass the features through the classifier head
logits = self.classifier(features)
return logits
# 3. Training Function
def train_model(model, dataloaders, criterion, optimizer, scheduler, num_epochs=20, device="cpu"):
"""
Trains the model and returns the trained model along with training and validation losses.
Args:
model (nn.Module): The model to be trained.
dataloaders (dict): Dictionary of data loaders for 'train' and 'val'.
criterion (nn.Module): Loss function.
optimizer (optim.Optimizer): Optimizer for training.
scheduler (optim.lr_scheduler): Learning rate scheduler.
num_epochs (int): Number of epochs to train.
device (torch.device): Device to use for training (cpu or gpu).
Returns:
model: Trained model.
train_losses (list): Training losses per epoch.
val_losses (list): Validation losses per epoch.
"""
train_losses = []
val_losses = []
for epoch in range(num_epochs):
print(f'Epoch {epoch+1}/{num_epochs}')
print('-' * 10)
# Each epoch has a training and validation phase
for phase in ['train', 'val']:
if phase == 'train':
model.train() # Set model to training mode
else:
model.eval() # Set model to evaluate mode
running_loss = 0.0
running_corrects = 0
# Iterate over data
for inputs, labels in dataloaders[phase]:
inputs = inputs.to(device)
labels = labels.to(device)
# Zero the parameter gradients
optimizer.zero_grad()
# Forward
# Track history if only in train
with torch.set_grad_enabled(phase == 'train'):
outputs = model(inputs)
_, preds = torch.max(outputs, 1)
loss = criterion(outputs, labels)
# Backward + Optimize only if in training phase
if phase == 'train':
loss.backward()
optimizer.step()
# Statistics
running_loss += loss.item() * inputs.size(0)
running_corrects += torch.sum(preds == labels.data)
if phase == 'train':
scheduler.step()
epoch_loss = running_loss / len(dataloaders[phase].dataset)
epoch_acc = running_corrects.double() / len(dataloaders[phase].dataset)
print(f'{phase} Loss: {epoch_loss:.4f} Acc: {epoch_acc:.4f}')
# Store the losses
if phase == 'train':
train_losses.append(epoch_loss)
else:
val_losses.append(epoch_loss)
print()
print('Training complete')
return model, train_losses, val_losses
# 4. Evaluation Function
def evaluate_model(model, dataloader, class_names, device="cpu"):
"""
Evaluates the model on the test set and returns the confusion matrix and classification report.
Args:
model (nn.Module): The trained model.
dataloader (DataLoader): Data loader for the test set.
class_names (list): List of class names.
device (torch.device): Device to use for evaluation (cpu or gpu).
Returns:
y_true (list): True labels.
y_pred (list): Predicted labels.
accuracy (float): Overall accuracy.
"""
model.eval()
y_true = []
y_pred = []
with torch.no_grad():
for inputs, labels in dataloader:
inputs = inputs.to(device)
labels = labels.to(device)
outputs = model(inputs)
_, preds = torch.max(outputs, 1)
y_true.extend(labels.cpu().numpy())
y_pred.extend(preds.cpu().numpy())
# Calculate accuracy
accuracy = np.mean(np.array(y_true) == np.array(y_pred))
print(f"Test Accuracy: {accuracy:.4f}")
# Generate classification report
print("Classification Report:")
print(classification_report(y_true, y_pred, target_names=class_names))
# Generate confusion matrix
cm = confusion_matrix(y_true, y_pred)
plt.figure(figsize=(10, 8))
sns.heatmap(cm, annot=True, fmt='d', cmap='Blues', xticklabels=class_names, yticklabels=class_names)
plt.xlabel('Predicted')
plt.ylabel('True')
plt.title('Confusion Matrix')
plt.show()
return y_true, y_pred, accuracy
# Main function
def main(data_dir, model_name="resnet50", num_epochs=20, batch_size=32, img_size=(224, 224)):
"""
Main function to train and evaluate the model.
Args:
data_dir (str): Root directory of the dataset.
model_name (str): Name of the base pre-trained model.
num_epochs (int): Number of epochs to train.
batch_size (int): Batch size for training and validation.
img_size (tuple): Size to which the images will be resized.
"""
# 1. Create data loaders
data_loaders, class_names, dataset_sizes = create_data_loaders(data_dir, batch_size, img_size)
num_classes = len(class_names)
# 2. Initialize the model
model = GameClassifier(num_classes=num_classes, base_model_name=model_name).to(device)
# 3. Define the loss function and optimizer
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.classifier.parameters(), lr=0.001)
# Learning rate scheduler
scheduler = lr_scheduler.ReduceLROnPlateau(optimizer, 'min', patience=3, factor=0.1)
# 4. Train the model
print("Starting Training...")
model, train_losses, val_losses = train_model(model, data_loaders, criterion, optimizer, scheduler, num_epochs, device)
# 5. Plot training and validation losses
plt.plot(train_losses, label='Training Loss')
plt.plot(val_losses, label='Validation Loss')
plt.xlabel('Epoch')
plt.ylabel('Loss')
plt.title('Training and Validation Loss')
plt.legend()
plt.show()
# 6. Evaluate the model on the test set
print("Evaluating on the test set...")
_, _, _ = evaluate_model(model, data_loaders['test'], class_names, device)
# 7. Save the model
model_path = f"{model_name}_game_classifier.pth"
torch.save(model.state_dict(), model_path)
print(f"Model saved to {model_path}")
if __name__ == "__main__":
# Parse command line arguments
parser = argparse.ArgumentParser(description="Train a neural network to classify video games from screenshots.")
parser.add_argument("--data_dir", type=str, required=True, help="Path to the dataset directory.")
parser.add_argument("--model_name", type=str, default="resnet50", help="Name of the base pre-trained model (resnet50, efficientnet_b0).")
parser.add_argument("--num_epochs", type=int, default=20, help="Number of epochs to train.")
parser.add_argument("--batch_size", type=int, default=32, help="Batch size for training and validation.")
parser.add_argument("--img_size", type=int, nargs=2, default=[224, 224], help="Image size (height, width).")
args = parser.parse_args()
# Run the main function
main(args.data_dir, args.model_name, args.num_epochs, args.batch_size, args.img_size)
README.md
# Video Game Screenshot Classifier
This repository contains a PyTorch implementation of a neural network for classifying video games based on screenshots. The model uses transfer learning with a pre-trained CNN (ResNet50 or EfficientNetB0) and a custom classifier head.
## Requirements
To run this code, you need the following Python packages:
```bash
torch
torchvision
numpy
matplotlib
seaborn
scikit-learn
You can install these packages using pip:
pip install torch torchvision numpy matplotlib seaborn scikit-learn
Dataset Structure
The dataset should be organized into three main folders: train, val, and test. Each of these folders should contain subfolders named after the game titles. For example:
dataset/
│
├── train/
│ ├── GameA/
│ │ ├── image1.png
│ │ ├── image2.png
│ │ └── ...
│ ├── GameB/
│ │ ├── image1.png
│ │ └── ...
│ └── ...
│
├── val/
│ ├── GameA/
│ │ ├── image1.png
│ │ └── ...
│ ├── GameB/
│ │ └── ...
│ └── ...
│
└── test/
├── GameA/
│ ├── image1.png
│ └── ...
├── GameB/
│ └── ...
└── ...
Running the Code
1. Prepare the Dataset
Organize your dataset as described in the Dataset Structure section. Ensure that the images are in standard formats like PNG or JPG.
2. Run the Model
You can run the model using the command line. The main script is game_classifier.py. You need to specify the path to the dataset directory. Optionally, you can specify the model name, number of epochs, batch size, and image size.
Example Command
python game_classifier.py --data_dir path/to/your/dataset --model_name resnet50 --num_epochs 20 --batch_size 32 --img_size 224 224
Arguments
--data_dir: Path to the dataset directory (required).
--model_name: Name of the base pre-trained model (default: resnet50). Options: resnet50, efficientnet_b0.
--num_epochs: Number of epochs to train (default: 20).
--batch_size: Batch size for training and validation (default: 32).
--img_size: Image size (height, width) as two integers (default: 224 224).
3. Output
The script will:
- Train the model and print the training and validation losses after each epoch.
- Evaluate the model on the test set and print the accuracy, precision, recall, and F1-score for each class.
- Generate a confusion matrix to visualize the model's performance.
- Save the trained model weights to a file named
<model_name>_game_classifier.pth.
Example Output
Using device: cuda
Class Names: ['Counter-Strike: Global Offensive', 'Minecraft', 'Fortnite']
Dataset Sizes: {'train': 30000, 'val': 5000, 'test': 5000}
Starting Training...
Epoch 1/20
----------
train Loss: 0.5931 Acc: 0.7892
val Loss: 0.3456 Acc: 0.8972
...
Test Accuracy: 0.9012
Classification Report:
precision recall f1-score support
CS:GO 0.91 0.89 0.90 500
Minecraft 0.92 0.91 0.92 500
Fortnite 0.89 0.90 0.89 500
accuracy 0.90 1500
macro avg 0.91 0.90 0.90 1500
weighted avg 0.91 0.90 0.90 1500
Model saved to resnet50_game_classifier.pth
4. Inference (Optional)
To perform inference on a single image after training, you can modify the code or write a separate script. Here’s an example of how to load the model and perform inference on a single image:
import torch
from torchvision import transforms
from PIL import Image
import argparse
def load_model(model_path, num_classes, model_name="resnet50", device="cpu"):
model = GameClassifier(num_classes=num_classes, base_model_name=model_name).to(device)
model.load_state_dict(torch.load(model_path, map_location=device))
model.eval()
return model
def predict_image(model, image_path, class_names, device="cpu"):
transform = transforms.Compose([
transforms.Resize((224, 224)),
transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
])
image = Image.open(image_path)
image = transform(image).unsqueeze(0).to(device)
with torch.no_grad():
output = model(image)
_, pred = torch.max(output, 1)
predicted_class = class_names[pred.item()]
print(f"Predicted Class: {predicted_class}")
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Predict the game from a screenshot.")
parser.add_argument("--image_path", type=str, required=True, help="Path to the image.")
parser.add_argument("--model_path", type=str, required=True, help="Path to the trained model.")
parser.add_argument("--class_names", type=str, nargs="+", required=True, help="List of class names in order.")
parser.add_argument("--model_name", type=str, default="resnet50", help="Name of the base pre-trained model.")
args = parser.parse_args()
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model = load_model(args.model_path, len(args.class_names), args.model_name, device)
predict_image(model, args.image_path, args.class_names, device)
Example Command for Inference
python predict.py --image_path path/to/your/image.png --model_path resnet50_game_classifier.pth --class_names "Counter-Strike: Global Offensive" Minecraft Fortnite
Model Architecture
Base Model
The base model used is ResNet50, a pre-trained CNN from the ResNet family. ResNet50 is chosen for its balance between model size, performance, and training time. It has been pre-trained on the ImageNet dataset, which provides a strong feature extractor for image classification tasks.
Alternative: EfficientNetB0
You can also use EfficientNetB0, which is more efficient in terms of parameters and computation. To use EfficientNetB0, pass --model_name efficientnet_b0 when running the script.
Custom Classifier Head
A custom classifier head is added on top of the pre-trained model. The head consists of:
- A fully connected (linear) layer with 512 units.
- A ReLU activation function.
- A Dropout layer with a dropout rate of 0.3 to prevent overfitting.
- A final linear layer with the number of outputs equal to the number of game classes.
- A Softmax activation function to produce probabilities for each game class.
Transfer Learning
- The pre-trained model's weights are frozen initially to use it as a feature extractor.
- Only the classifier head is trained in the first few epochs.
- Optionally, you can unfreeze the last few layers of the pre-trained model for fine-tuning after the initial training.
Data Augmentation
Data augmentation is applied to the training set to improve the model's generalization. The augmentation techniques include:
- Random Resized Crop: Randomly crops and resizes the image.
- Random Horizontal Flip: Flips the image horizontally with a 50% probability.
- Random Rotation: Rotates the image by up to 10 degrees.
- Random Color Jitter: Adjusts the brightness, contrast, saturation, and hue of the image.
Training Procedure
- Loss Function: Cross-Entropy Loss.
- Optimizer: Adam optimizer with a learning rate of 0.001.
- Learning Rate Scheduler:
ReduceLROnPlateau reduces the learning rate when the validation loss plateaus.
- Batch Size: 32 (can be adjusted based on GPU memory).
- Device: Uses GPU if available, otherwise falls back to CPU.
- Epochs: Trains for a minimum of 20 epochs.
Evaluation Metrics
- Accuracy: Overall accuracy on the test set.
- Precision, Recall, and F1-Score: Calculated for each game class.
- Confusion Matrix: Visualizes the model's performance and identifies potential misclassifications.
Notes
- The model is designed to handle images of varying resolutions by resizing them to a fixed size (224x224 by default).
- The code is modular and can be easily extended for more advanced techniques like fine-tuning the pre-trained model or using different architectures.
Future Improvements
- Fine-Tuning: Unfreeze the last few layers of the pre-trained model for fine-tuning after the initial training.
- Hyperparameter Tuning: Tune hyperparameters like learning rate, batch size, and dropout rate.
- More Advanced Architectures: Experiment with more advanced architectures like Vision Transformers (ViT) or ConvNeXt.
- Class Imbalance: If the dataset is imbalanced, use techniques like class weights or oversampling.
### Explanation of Key Components
#### 1. **Data Preparation and Augmentation**
- The `create_data_loaders` function creates data loaders for the training, validation, and test sets. It applies data augmentation to the training set, including random resized crop, horizontal flip, rotation, and color jitter. The validation and test sets only use normalization and center cropping.
#### 2. **Model Architecture**
- The `GameClassifier` class defines the model architecture. It uses a pre-trained model (ResNet50 or EfficientNetB0) as a feature extractor and adds a custom classifier head on top.
- The custom classifier head consists of a linear layer with 512 units, a ReLU activation, a Dropout layer, and a final linear layer for classification.
- The pre-trained model's weights are frozen initially to use it as a feature extractor.
#### 3. **Training Loop**
- The `train_model` function implements the training loop. It trains the model for a specified number of epochs, evaluates it on the validation set after each epoch, and uses a learning rate scheduler to reduce the learning rate when the validation loss plateaus.
#### 4. **Evaluation**
- The `evaluate_model` function evaluates the model on the test set and generates a confusion matrix and classification report.
#### 5. **Main Function**
- The `main` function orchestrates the entire process: creating data loaders, initializing the model, training it, evaluating it, and saving the model.
### How to Use the Code
1. **Organize Your Dataset**: Follow the dataset structure described in the `README.md`.
2. **Run the Script**: Use the command line to run the script with the appropriate arguments.
3. **Evaluate the Model**: The script will print the evaluation metrics and save the model.
### Example Command to Run the Script
```bash
python game_classifier.py --data_dir path/to/your/dataset --model_name resnet50 --num_epochs 20 --batch_size 32 --img_size 224 224
This command will train a ResNet50-based model on your dataset for 20 epochs with a batch size of 32 and an image size of 224x224.