|
| 1 | +import torch |
| 2 | +import torch.nn as nn |
| 3 | + |
| 4 | + |
| 5 | +class SolveigModel(nn.Module): |
| 6 | + """ |
| 7 | + A Convolutional Neural Network model for classification. |
| 8 | +
|
| 9 | + Args |
| 10 | + ---- |
| 11 | + image_shape : tuple(int, int, int) |
| 12 | + Shape of the input image (C, H, W). |
| 13 | + num_classes : int |
| 14 | + Number of classes in the dataset. |
| 15 | +
|
| 16 | + Attributes: |
| 17 | + ----------- |
| 18 | + conv_block1 : nn.Sequential |
| 19 | + First convolutional block containing a convolutional layer, ReLU activation, and max-pooling. |
| 20 | + conv_block2 : nn.Sequential |
| 21 | + Second convolutional block containing a convolutional layer and ReLU activation. |
| 22 | + conv_block3 : nn.Sequential |
| 23 | + Third convolutional block containing a convolutional layer and ReLU activation. |
| 24 | + fc1 : nn.Linear |
| 25 | + Fully connected layer that outputs the final classification scores. |
| 26 | + """ |
| 27 | + |
| 28 | + def __init__(self, image_shape, num_classes): |
| 29 | + super().__init__() |
| 30 | + |
| 31 | + C, *_ = image_shape |
| 32 | + |
| 33 | + # Define the first convolutional block (conv + relu + maxpool) |
| 34 | + self.conv_block1 = nn.Sequential( |
| 35 | + nn.Conv2d(in_channels=C, out_channels=25, kernel_size=3, padding=1), |
| 36 | + nn.ReLU(), |
| 37 | + nn.MaxPool2d(kernel_size=2, stride=2) |
| 38 | + ) |
| 39 | + |
| 40 | + # Define the second convolutional block (conv + relu) |
| 41 | + self.conv_block2 = nn.Sequential( |
| 42 | + nn.Conv2d(in_channels=25, out_channels=50, kernel_size=3, padding=1), |
| 43 | + nn.ReLU() |
| 44 | + ) |
| 45 | + |
| 46 | + # Define the third convolutional block (conv + relu) |
| 47 | + self.conv_block3 = nn.Sequential( |
| 48 | + nn.Conv2d(in_channels=50, out_channels=100, kernel_size=3, padding=1), |
| 49 | + nn.ReLU() |
| 50 | + ) |
| 51 | + |
| 52 | + self.fc1 = nn.Linear(100 * 8 * 8, num_classes) |
| 53 | + |
| 54 | + def forward(self, x): |
| 55 | + x = self.conv_block1(x) |
| 56 | + x = self.conv_block2(x) |
| 57 | + x = self.conv_block3(x) |
| 58 | + x = torch.flatten(x, 1) |
| 59 | + |
| 60 | + x = self.fc1(x) |
| 61 | + x = nn.Softmax(x) |
| 62 | + |
| 63 | + return x |
| 64 | + |
| 65 | + |
| 66 | +if __name__ == "__main__": |
| 67 | + |
| 68 | + x = torch.randn(1,3, 16, 16) |
| 69 | + |
| 70 | + model = SolveigModel(x.shape[1:], 3) |
| 71 | + |
| 72 | + y = model(x) |
| 73 | + |
| 74 | + print(y) |
0 commit comments