Update README.md

#2
by dragicakostoska - opened
Files changed (1) hide show
  1. README.md +170 -251
README.md CHANGED
@@ -4,291 +4,210 @@ library_name: pytorch
4
  pipeline_tag: image-classification
5
  tags:
6
  - image-classification
7
- - pytorch
8
  - convnext
9
  - vehicles
10
  - cars
11
  - stanford-cars
12
  - fine-grained-classification
 
 
13
  datasets:
14
  - naufalso/stanford_cars
15
  metrics:
16
  - accuracy
17
- ---
18
-
19
- # TwinCar: Deep Learning for Automotive Classification
20
-
21
- TwinCar is a deep learning project focused on vehicle classification and automotive attribute prediction. It explores and compares multiple state-of-the-art convolutional neural networks (CNNs) and Vision Transformer architectures using transfer learning techniques on public automotive datasets.
22
-
23
- The project evaluates model performance across different datasets and training strategies, including fine-tuning and feature extraction, while providing a reproducible workflow for data preparation, training, evaluation, and inference.
24
-
25
- ## Features
26
-
27
- * Comparison of multiple deep learning architectures:
28
-
29
- * EfficientNet-B0
30
- * ConvNeXt-Tiny
31
- * Vision Transformer (ViT-B/16)
32
- * Swin Transformer (Swin-T)
33
- * DeiT
34
- * Support for multiple automotive datasets:
35
-
36
- * Stanford Cars
37
- * CompCars
38
- * Transfer learning experiments with both fine-tuning and frozen-backbone approaches
39
- * Comprehensive evaluation metrics and visualizations
40
- * Batch inference demonstrations
41
- * Structured and reproducible notebook-based workflow
42
-
43
- ---
44
-
45
- ## Project Structure
46
-
47
- ```text
48
- TwinCar/
49
- β”œβ”€β”€ notebooks/
50
- β”‚ β”œβ”€β”€ 01_data_exploration.ipynb
51
- β”‚ β”œβ”€β”€ 02_data_preparation.ipynb
52
- β”‚ β”‚
53
- β”‚ β”œβ”€β”€ EfficientNet Experiments
54
- β”‚ β”œβ”€β”€ 03a_efficientnet_b0_v1.ipynb
55
- β”‚ β”œβ”€β”€ 03a_efficientnet_b0_v1_evaluation.ipynb
56
- β”‚ β”œβ”€β”€ 03b_efficientnet_b0_v2.ipynb
57
- β”‚ β”œβ”€β”€ 03b_efficientnet_b0_v2_evaluation.ipynb
58
- β”‚ β”‚
59
- β”‚ β”œβ”€β”€ ConvNeXt Experiments
60
- β”‚ β”œβ”€β”€ 04_convnext.ipynb
61
- β”‚ β”œβ”€β”€ 04_convnext_tiny_evaluation.ipynb
62
- β”‚ β”‚
63
- β”‚ β”œβ”€β”€ Stanford Cars Models
64
- β”‚ β”œβ”€β”€ ConvNeXt_Tiny - Stanford Cars.ipynb
65
- β”‚ β”œβ”€β”€ ConvNeXt_Tiny with freezing - Stanford Cars.ipynb
66
- β”‚ β”œβ”€β”€ ConvNeXt_Tiny with freezing v2 - Stanford Cars.ipynb
67
- β”‚ β”œβ”€β”€ EfficientNet_B0 - Stanford Cars.ipynb
68
- β”‚ β”œβ”€β”€ Swin_T - Stanford Cars.ipynb
69
- β”‚ β”œβ”€β”€ ViT_B_16_StanfordCars_model.ipynb
70
- β”‚ β”œβ”€β”€ deit_tiny_patch16_224 - Stanford Cars.ipynb
71
- β”‚ β”‚
72
- β”‚ β”œβ”€β”€ CompCars Models
73
- β”‚ β”œβ”€β”€ 06_compcars_efficientnet_b0_make_model_year.ipynb
74
- β”‚ β”œβ”€β”€ EfficientNet_B0 - Comp Cars.ipynb
75
- β”‚ β”œβ”€β”€ ConvNeXt_Tiny - Comp Cars.ipynb
76
- β”‚ β”œβ”€β”€ CompCars_ViT_model.ipynb
77
- β”‚ β”‚
78
- β”‚ β”œβ”€β”€ 05_batch_prediction_demo.ipynb
79
- β”‚ └── ml-final-project.ipynb
80
- β”‚
81
- β”œβ”€β”€ models/
82
- β”œβ”€β”€ reports/
83
- β”œβ”€β”€ scripts/
84
- β”œβ”€β”€ requirements.txt
85
- └── README.md
86
- ```
87
-
88
- ---
89
-
90
- ## Datasets
91
-
92
- ### Stanford Cars
93
-
94
- A fine-grained vehicle classification dataset containing approximately 16,000 images across 196 vehicle categories. It is widely used for benchmarking car recognition models.
95
-
96
- ### CompCars
97
-
98
- A large-scale automotive dataset containing over 30,000 images with detailed annotations, including vehicle make, model, and year. It is suitable for both classification and attribute prediction tasks.
99
-
100
- ---
101
-
102
- ## Model Architectures
103
-
104
- ### CNN-Based Models
105
-
106
- #### EfficientNet-B0
107
-
108
- EfficientNet uses compound scaling to balance network depth, width, and resolution. Multiple versions are included to evaluate the impact of training and optimization strategies.
109
-
110
- #### ConvNeXt-Tiny
111
-
112
- A modern CNN architecture inspired by Vision Transformers while retaining the efficiency and simplicity of convolutional networks. Experiments include both fully trainable and partially frozen variants.
113
-
114
- ### Transformer-Based Models
115
-
116
- #### Vision Transformer (ViT-B/16)
117
-
118
- A pure transformer architecture that processes images as sequences of patches for image classification.
119
-
120
- #### Swin Transformer (Swin-T)
121
-
122
- A hierarchical transformer architecture that uses shifted-window attention for efficient feature extraction.
123
-
124
- #### DeiT
125
-
126
- A data-efficient transformer model designed to achieve strong performance with reduced training requirements.
127
-
128
- ---
129
-
130
- ## Installation
131
-
132
- ### Prerequisites
133
-
134
- * Python 3.8+
135
- * CUDA-capable GPU (recommended)
136
- * Jupyter Notebook
137
-
138
- ### Clone the Repository
139
-
140
- ```bash
141
- git clone https://github.com/dragicakostoska/TwinCar.git
142
- cd TwinCar
143
- ```
144
-
145
- ### Install Dependencies
146
-
147
- ```bash
148
- pip install -r requirements.txt
149
  ```
