baseline.py 5.54 KB
Newer Older
Verena Praher's avatar
Verena Praher committed
1
import torch.nn as nn
2
from datasets.mtgjamendo import df_get_mtg_set
Verena Praher's avatar
Verena Praher committed
3
4

from utils import *
5
from datasets.dataset import HDF5Dataset
Verena Praher's avatar
Verena Praher committed
6
7
8
9
10
11
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import DataLoader
import pytorch_lightning as pl

12
from sklearn import metrics
Verena Praher's avatar
Verena Praher committed
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

# TODO pr-auc
# TODO f1-score

class CNN(pl.LightningModule):
    def __init__(self, num_class):
        super(CNN, self).__init__()

        # init bn
        self.bn_init = nn.BatchNorm2d(1)

        # layer 1
        self.conv_1 = nn.Conv2d(1, 64, 3, padding=1)
        self.bn_1 = nn.BatchNorm2d(64)
        self.mp_1 = nn.MaxPool2d((2, 4))

        # layer 2
        self.conv_2 = nn.Conv2d(64, 128, 3, padding=1)
        self.bn_2 = nn.BatchNorm2d(128)
        self.mp_2 = nn.MaxPool2d((2, 4))

        # layer 3
        self.conv_3 = nn.Conv2d(128, 128, 3, padding=1)
        self.bn_3 = nn.BatchNorm2d(128)
        self.mp_3 = nn.MaxPool2d((2, 4))

        # layer 4
        self.conv_4 = nn.Conv2d(128, 128, 3, padding=1)
        self.bn_4 = nn.BatchNorm2d(128)
        self.mp_4 = nn.MaxPool2d((3, 5))

        # layer 5
        self.conv_5 = nn.Conv2d(128, 64, 3, padding=1)
        self.bn_5 = nn.BatchNorm2d(64)
        self.mp_5 = nn.MaxPool2d((4, 4))

        # classifier
50
        self.dense = nn.Linear(320, num_class)
Verena Praher's avatar
Verena Praher committed
51
52
53
        self.dropout = nn.Dropout(0.5)

    def forward(self, x):
54
        # x = x.unsqueeze(1)
Verena Praher's avatar
Verena Praher committed
55
56
57

        # init bn
        x = self.bn_init(x)
58
        # print(x.shape)
Verena Praher's avatar
Verena Praher committed
59
60
        # layer 1
        x = self.mp_1(nn.ELU()(self.bn_1(self.conv_1(x))))
61
        # print(x.shape)
Verena Praher's avatar
Verena Praher committed
62
63

        # layer 2
64
65
66
        x = nn.ELU()(self.bn_2(self.conv_2(x)))
        # x = self.mp_2(nn.ELU()(self.bn_2(self.conv_2(x))))
        # print(x.shape)
Verena Praher's avatar
Verena Praher committed
67
68
69

        # layer 3
        x = self.mp_3(nn.ELU()(self.bn_3(self.conv_3(x))))
70
        # print(x.shape)
Verena Praher's avatar
Verena Praher committed
71
72

        # layer 4
73
        # x = nn.ELU()(self.bn_4(self.conv_4(x)))
Verena Praher's avatar
Verena Praher committed
74
        x = self.mp_4(nn.ELU()(self.bn_4(self.conv_4(x))))
75
        # print(x.shape)
Verena Praher's avatar
Verena Praher committed
76
77
78

        # layer 5
        x = self.mp_5(nn.ELU()(self.bn_5(self.conv_5(x))))
79
        # print(x.shape)
Verena Praher's avatar
Verena Praher committed
80
81
82

        # classifier
        x = x.view(x.size(0), -1)
83
        # print("Lin input", x.shape)
Verena Praher's avatar
Verena Praher committed
84
85
        x = self.dropout(x)
        logit = nn.Sigmoid()(self.dense(x))
86
        # print(x.shape)
Verena Praher's avatar
Verena Praher committed
87
88
89
90

        return logit

    def my_loss(self, y_hat, y):
91
92
        return F.binary_cross_entropy(y_hat, y)

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
    def forward_full_song(self, x, y):
        # print(x.shape)
        #TODO full song???
        return self.forward(x[:, :, :, :512])
        # y_hat = torch.zeros((x.shape[0], 56), requires_grad=True).cuda()
        # hop_size = 256
        # i=0
        # count = 0
        # while i < x.shape[-1]:
        #     y_hat += self.forward(x[:,:,:,i:i+512])
        #     i += hop_size
        #     count += 1
        # return y_hat/count

    def training_step(self, data_batch, batch_nb):
        x, _, y = data_batch
        y_hat = self.forward_full_song(x, y)
        y = y.float()
        y_hat = y_hat.float()
        return {'loss':self.my_loss(y_hat, y)}

    def validation_step(self, data_batch, batch_nb):
        # print("data_batch", data_batch)
        x, _, y = data_batch
        # print("x", x)
        # print("y", y)
        y_hat = self.forward_full_song(x, y)
        y = y.float()
        y_hat = y_hat.float()
        rocauc = metrics.roc_auc_score(y.t().cpu(), y_hat.t().cpu())
        prauc = metrics.average_precision_score(y.t().cpu(), y_hat.t().cpu())
        # _, _, fscore, _ = metrics.precision_recall_fscore_support(y.t().cpu(), y_hat.t().cpu())
        fscore = 0.
        return {'val_loss': self.my_loss(y_hat, y),
                'rocauc':rocauc,
                'prauc':prauc,
                'fscore':fscore}

    def validation_end(self, outputs):
        avg_loss = torch.stack([x['val_loss'] for x in outputs]).mean()
        avg_auc = torch.stack([torch.tensor([x['rocauc']]) for x in outputs]).mean()
        avg_prauc = torch.stack([torch.tensor([x['prauc']]) for x in outputs]).mean()
        avg_fscore = torch.stack([torch.tensor([x['fscore']]) for x in outputs]).mean()
        return {'val_loss':avg_loss,
                'rocauc':avg_auc,
                'prauc':avg_prauc,
                'fscore':avg_fscore}

141
    def configure_optimizers(self):
Shreyan Chowdhury's avatar
Shreyan Chowdhury committed
142
143
144
145
        return [torch.optim.Adam(self.parameters(), lr=1e-4)]  # from their code

    @pl.data_loader
    def tng_dataloader(self):
146
147
148
149
150
151
        train_csv = os.path.join(PATH_ANNOTATIONS, 'train_processed.tsv')
        cache_x_name = "_ap_mtgjamendo44k"
        dataset = df_get_mtg_set('mtgjamendo', train_csv, PATH_AUDIO, cache_x_name)
        return DataLoader(dataset=dataset,
                                  batch_size=32,
                                  shuffle=True)
Shreyan Chowdhury's avatar
Shreyan Chowdhury committed
152
153
154

    @pl.data_loader
    def val_dataloader(self):
155
156
157
158
159
160
        validation_csv = os.path.join(PATH_ANNOTATIONS, 'validation_processed.tsv')
        cache_x_name = "_ap_mtgjamendo44k"
        dataset = df_get_mtg_set('mtgjamendo_val', validation_csv, PATH_AUDIO, cache_x_name)
        return DataLoader(dataset=dataset,
                          batch_size=32,
                          shuffle=True)
Shreyan Chowdhury's avatar
Shreyan Chowdhury committed
161
162
163

    @pl.data_loader
    def test_dataloader(self):
164
165
166
167
168
169
        test_csv = os.path.join(PATH_ANNOTATIONS, 'test_processed.tsv')
        cache_x_name = "_ap_mtgjamendo44k"
        dataset = df_get_mtg_set('mtgjamendo_test', test_csv, PATH_AUDIO, cache_x_name)
        return DataLoader(dataset=dataset,
                          batch_size=32,
                          shuffle=True)
Shreyan Chowdhury's avatar
Shreyan Chowdhury committed
170
171
172
173
174

    @staticmethod
    def add_model_specific_args(parent_parser, root_dir):
        return parent_parser
        pass