-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmodel.py
More file actions
96 lines (76 loc) · 2.99 KB
/
model.py
File metadata and controls
96 lines (76 loc) · 2.99 KB
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
import torch.nn as nn
import torch
class ResidualBlock(nn.Module):
def __init__(self, in_channels, out_channels, stride=1):
super().__init__()
self.conv1 = nn.Conv2d(in_channels, out_channels,
3, stride, padding=1, bias=False)
self.bn1 = nn.BatchNorm2d(out_channels)
self.conv2 = nn.Conv2d(out_channels, out_channels,
3, 1, padding=1, bias=False)
self.bn2 = nn.BatchNorm2d(out_channels)
self.shortcut = nn.Sequential()
self.use_shortcut = stride!=1 or in_channels != out_channels
if self.use_shortcut:
self.shortcut = nn.Sequential(
nn.Conv2d(in_channels, out_channels, 1, stride=stride, bias=False),
nn.BatchNorm2d(out_channels)
)
def forward(self, x):
out = self.conv1(x)
out = self.bn1(out)
out = torch.relu(out)
out = self.conv2(out)
out = self.bn2(out)
shortcut = self.shortcut(x) if self.use_shortcut else x
out_add = out + shortcut
out = torch.relu(out_add)
return out
class AudioCNN(nn.Module):
def __init__(self, num_classes=50):
super(
).__init__()
self.conv1 = nn.Sequential(
nn.Conv2d(1, 64 , 7, stride=2, padding=3, bias=False),
nn.BatchNorm2d(64),
nn.ReLU(inplace=True),
nn.MaxPool2d(3, stride=2, padding =1)
)
self.layer1 = nn.ModuleList([
ResidualBlock(64, 64) for i in range(3)
])
self.layer2 = nn.ModuleList([
ResidualBlock(64 if i == 0 else 128, 128, stride=2 if i ==0 else 1) for i in range(4)
])
self.layer3 = nn.ModuleList([
ResidualBlock(128 if i == 0 else 256, 256, stride=2 if i ==0 else 1) for i in range(6)
])
self.layer4 = nn.ModuleList([
ResidualBlock(256 if i == 0 else 512, 512, stride=2 if i ==0 else 1) for i in range(3)
])
self.avgpool = nn.AdaptiveAvgPool2d((1, 1))
self.dropout= nn.Dropout(0.5)
self.fc = nn.Linear(512, num_classes)
def forward(self, x, return_feature_maps=False):
feature_maps = {}
x = self.conv1(x)
feature_maps['conv1'] = x
for i, block in enumerate(self.layer1):
x = block(x)
feature_maps[f'layer1.{i}'] = x
for i, block in enumerate(self.layer2):
x = block(x)
feature_maps[f'layer2.{i}'] = x
for i, block in enumerate(self.layer3):
x = block(x)
feature_maps[f'layer3.{i}'] = x
for i, block in enumerate(self.layer4):
x = block(x)
feature_maps[f'layer4.{i}'] = x
x = self.avgpool(x)
x = x.view(x.size(0), -1)
x = self.dropout(x)
x = self.fc(x)
if return_feature_maps:
return x, feature_maps
return x