150
 
151
- ---
152
-
153
- ## Dependencies
154
-
155
- Core libraries used throughout the project include:
156
-
157
- * PyTorch and TorchVision
158
- * NumPy and Pandas
159
- * Pillow
160
- * Hugging Face Datasets
161
- * Scikit-learn
162
- * Matplotlib
163
- * tqdm
164
- * Jupyter Notebook and IPython Kernel
165
-
166
- ---
167
-
168
- ## Workflow
169
-
170
- ### 1. Data Exploration
171
-
172
- `01_data_exploration.ipynb`
173
-
174
- * Explore dataset characteristics
175
- * Visualize class distributions
176
- * Inspect image samples and dataset statistics
177
-
178
- ### 2. Data Preparation
179
-
180
- `02_data_preparation.ipynb`
181
-
182
- * Apply preprocessing and augmentation techniques
183
- * Create training, validation, and test splits
184
- * Build dataset loaders and transformations
185
-
186
- ### 3. Model Training
187
-
188
- * Select the desired architecture notebook
189
- * Configure hyperparameters
190
- * Train using transfer learning or fine-tuning
191
- * Monitor performance throughout training
192
-
193
- ### 4. Evaluation
194
-
195
- * Analyze classification metrics
196
- * Generate confusion matrices
197
- * Visualize training and validation curves
198
- * Compare model performance across architectures
199
 
200
- ### 5. Inference
201
 
202
- `05_batch_prediction_demo.ipynb`
203
 
204
- * Load trained models
205
- * Run predictions on image batches
206
- * Visualize outputs and confidence scores
207
 
208
- ---
209
-
210
- ## Training Strategies
211
-
212
- The project investigates two common transfer learning approaches:
213
 
214
- ### Fine-Tuning
 
 
 
215
 
216
- All network layers are trained starting from pretrained weights, allowing the model to adapt fully to the target dataset.
217
 
218
- ### Feature Extraction
219
 
220
- Earlier layers are frozen while only the classification head is trained. This reduces training time and helps preserve pretrained feature representations.
221
 
222
- ---
 
 
 
 
 
 
 
 
 
 
 
223
 
224
- ## Evaluation Metrics
225
 
226
- Each evaluation notebook provides:
227
 
