-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathgender_cnn.py
59 lines (47 loc) · 2.16 KB
/
gender_cnn.py
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
import torch.nn as nn
import torch.nn.functional as F
# Defines CNN topology
class GenderCnn(nn.Module):
def __init__(self):
super(GenderCnn, self).__init__()
self.predict = True
# Input channels = 3 (32 * 32), output channels = 18 (32 * 32)
self.conv1 = nn.Conv2d(3, 18, kernel_size=3, stride=1, padding=1)
# Input channels = 18 (32 * 32), output channels = 18 (16 * 16)
self.pool1 = nn.MaxPool2d(kernel_size=2, stride=2, padding=0)
# Input channels = 18 (16 * 16), output channels = 26 (16 * 16)
self.conv2 = nn.Conv2d(18, 18, kernel_size=3, stride=1, padding=1)
# Input channels = 26 (16 * 16), output channels = 26 (8 * 8)
self.pool2 = nn.MaxPool2d(kernel_size=2, stride=2, padding=0)
# Input channels = 18 (8 * 8), output channels = 18 (8 * 8)
self.conv3 = nn.Conv2d(18, 18, kernel_size=3, stride=1, padding=1)
# Input channels = 18 (8 * 8), output channels = 18 (8 * 8)
self.conv4 = nn.Conv2d(18, 18, kernel_size=3, stride=1, padding=1)
# 1152 (26 * 8 * 8) input features, 64 output features (see sizing flow below).
self.fc1 = nn.Linear(18 * 8 * 8, 64)
# Dropout layer(s): drops with probability 0.4
self.dropout = nn.Dropout(p=0.4)
# 64 input features, 10 output features for our 10 defined classes
self.fc2 = nn.Linear(64, 2)
def forward(self, x):
# conv1: from (3, 32, 32) to (18, 32, 32)
x = F.relu(self.conv1(x))
# pool1: from (18, 32, 32) to (18, 16, 16)
x = self.pool1(x)
# conv2: from (18, 16, 16) to (18, 16, 16)
x = F.relu(self.conv2(x))
# pool2: from (18, 16, 16) to (18, 8, 8)
x = self.pool2(x)
# conv3: from (18, 8, 8) to (18, 8, 8)
x = F.relu(self.conv3(x))
# conv4: from (18, 8, 8) to (18, 8, 8)
x = F.relu(self.conv4(x))
# re-shape: from pool2 to fc1
x = x.view(-1, 18 * 8 * 8)
# fc1: from 1152 (18 * 8 * 8) to 64
x = F.relu(self.fc1(x))
# dropout: p = 0.5
if not self.predict:
x = self.dropout(x)
# fc2: from 64 to 2
return self.fc2(x)