fkl100/Behavior_and_Emotion_Recognition
0
1# File: models.py (continued)
2
3import torch
4import torch.nn as nn
5import torch.nn.functional as F
6import math
7
8class Bottleneck(nn.Module):
9 expansion = 4
10
11 def __init__(self, in_channels, out_channels, i_downsample=None, stride=1):
12 super(Bottleneck, self).__init__()
13 self.conv1 = nn.Conv2d(in_channels, out_channels, kernel_size=1, stride=stride, padding=0, bias=False)
14 self.batch_norm1 = nn.BatchNorm2d(out_channels, eps=0.001, momentum=0.99)
15 self.conv2 = nn.Conv2d(out_channels, out_channels, kernel_size=3, padding='same', bias=False)
16 self.batch_norm2 = nn.BatchNorm2d(out_channels, eps=0.001, momentum=0.99)
17 self.conv3 = nn.Conv2d(out_channels, out_channels * self.expansion, kernel_size=1, stride=1, padding=0, bias=False)
18 self.batch_norm3 = nn.BatchNorm2d(out_channels * self.expansion, eps=0.001, momentum=0.99)
19 self.i_downsample = i_downsample
20 self.stride = stride
21 self.relu = nn.ReLU()
22
23 def forward(self, x):
24 identity = x.clone()
25 x = self.relu(self.batch_norm1(self.conv1(x)))
26 x = self.relu(self.batch_norm2(self.conv2(x)))
27 x = self.conv3(x)
28 x = self.batch_norm3(x)
29
30 if self.i_downsample is not None:
31 identity = self.i_downsample(identity)
32 x += identity
33 x = self.relu(x)
34 return x
35
36class Conv2dSame(torch.nn.Conv2d):
37 def calc_same_pad(self, i: int, k: int, s: int, d: int) -> int:
38 return max((math.ceil(i / s) - 1) * s + (k - 1) * d + 1 - i, 0)
39
40 def forward(self, x: torch.Tensor) -> torch.Tensor:
41 ih, iw = x.size()[-2:]
42
43 pad_h = self.calc_same_pad(i=ih, k=self.kernel_size[0], s=self.stride[0], d=self.dilation[0])
44 pad_w = self.calc_same_pad(i=iw, k=self.kernel_size[1], s=self.stride[1], d=self.dilation[1])
45
46 if pad_h > 0 or pad_w > 0:
47 x = F.pad(x, [pad_w // 2, pad_w - pad_w // 2, pad_h // 2, pad_h - pad_h // 2])
48 return F.conv2d(x, self.weight, self.bias, self.stride, self.padding, self.dilation, self.groups)
49
50class ResNet(nn.Module):
51 def __init__(self, ResBlock, layer_list, num_classes, num_channels=3):
52 super(ResNet, self).__init__()
53 self.in_channels = 64
54
55 self.conv_layer_s2_same = Conv2dSame(num_channels, 64, 7, stride=2, groups=1, bias=False)
56 self.batch_norm1 = nn.BatchNorm2d(64, eps=0.001, momentum=0.99)
57 self.relu = nn.ReLU()
58 self.max_pool = nn.MaxPool2d(kernel_size=3, stride=2)
59
60 self.layer1 = self._make_layer(ResBlock, layer_list[0], planes=64, stride=1)
61 self.layer2 = self._make_layer(ResBlock, layer_list[1], planes=128, stride=2)
62 self.layer3 = self._make_layer(ResBlock, layer_list[2], planes=256, stride=2)
63 self.layer4 = self._make_layer(ResBlock, layer_list[3], planes=512, stride=2)
64
65 self.avgpool = nn.AdaptiveAvgPool2d((1, 1))
66 self.fc1 = nn.Linear(512 * ResBlock.expansion, 512)
67 self.relu1 = nn.ReLU()
68 self.fc2 = nn.Linear(512, num_classes)
69
70 def extract_features(self, x):
71 x = self.relu(self.batch_norm1(self.conv_layer_s2_same(x)))
72 x = self.max_pool(x)
73 x = self.layer1(x)
74 x = self.layer2(x)
75 x = self.layer3(x)
76 x = self.layer4(x)
77 x = self.avgpool(x)
78 x = x.reshape(x.shape[0], -1)
79 x = self.fc1(x)
80 return x
81
82 def forward(self, x):
83 x = self.extract_features(x)
84 x = self.relu1(x)
85 x = self.fc2(x)
86 return x
87
88 def _make_layer(self, ResBlock, blocks, planes, stride=1):
89 ii_downsample = None
90 layers = []
91
92 if stride != 1 or self.in_channels != planes * ResBlock.expansion:
93 ii_downsample = nn.Sequential(
94 nn.Conv2d(self.in_channels, planes * ResBlock.expansion, kernel_size=1, stride=stride, bias=False, padding=0),
95 nn.BatchNorm2d(planes * ResBlock.expansion, eps=0.001, momentum=0.99)
96 )
97
98 layers.append(ResBlock(self.in_channels, planes, i_downsample=ii_downsample, stride=stride))
99 self.in_channels = planes * ResBlock.expansion
100
101 for i in range(blocks - 1):
102 layers.append(ResBlock(self.in_channels, planes))
103
104 return nn.Sequential(*layers)
105
106def ResNet50(num_classes, channels=3):
107 return ResNet(Bottleneck, [3, 4, 6, 3], num_classes, channels)
108
109class LSTMPyTorch(nn.Module):
110 def __init__(self):
111 super(LSTMPyTorch, self).__init__()
112 self.lstm1 = nn.LSTM(input_size=512, hidden_size=512, batch_first=True, bidirectional=False)
113 self.lstm2 = nn.LSTM(input_size=512, hidden_size=256, batch_first=True, bidirectional=False)
114 self.fc = nn.Linear(256, 7)
115 self.softmax = nn.Softmax(dim=1)
116
117 def forward(self, x):
118 x, _ = self.lstm1(x)
119 x, _ = self.lstm2(x)
120 x = self.fc(x[:, -1, :])
121 x = self.softmax(x)
122 return x