228
- * Top-1 and Top-5 Accuracy
229
- * Precision, Recall, and F1 Score
230
- * Per-class performance analysis
231
- * Confusion matrices
232
- * Training and validation loss curves
233
- * Inference speed comparisons
234
- * Prediction visualizations
235
 
236
- ---
237
 
238
- ## Key Observations
239
 
240
- * EfficientNet-B0 v2 improves upon the baseline v1 configuration.
241
- * ConvNeXt-Tiny achieves strong performance while maintaining computational efficiency.
242
- * Transformer-based architectures provide competitive results and different representational advantages compared to CNNs.
243
- * Transfer learning significantly reduces training requirements while maintaining strong classification accuracy.
 
 
 
 
 
 
 
244
 
245
- ---
246
 
247
- ## Customization
 
 
 
 
248
 
249
- The project can be extended in several ways:
250
 
251
- * Integrate additional automotive datasets
252
- * Add new model architectures
253
- * Experiment with alternative hyperparameters
254
- * Explore multi-task learning objectives
255
- * Implement custom data augmentation pipelines
256
 
257
- ---
258
-
259
- ## Future Work
260
-
261
- * Convert notebook workflows into modular Python packages
262
- * Implement model ensembling techniques
263
- * Add advanced augmentation methods such as MixUp and RandAugment
264
- * Explore knowledge distillation strategies
265
- * Optimize deployment using ONNX or TensorRT
266
- * Develop an inference API
267
- * Create a unified benchmark report across all experiments
268
-
269
- ---
270
 
271
  ## References
272
 
273
- * EfficientNet β€” *Scaling Convolutional Neural Networks Efficiently*
274
- * ConvNeXt β€” *A ConvNet for the 2020s*
275
- * Vision Transformer β€” *An Image is Worth 16Γ—16 Words*
276
- * Swin Transformer β€” *Hierarchical Vision Transformer Using Shifted Windows*
277
- * DeiT β€” *Data-efficient Image Transformers*
278
-
279
- ---
280
-
281
- ## Contributing
282
-
283
- Contributions, suggestions, and bug reports are welcome. Feel free to open an issue or submit a pull request.
284
-
285
- ---
286
 
287
  ## License
288
 
289
- This project is provided for educational and research purposes.
290
-
291
-
292
- ---
293
-
294
- **Last Updated:** June 2026
 
4
  pipeline_tag: image-classification
5
  tags:
6
  - image-classification
 
7
  - convnext
8
  - vehicles
9
  - cars
10
  - stanford-cars
11
  - fine-grained-classification
12
+ - pytorch
13
+ - transfer-learning
14
  datasets:
15
  - naufalso/stanford_cars
16
  metrics:
17
  - accuracy
