File size: 11,660 Bytes
db337f7
 
47848da
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6052e2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
---
license: apache-2.0
datasets:
- uoft-cs/cifar100
language:
- en
metrics:
- accuracy
base_model:
- adityachaubey/vision_transform
pipeline_tag: image-classification
library_name: transformers
tags:
- vits
- transformer
- Pytorch
- self_attention
---

# Vision Transformer (ViT) - CIFAR-10 Image Classification

A custom Vision Transformer (ViT) implemented in PyTorch and trained on the CIFAR-10 dataset for image classification.

This project explores Transformer-based architectures for computer vision, implementing the Vision Transformer approach and training it using mixed-precision training for improved computational efficiency.

The model was trained for 20 epochs on CIFAR-10 using PyTorch.

## Model Details

### Model Description

This model is a custom implementation of a Vision Transformer (ViT) designed for image classification.

Unlike traditional Convolutional Neural Networks (CNNs), which process images using convolutional operations, Vision Transformers divide an image into smaller patches, project them into embeddings, and process these embeddings using Transformer encoder blocks.

The model uses self-attention mechanisms to learn relationships between different image patches and generate representations useful for image classification.

The model was trained on CIFAR-10, a widely used benchmark dataset containing 60,000 color images across 10 different object categories.

**Key Highlights:**

- Custom Vision Transformer architecture implemented in PyTorch.
- Trained on the CIFAR-10 dataset.
- Patch-based image representation.
- Transformer encoder blocks with self-attention.
- Mixed-precision training using automatic mixed precision (AMP).
- 20 training epochs.
- GPU-accelerated training.

### Model Information

- **Developed by:** Aditya Chaubey 
- **Model type:** Vision Transformer (ViT)
- **Task:** Image Classification
- **Framework:** PyTorch
- **Dataset:** CIFAR-10
- **Training epochs:** 20
- **Batch size:** 64
- **Training precision:** Mixed Precision (AMP)
- **License:** MIT
- **Language(s):** Not applicable

### Model Sources

