Skip to content

Instantly share code, notes, and snippets.

@MartinWeiss12
Last active October 23, 2024 17:37
Show Gist options
  • Save MartinWeiss12/f8e5d672bd0629789c19082d2be65a36 to your computer and use it in GitHub Desktop.
Save MartinWeiss12/f8e5d672bd0629789c19082d2be65a36 to your computer and use it in GitHub Desktop.
CNN
class CNN(nn.Module):
def __init__(self, num_classes):
super(CNN, self).__init__()
self.CONV1 = 64
self.CONV2 = 128
self.CONV3 = 256
self.CONV4 = 512
self.FC1 = 64
self.conv_layers = nn.Sequential(
nn.Conv2d(3, self.CONV1, kernel_size=3, padding=1),
nn.BatchNorm2d(self.CONV1),
nn.LeakyReLU(0.1),
nn.MaxPool2d(2, 2),
nn.Conv2d(self.CONV1, self.CONV2, kernel_size=3, padding=1),
nn.BatchNorm2d(self.CONV2),
nn.LeakyReLU(0.1),
nn.MaxPool2d(2, 2),
nn.Conv2d(self.CONV2, self.CONV3, kernel_size=3, padding=1),
nn.BatchNorm2d(self.CONV3),
nn.LeakyReLU(0.1),
nn.MaxPool2d(2, 2),
nn.Conv2d(self.CONV3, self.CONV4, kernel_size=3, padding=1),
nn.BatchNorm2d(self.CONV4),
nn.LeakyReLU(0.1),
nn.MaxPool2d(2, 2),
)
self.gap = nn.AdaptiveAvgPool2d(1)
self.fc1 = nn.Linear(self.CONV4, self.FC1)
self.dropout1 = nn.Dropout(p=0.2)
self.fc2 = nn.Linear(self.FC1, num_classes)
self.dropout2 = nn.Dropout(p=0.1)
def forward(self, x):
x = self.conv_layers(x)
x = self.gap(x)
x = x.view(x.size(0), -1)
x = F.leaky_relu(self.fc1(x), 0.1)
x = self.dropout1(x)
x = self.fc2(x)
x = self.dropout2(x)
return x
def predict(self, x):
logits = self.forward(x)
return F.softmax(logits, dim=1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment