File size: 1,886 Bytes
9eabb80
2f0c04b
9eabb80
 
 
2f0c04b
9eabb80
2f0c04b
9eabb80
2f0c04b
9eabb80
2f0c04b
 
9eabb80
2f0c04b
 
 
9eabb80
2f0c04b
 
 
9eabb80
2f0c04b
 
 
9eabb80
2f0c04b
 
9eabb80
2f0c04b
 
 
 
 
9eabb80
2f0c04b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9eabb80
 
2f0c04b
9eabb80
 
 
 
 
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
"""

CNN Model Architecture for CIFAR-10 Classification

"""
import torch
import torch.nn as nn
import torch.nn.functional as F

class CIFAR10CNN(nn.Module):
    """

    Convolutional Neural Network for CIFAR-10 classification

    """
    def __init__(self, num_classes=10):
        super(CIFAR10CNN, self).__init__()
        
        # Convolutional Layer 1
        self.conv1 = nn.Conv2d(3, 32, kernel_size=3, padding=1)
        self.bn1 = nn.BatchNorm2d(32)
        
        # Convolutional Layer 2
        self.conv2 = nn.Conv2d(32, 64, kernel_size=3, padding=1)
        self.bn2 = nn.BatchNorm2d(64)
        
        # Convolutional Layer 3
        self.conv3 = nn.Conv2d(64, 128, kernel_size=3, padding=1)
        self.bn3 = nn.BatchNorm2d(128)
        
        # Max Pooling
        self.pool = nn.MaxPool2d(2, 2)
        
        # Fully Connected Layers
        # After three 2x2 pools, 32x32 image becomes 4x4
        self.fc1 = nn.Linear(128 * 4 * 4, 512)
        self.dropout = nn.Dropout(0.5)
        self.fc2 = nn.Linear(512, num_classes)

    def forward(self, x):
        # Layer 1: Conv -> BN -> ReLU -> Pool
        x = self.pool(F.relu(self.bn1(self.conv1(x))))
        # Layer 2: Conv -> BN -> ReLU -> Pool
        x = self.pool(F.relu(self.bn2(self.conv2(x))))
        # Layer 3: Conv -> BN -> ReLU -> Pool
        x = self.pool(F.relu(self.bn3(self.conv3(x))))
        
        # Flatten
        x = x.view(-1, 128 * 4 * 4)
        
        # FC Layers
        x = F.relu(self.fc1(x))
        x = self.dropout(x)
        x = self.fc2(x)
        
        return x

def get_model(num_classes=10, device='cpu'):
    model = CIFAR10CNN(num_classes=num_classes)
    model = model.to(device)
    return model

def count_parameters(model):
    return sum(p.numel() for p in model.parameters() if p.requires_grad)