- **GitHub Repository:** [Github](https://github.com/adityachaubeycode/Vision-Transformer-Model)
- **Dataset:** [CIFAR-10 - Official Dataset](https://www.cs.toronto.edu/~kriz/cifar.html)

---

## Uses

### Direct Use

The model can be used directly for classifying images into one of the ten CIFAR-10 categories.

The supported classes are:

1. Airplane
2. Automobile
3. Bird
4. Cat
5. Deer
6. Dog
7. Frog
8. Horse
9. Ship
10. Truck

Users can load the trained model weights and perform inference on compatible input images.

### Downstream Use

The model can serve as a starting point for:

- Experimenting with Vision Transformer architectures.
- Learning Transformer-based computer vision.
- Comparing CNNs and Vision Transformers.
- Fine-tuning on similar image classification datasets.
- Exploring attention mechanisms in computer vision.
- Educational and research experiments.

### Out-of-Scope Use

This model is not intended for:

- General-purpose image classification.
- Medical image diagnosis.
- Real-world object detection.
- Image segmentation.
- Safety-critical applications.
- Classification of images outside the CIFAR-10 categories without additional training or evaluation.

---

## Bias, Risks, and Limitations

Although CIFAR-10 is a commonly used benchmark dataset, the model has several limitations.

- **Dataset limitations:** The model was trained specifically on CIFAR-10 and may not generalize well to unrelated datasets.
- **Image resolution:** CIFAR-10 contains low-resolution 32 × 32 images. Performance on high-resolution images is not established.
- **Domain generalization:** The model may perform poorly on images with different visual characteristics from the training dataset.
- **Training limitations:** The model was trained for 20 epochs, and additional training or hyperparameter optimization may improve performance.
- **Evaluation limitations:** Performance should be assessed using independent test data and appropriate classification metrics.

### Recommendations

Users should:

- Apply the same preprocessing used during training.
- Evaluate the model on independent test data.
- Avoid assuming that performance on CIFAR-10 translates to real-world applications.
- Consider fine-tuning before applying the model to another dataset.
- Review the model's evaluation metrics before using it in downstream applications.

---

## How to Get Started with the Model

### Requirements

Install the required dependencies:

```bash
pip install torch torchvision numpy matplotlib tqdm
```

### Loading the Model

The model architecture must be defined before loading the trained weights.

```python
import torch

# Import your custom Vision Transformer architecture
from model import VisionTransformer

device = torch.device(
    "cuda" if torch.cuda.is_available() else "cpu"
)

# Initialize the model with the same configuration
model = VisionTransformer(
    # Add your architecture parameters here
)

# Load trained weights
checkpoint = torch.load(
    "model.pth",
    map_location=device,
    weights_only=True
)

model.load_state_dict(checkpoint)

model.to(device)
model.eval()

print("Model loaded successfully!")
```

### Image Classification

```python
import torch
from PIL import Image
from torchvision import transforms

classes = [
    "airplane", "automobile", "bird", "cat", "deer",
    "dog", "frog", "horse", "ship", "truck"
]

transform = transforms.Compose([
    transforms.Resize((32, 32)),
    transforms.ToTensor(),
    transforms.Normalize(
        (0.4914, 0.4822, 0.4465),
        (0.2470, 0.2435, 0.2616)
    )
])

image = Image.open("image.jpg").convert("RGB")
image = transform(image).unsqueeze(0).to(device)

with torch.no_grad():
    outputs = model(image)
    prediction = outputs.argmax(dim=1).item()

print("Predicted class:", classes[prediction])
```

**Note:** The example assumes a standard CIFAR-10 normalization scheme and a model that accepts 32 × 32 images and returns ten class logits. Adjust the architecture initialization, checkpoint loading, and preprocessing to match your actual implementation.

---

## Training Details

### Training Data

The model was trained using the CIFAR-10 dataset.

CIFAR-10 consists of:

- 60,000 RGB images.
- 50,000 training images.
- 10,000 test images.
- 10 object categories.
- Image resolution: 32 × 32 pixels.
- Three color channels (RGB).

**Dataset Source:** https://www.cs.toronto.edu/~kriz/cifar.html

### Training Procedure

The Vision Transformer was implemented and trained using PyTorch.

Training was performed for 20 epochs with a batch size of 64.

Mixed-precision training was enabled to improve computational efficiency and reduce memory consumption during training.

#### Preprocessing

The CIFAR-10 dataset was loaded using Torchvision.

Preprocessing included:

- Image conversion to tensors.
- Image normalization.
- Resizing or other transformations, if applicable, according to the model configuration.

#### Training Configuration

| Parameter | Value |
|---|---|
| Framework | PyTorch |
| Dataset | CIFAR-10 |
| Epochs | 20 |
| Batch Size | 64 |
| Precision | Mixed Precision (AMP) |
| Task | Image Classification |
| Optimizer | Adam] |
| Loss Function | Cross Entropy Loss |
| Learning Rate | 1e-4 |
| Scheduler | [None] |
| Hardware | [Tesla T4] |

### Model Architecture

The model follows the Vision Transformer architecture.

Its main components include:

- Patch Embedding
- Positional Embedding
- Transformer Encoder Blocks
- Multi-Head Self-Attention
- Feed-Forward Networks (MLP)
- Classification Head

**Model Architecture Summary (Torchinfo):**

Complete `torchinfo.summary()` output here.

```text
[=====================================================================================
Layer (type:depth-idx)                                       Param #
=====================================================================================
vit                                                          --
├─Patch_Embedding: 1-1                                       16,896
│    └─Conv2d: 2-1                                           12,544
├─Sequential: 1-2                                            --
│    └─TransformerEncoderLayer: 2-2                          --
│    │    └─LayerNorm: 3-1                                   512
│    │    └─MultiheadAttention: 3-2                          263,168
│    │    └─LayerNorm: 3-3                                   512
│    │    └─MLP: 3-4                                         262,912
│    └─TransformerEncoderLayer: 2-3                          --
│    │    └─LayerNorm: 3-5                                   512
│    │    └─MultiheadAttention: 3-6                          263,168
│    │    └─LayerNorm: 3-7                                   512
│    │    └─MLP: 3-8                                         262,912
│    └─TransformerEncoderLayer: 2-4                          --
│    │    └─LayerNorm: 3-9                                   512
│    │    └─MultiheadAttention: 3-10                         263,168
│    │    └─LayerNorm: 3-11                                  512
│    │    └─MLP: 3-12                                        262,912
│    └─TransformerEncoderLayer: 2-5                          --
│    │    └─LayerNorm: 3-13                                  512
│    │    └─MultiheadAttention: 3-14                         263,168
│    │    └─LayerNorm: 3-15                                  512
│    │    └─MLP: 3-16                                        262,912
│    └─TransformerEncoderLayer: 2-6                          --
│    │    └─LayerNorm: 3-17                                  512
│    │    └─MultiheadAttention: 3-18                         263,168
│    │    └─LayerNorm: 3-19                                  512
│    │    └─MLP: 3-20                                        262,912
│    └─TransformerEncoderLayer: 2-7                          --
│    │    └─LayerNorm: 3-21                                  512
│    │    └─MultiheadAttention: 3-22                         263,168
│    │    └─LayerNorm: 3-23                                  512
│    │    └─MLP: 3-24                                        262,912
├─LayerNorm: 1-3                                             512
├─Linear: 1-4                                                2,570
=====================================================================================
Total params: 3,195,146
Trainable params: 3,195,146
Non-trainable params: 0
=====================================================================================]
```

### Evaluation

| Metric | Result |
|---|---|
| Test Accuracy | 69% |
| Test Loss |0.98 |
| Training Epochs | 20 |

Evaluation metrics should be updated with the actual results from your training and testing process.

---

## Hardware and Software

### Software

- Python
- PyTorch
- Torchvision
- NumPy
- Matplotlib
- tqdm

### Hardware

- GPU: [Tesla T4 cuda]

---

## License

This model is released under the MIT License.

You are free to use, modify, and distribute this project in accordance with the terms of the license.

---

## Acknowledgements

- Hugging Face for providing the model hosting platform.
- PyTorch for the deep learning framework.
- The CIFAR-10 dataset creators for providing the benchmark dataset.

**Built with PyTorch | Computer Vision | Vision Transformers**