import torch
import torch.nn as nn
import torch.nn.functional as F
class DahwinFaceNet(nn.Module):
def init(self):
super(DahwinFaceNet, self).init()
self.conv1 = nn.Conv2d(3, 32, kernel_size=3, stride=1, padding=1)
self.bn1 = nn.BatchNorm2d(32)
self.conv2 = nn.Conv2d(32, 32, kernel_size=3, stride=1, padding=1)
self.bn2 = nn.BatchNorm2d(32)
self.conv3 = nn.Conv2d(32, 64, kernel_size=3, stride=1, padding=1)
self.bn3 = nn.BatchNorm2d(64)
self.conv4 = nn.Conv2d(64, 64, kernel_size=3, stride=1, padding=1)
self.bn4 = nn.BatchNorm2d(64)
self.conv5 = nn.Conv2d(64, 64, kernel_size=3, stride=1, padding=1)
self.bn5 = nn.BatchNorm2d(64)
self.conv6 = nn.Conv2d(64, 64, kernel_size=3, stride=1, padding=1)
self.bn6 = nn.BatchNorm2d(64)
self.conv7 = nn.Conv2d(64, 64, kernel_size=3, stride=1, padding=1)
self.bn7 = nn.BatchNorm2d(64)
self.conv8_1 = nn.Conv2d(64, 64, kernel_size=1, stride=1, padding=0)
self.conv8_2 = nn.Conv2d(64, 64, kernel_size=7, stride=1, padding=0)
self.conv9_1 = nn.Conv2d(64, 64, kernel_size=1, stride=1, padding=0)
self.conv9_2 = nn.Conv2d(64, 64, kernel_size=7, stride=1, padding=0)
self.conv10_1 = nn.Conv2d(64, 64, kernel_size=1, stride=1, padding=0)
self.conv10_2 = nn.Conv2d(64, 64, kernel_size=7, stride=1, padding=0)
self.conv11_1 = nn.Conv2d(64, 64, kernel_size=1, stride=1, padding=0)
self.conv11_2 = nn.Conv2d(64, 64, kernel_size=7, stride=1, padding=0)
self.fc = nn.Linear(64 * 14 * 14, 512) # Removed BatchNorm1d layer
self.fc1 = nn.Linear(512, 6)
def forward(self, x):
# Feature extraction
x = F.relu(self.bn1(self.conv1(x)))
x = F.max_pool2d(F.relu(self.bn2(self.conv2(x))), 2)
x = F.relu(self.bn3(self.conv3(x)))
x = F.max_pool2d(F.relu(self.bn4(self.conv4(x))), 2)
x = F.relu(self.bn5(self.conv5(x)))
x = F.max_pool2d(F.relu(self.bn6(self.conv6(x))), 2)
x = F.relu(self.bn7(self.conv7(x)))
x = F.max_pool2d(x, 2)
print(x.shape)
x = x.view(-1, 64 * 7 * 7)
x = self.fc(x) # Removed L2 normalization
return x
Create the model
torch.manual_seed(42)
model = DahwinFaceNet()
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=0.001)
Train model
for epoch in range(10):
model.train()
for inputs, labels in train_loader:
print(f"Input shape: {inputs.shape}, Labels shape: {labels.shape}")
# Your training code here
optimizer.zero_grad()
outputs = model(inputs)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
# Evaluate model
model.eval()
correct = 0
total = 0
with torch.no_grad():
for inputs, labels in test_loader:
outputs = model(inputs)
_, predicted = torch.max(outputs.data, 1)
total += labels.size(0)
correct += (predicted == labels).sum().item()
accuracy = 100 * correct / total
print('Epoch: {}, Test Accuracy: {}%'.format(epoch, accuracy))
Save model
torch.save(model.state_dict(), ‘model.pth’)