18
+ - f1
19
+ - precision
20
+ - recall
21
+ model-index:
22
+ - name: twincars_convnext
23
+ results:
24
+ - task:
25
+ type: image-classification
26
+ name: Image Classification
27
+ dataset:
28
+ name: Stanford Cars
29
+ type: naufalso/stanford_cars
30
+ metrics:
31
+ - type: accuracy
32
+ value: 0.8708
33
+ name: Top-1 Accuracy
34
+ - type: accuracy
35
+ value: 0.9681
36
+ name: Top-5 Accuracy
37
+ - type: f1
38
+ value: 0.8705
39
+ name: Weighted F1
40
+ - type: precision
41
+ value: 0.8765
42
+ name: Macro Precision
43
+ - type: recall
44
+ value: 0.8696
45
+ name: Macro Recall
46
+ ---
47
+
48
+ # TwinCar β€” ConvNeXt-Tiny (Stanford Cars)
49
+
50
+ A fine-grained vehicle make/model classifier built on **ConvNeXt-Tiny**, fully fine-tuned on the **Stanford Cars** dataset (195 classes). This is the best-performing model from the [TwinCar](https://github.com/dragicakostoska/TwinCar) project, which compares several CNN and Vision Transformer architectures for automotive classification.
51
+
52
+ Given an image of a car, the model predicts the vehicle's make, model, and year as a single fine-grained class (e.g. `BMW_X5_SUV_2007`).
53
+
54
+ ## Model details
55
+
56
+ | | |
57
+ |---|---|
58
+ | **Architecture** | ConvNeXt-Tiny (`torchvision.models.convnext_tiny`) |
59
+ | **Initialization** | ImageNet-1k pretrained weights (`ConvNeXt_Tiny_Weights.IMAGENET1K_V1`) |
60
+ | **Fine-tuning** | Full network (single-phase, no frozen layers) |
61
+ | **Classes** | 195 fine-grained make/model/year categories |
62
+ | **Input size** | 224 Γ— 224 RGB |
63
+ | **Framework** | PyTorch |
64
+ | **Weights file** | `best_model.pt` (raw `state_dict`, ~112 MB) |
65
+
66
+ The classifier head is the standard ConvNeXt-Tiny head with the final `Linear` layer replaced by a `Linear(in_features, 195)`. Only the final layer is reshaped; LayerNorm and Flatten are kept as in the original head.
67
+
68
+ ## Files in this repository
69
+
70
+ | File | Description |
71
+ |---|---|
72
+ | `best_model.pt` | Model weights, saved as a plain `state_dict` |
73
+ | `idx_to_class.json` | Maps class index β†’ label string (e.g. `42 β†’ "BMW_X5_SUV_2007"`) |
74
+ | `train_config.json` | Training hyperparameters and preprocessing constants |
75
+ | `README.md` | This model card |
76
+
77
+ > **Note on the weights format.** `best_model.pt` is a raw `state_dict` saved with `torch.save(model.state_dict(), ...)`, not a wrapped checkpoint. Load it directly with `model.load_state_dict(...)` as shown below.
78
+
79
+ ## How to use
80
+
81
+ ```python
82
+ import json
83
+ import torch
84
+ import torch.nn as nn
85
+ from PIL import Image
86
+ from torchvision import models, transforms
87
+ from huggingface_hub import hf_hub_download
88
+
89
+ REPO_ID = "cherky15/twincars_convnext"
90
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
91
+
92
+ # 1. Download files from the Hub
93
+ weights_path = hf_hub_download(REPO_ID, "best_model.pt")
94
+ labels_path = hf_hub_download(REPO_ID, "idx_to_class.json")
95
+ config_path = hf_hub_download(REPO_ID, "train_config.json")
96
+
97
+ with open(labels_path) as f:
98
+ idx_to_class = {int(k): v for k, v in json.load(f).items()}
99
+ with open(config_path) as f:
100
+ config = json.load(f)
101
+
102
+ num_classes = len(idx_to_class) # 195
103
+
104
+ # 2. Rebuild the architecture and load the weights
105
+ model = models.convnext_tiny(weights=None)
106
+ in_features = model.classifier[2].in_features
107
+ model.classifier[2] = nn.Linear(in_features, num_classes)
108
+
109
+ state_dict = torch.load(weights_path, map_location=device)
110
+ model.load_state_dict(state_dict)
111
+ model.to(device).eval()
112
+
113
+ # 3. Preprocess (must match validation/test transforms used in training)
114
+ transform = transforms.Compose([
115
+ transforms.Resize(256),
116
+ transforms.CenterCrop(config["img_size"]), # 224
117
+ transforms.ToTensor(),
118
+ transforms.Normalize(mean=config["imagenet_mean"], # ImageNet stats
119
+ std=config["imagenet_std"]),
120
+ ])
121
+
122
+ # 4. Predict
123
+ image = Image.open("car.jpg").convert("RGB")
124
+ x = transform(image).unsqueeze(0).to(device)
125
+
126
+ with torch.no_grad():
127
+ probs = torch.softmax(model(x), dim=1)
128
+ top5_prob, top5_idx = probs.topk(5, dim=1)
129
+
130
+ for prob, idx in zip(top5_prob[0], top5_idx[0]):
131
+ label = idx_to_class[int(idx)].replace("_", " ")
132
+ print(f"{label:40s} {prob.item():.3f}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
133
  ```
134
 
135
+ For batch inference over a folder of images (with make/model/year parsing and CSV export), see `batch_predict.py` in the [TwinCar repository](https://github.com/dragicakostoska/TwinCar).
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
136
 
137
+ ## Intended use
138
 
139
+ **Intended:** fine-grained recognition of car make/model/year on clean, well-framed images similar in distribution to Stanford Cars (single centered vehicle, mostly clear backgrounds), and as a research/educational baseline for comparing architectures on fine-grained classification.
140
 
141
+ **Out of scope:** the model only knows the 195 Stanford Cars categories. It cannot recognize makes/models outside this set, and will still return a confident class for non-car images or unseen vehicles. It is not validated for safety-critical or surveillance use.
 
 
142
 
143
+ ## Training data
 
 
 
 
144
 
145
+ - **Dataset:** [Stanford Cars](https://huggingface.co/datasets/naufalso/stanford_cars) (`naufalso/stanford_cars`)
146
+ - **Classes:** 195 fine-grained make/model/year categories
147
+ - **Test split:** 8,000 images
148
+ - Class imbalance was handled during training with a `WeightedRandomSampler`.
149
 
150
+ ## Training procedure
151
 
152
+ Fine-tuned end-to-end from ImageNet-pretrained weights with mixed-precision (AMP) on a CUDA GPU.
153
 
154
+ ### Hyperparameters
155
 
156
+ | Hyperparameter | Value |
157
+ |---|---|
158
+ | Optimizer | AdamW |
159
+ | Learning rate | 3e-4 |
160
+ | Weight decay | 1e-4 |
161
+ | Loss | CrossEntropy with label smoothing = 0.1 |
162
+ | LR scheduler | ReduceLROnPlateau (mode=min, factor=0.5, patience=2) |
163
+ | Batch size | 32 |
164
+ | Max epochs | 30 |
165
+ | Early stopping | patience = 5 (on validation loss) |
166
+ | Image size | 224 Γ— 224 |
167
+ | Seed | 42 |
168
 
169
+ ### Data augmentation (training)
170
 
171
+ `RandomResizedCrop(224, scale=(0.8, 1.0))`, `RandomHorizontalFlip(p=0.5)`, `RandomRotation(10)`, `ColorJitter(brightness=0.2, contrast=0.2, saturation=0.1, hue=0.02)`, then `ToTensor` and ImageNet normalization. Validation/test images use `Resize(256)` β†’ `CenterCrop(224)` β†’ normalize.
172
 
173
+ The checkpoint corresponds to the epoch with the lowest validation loss.
 
 
 
 
 
 
174
 
175
+ ## Evaluation results
176
 
177
+ Evaluated on the Stanford Cars test split (8,000 images, 195 classes).
178
 
179
+ | Metric | Value |
180
+ |---|---:|
181
+ | Test loss | 0.6942 |
182
+ | **Top-1 accuracy** | **87.08%** |
183
+ | Top-5 accuracy | 96.81% |
184
+ | Macro Precision | 0.8765 |
185
+ | Macro Recall | 0.8696 |
186
+ | Macro F1 | 0.8697 |
187
+ | Weighted F1 | 0.8705 |
188
+ | Make accuracy | 93.03% |
189
+ | Make + Model accuracy | 87.58% |
190
 
191
+ ### Comparison with other TwinCar models
192
 
193
+ | Model | Top-1 | Top-5 | Weighted F1 | Make + Model Acc | Size |
194
+ |---|---:|---:|---:|---:|---:|
195
+ | EfficientNet-B0 v1 | 83.08% | 95.20% | 0.8308 | 83.45% | 17.33 MB |
196
+ | EfficientNet-B0 v2 | 81.64% | 94.50% | 0.8184 | 82.19% | 17.33 MB |
197
+ | **ConvNeXt-Tiny (this model)** | **87.08%** | **96.81%** | **0.8705** | **87.58%** | 111.95 MB |
198
 
199
+ ConvNeXt-Tiny is the strongest model for the core TwinCar goal β€” distinguishing visually similar makes/models (e.g. Audi S4 vs S5, BMW 3 Series vs M3) β€” thanks to a stronger backbone, at the cost of a larger model size. EfficientNet-B0 v1 remains a useful lightweight baseline (~6Γ— smaller) when deployment size matters.
200
 
201
+ ## Limitations and bias
 
 
 
 
202
 
203
+ Results are measured on the Stanford Cars test split. Real-world images β€” e.g. from drones or ground robots, with varied angles, shadows, reflections, occlusion, or cluttered parking-lot backgrounds β€” will likely degrade accuracy. The reported numbers are benchmark performance on a curated dataset, **not** guaranteed production performance. The label space and any demographic/geographic biases are inherited from Stanford Cars (predominantly US-market vehicles up to ~2012).
 
 
 
 
 
 
 
 
 
 
 
 
204
 
205
  ## References
206
 
207
+ - ConvNeXt β€” *A ConvNet for the 2020s* (Liu et al., 2022)
208
+ - Stanford Cars β€” *3D Object Representations for Fine-Grained Categorization* (Krause et al., 2013)
209
+ - Project repository β€” [github.com/dragicakostoska/TwinCar](https://github.com/dragicakostoska/TwinCar)
 
 
 
 
 
 
 
 
 
 
210
 
211
  ## License
212
 
213
+ Released under **CC BY-NC 4.0** for educational and research purposes. Note that use is also subject to the terms of the Stanford Cars dataset and the ImageNet-pretrained base weights.