-
Notifications
You must be signed in to change notification settings - Fork 1
/
transflearn_models.py
197 lines (143 loc) · 6.09 KB
/
transflearn_models.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
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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
import os
import sys
import torch
torch.backends.cudnn.benchmark=True
torch.manual_seed(0)
import torch.nn as nn
import torch.nn.functional as F
sys.path.append('audio_tagging_functions')
from models import *
DEVICE = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu')
### Load model function and Models class ###
def load_model(model_type, sample_rate, nb_species, model_path, after_train=False):
"""
Loads and returns the choosen model.
Use after_train=True for loading the model after the training (see plot_stats.pynb)
"""
# Initialize Model
Model = eval(model_type)
model = Model(sample_rate=sample_rate, window_size=1024, hop_size=320, mel_bins=64, fmin=50, fmax=32000,
classes_num=nb_species, freeze_base=True)
if after_train:
model.load_state_dict(torch.load(model_path))
else:
# Load pretrained model
print(model)
model.load_from_pretrain(model_path)
# Parallel
print('GPU number: {}'.format(torch.cuda.device_count()))
model = torch.nn.DataParallel(model)
if DEVICE == 'cuda':
model.to(DEVICE)
print('Load pretrained model successfully!')
return model
class Transfer_Cnn6(nn.Module):
def __init__(self, sample_rate, window_size, hop_size, mel_bins, fmin,
fmax, classes_num, freeze_base):
"""
Classifier for bird species using pretrained Cnn6 as a sub module.
"""
super(Transfer_Cnn6, self).__init__()
audioset_classes_num = 527
self.base = Cnn6(sample_rate, window_size, hop_size, mel_bins, fmin,
fmax, audioset_classes_num)
# Transfer to another task layer
self.fc_transfer1 = nn.Linear(512, 256, bias=True)
self.fc_transfer2 = nn.Linear(256, classes_num, bias=True)
if freeze_base:
# Freeze AudioSet pretrained layers
for param in self.base.parameters():
param.requires_grad = False
self.init_weights()
def init_weights(self):
init_layer(self.fc_transfer1)
init_layer(self.fc_transfer2)
def load_from_pretrain(self, pretrained_checkpoint_path):
checkpoint = torch.load(pretrained_checkpoint_path, map_location=torch.device(DEVICE))
self.base.load_state_dict(checkpoint['model'])
def forward(self, input, mixup_lambda=None):
"""
Input: (batch_size, data_length)
"""
output_dict = self.base(input, mixup_lambda)
embedding = output_dict['embedding']
x = F.relu(self.fc_transfer1(embedding))
clipwise_output = self.fc_transfer2(x)
output_dict['clipwise_output'] = clipwise_output
return output_dict
class Transfer_Cnn14(nn.Module):
def __init__(self, sample_rate, window_size, hop_size, mel_bins, fmin,
fmax, classes_num, freeze_base):
"""Classifier for a new task using pretrained Cnn14 as a sub module.
"""
super(Transfer_Cnn14, self).__init__()
audioset_classes_num = 527
self.base = Cnn14(sample_rate, window_size, hop_size, mel_bins, fmin,
fmax, audioset_classes_num)
# Transfer to another task layer
self.fc_transfer1 = nn.Linear(2048, 256, bias=True)
self.fc_transfer2 = nn.Linear(256, classes_num, bias=True)
if freeze_base:
# Freeze AudioSet pretrained layers
for param in self.base.parameters():
param.requires_grad = False
self.init_weights()
def init_weights(self):
init_layer(self.fc_transfer1)
init_layer(self.fc_transfer2)
def load_from_pretrain(self, pretrained_checkpoint_path):
checkpoint = torch.load(pretrained_checkpoint_path, map_location=torch.device(DEVICE))
self.base.load_state_dict(checkpoint['model'])
def forward(self, input, mixup_lambda=None):
"""Input: (batch_size, data_length)
"""
output_dict = self.base(input, mixup_lambda)
embedding = output_dict['embedding']
x = F.relu(self.fc_transfer1(embedding))
clipwise_output = self.fc_transfer2(x)
output_dict['clipwise_output'] = clipwise_output
return output_dict
class Transfer_ResNet22(nn.Module):
def __init__(self, sample_rate, window_size, hop_size, mel_bins, fmin,
fmax, classes_num, freeze_base):
"""Classifier for a new task using pretrained Cnn14 as a sub module.
"""
super(Transfer_ResNet22, self).__init__()
audioset_classes_num = 527
self.base = ResNet22(sample_rate, window_size, hop_size, mel_bins, fmin,
fmax, audioset_classes_num)
# Transfer to another task layer
self.fc_transfer1 = nn.Linear(2048, 256, bias=True)
self.fc_transfer2 = nn.Linear(256, classes_num, bias=True)
if freeze_base:
# Freeze AudioSet pretrained layers
for param in self.base.parameters():
param.requires_grad = False
self.init_weights()
def init_weights(self):
init_layer(self.fc_transfer1)
init_layer(self.fc_transfer2)
def load_from_pretrain(self, pretrained_checkpoint_path):
checkpoint = torch.load(pretrained_checkpoint_path, map_location=torch.device(DEVICE))
self.base.load_state_dict(checkpoint['model'])
def forward(self, input, mixup_lambda=None):
"""Input: (batch_size, data_length)
"""
with torch.no_grad():
output_dict = self.base(input, mixup_lambda)
embedding = output_dict['embedding']
x = F.relu(self.fc_transfer1(embedding))
clipwise_output = self.fc_transfer2(x)
output_dict['clipwise_output'] = clipwise_output
return output_dict
if __name__ == "__main__":
### Main parameters ###
# Path
MODEL_PATH = "pretrained_models/Cnn6_mAP=0.343.pth"
# Audio parameters
SR = 32000 # Sample Rate
# Model parameters
MODEL_TYPE = "Transfer_Cnn6"
NB_SPECIES = 13 # Number of classes
### Load Model ###
model = load_model(model_type=MODEL_TYPE, sample_rate=SR, nb_species=NB_SPECIES, model_path=MODEL_PATH)