Regression tasks with images require a specialized setup, different from typical classification or segmentation problems. For this, I created a minimalist image regression framework using PyTorch. It's designed to help you quickly set up and run regression models, with a flexible codebase that you can extend for custom datasets and architectures. You can find the repository on GitHub.
The structure of the repository is organized to make it easy to train and test your models. The key components include a dataset of images, CSV files with labels, a CNN model, training and evaluation scripts, and a basic training loop. Here's a breakdown of the main files:
train.csv and test.csv to map images to target values.1_100_100.pth and 3_100_100.pth).
The core of this project is the CNNRegression model, a convolutional neural network designed for image regression tasks. The network consists of two convolutional layers followed by fully connected layers. It outputs two values, which in my case represent the x and y coordinates of a target angle.
The network is simple but effective for a variety of regression tasks, and it can be easily extended. Here is a glimpse into the architecture:
self.conv1 = nn.Conv2d(in_channels=self.image_size[0], out_channels=4, kernel_size=3, stride=1, padding=1)
self.pool1 = nn.MaxPool2d(kernel_size=2, stride=2)
self.conv2 = nn.Conv2d(in_channels=4, out_channels=16, kernel_size=3, stride=1, padding=1)
self.pool2 = nn.MaxPool2d(kernel_size=2, stride=2)
self.fc1 = nn.Linear(in_features=16 * (image_size[1] // 4) * (image_size[2] // 4), out_features=128)
self.fc2 = nn.Linear(in_features=128, out_features=2)
You can see how it uses convolutional layers with ReLU activation and max pooling, followed by fully connected layers to predict two continuous outputs (e.g., angles, coordinates). The model is designed to handle 100x100 image inputs but can be adapted for different sizes.
The training loop, implemented in network.py, allows you to train the CNN using Mean Squared Error (MSE) as the loss function. It includes a basic Adam optimizer and leverages PyTorch’s DataLoader for efficient data batching. You can specify the number of epochs and other parameters when calling the train_network function.
Here’s how you can start training:
python network.py
During training, TensorBoard can be used to visualize the loss values and track performance over time, making it easy to monitor the model’s progress.
The dataset consists of image files and corresponding CSV files for training and testing. In data_loading.py, the dataset is preprocessed and loaded into PyTorch DataLoader objects. Images are resized and normalized, and the labels are read from the CSV files. The data loading process supports grayscale or RGB images.
You can generate a sample dataset using the generate_sample_dataset.py script, which creates random images and labels. This is useful if you want to experiment with the framework before working with your real-world data.
After training, the model can be saved for later use. The repository includes utility functions to save and load models as .pth files. This allows you to easily save a trained model and reload it later for evaluation or prediction:
# Save the model after training
save_model(model, filename='my_model.pth')
# Load the model for later use
model = load_model(image_size=(3, 100, 100), filename='my_model.pth')
These functions help maintain flexibility when working with different image sizes and datasets. The model architecture is restored during the loading process, and the weights are reloaded from the saved file.
Once the model is trained, you can evaluate it on the test dataset using the evaluate_network function in network.py. This function computes the Mean Squared Error (MSE) on the test data and calculates the angle error (if relevant to your task).
# Evaluate the model on the test set
evaluate_network(model, device, image_size=(3, 100, 100))
The evaluate_network function also calculates the mean angle error between the predicted and target angles in degrees. This provides a human-readable metric for performance in tasks like predicting orientations or directions.
With this setup, you can test the model on new data, visualize the predictions, and adjust the model as needed based on the evaluation results.
The PyTorch Image Regression repository provides a simple yet flexible framework for image regression tasks. With its modular structure, it’s easy to extend or adapt the code for your specific use case, whether you're predicting angles, coordinates, or other continuous values from images.
The provided CNN model, training loop, and data loading scripts offer a great starting point for both beginners and experienced practitioners working with image regression. You can customize the model, integrate it with your own datasets, or use the pretrained models included in the repository.
Feel free to explore the repository and experiment with the code. If you have questions or suggestions for improvements, contributions are welcome!
Full code and documentation can be found on the GitHub repository.
This project is licensed under the MIT License. See the LICENSE file in the repository for more details.