utils.py 6.96 KB
Newer Older
Shreyan Chowdhury's avatar
Shreyan Chowdhury committed
1
2
3
import os
import time
import hashlib
Verena Praher's avatar
Verena Praher committed
4
import getpass
Shreyan Chowdhury's avatar
Shreyan Chowdhury committed
5
6
7
8
9
10
11
12
import datetime
import torch
import torch.nn as nn
import logging
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
from tqdm import tqdm
Shreyan Chowdhury's avatar
Shreyan Chowdhury committed
13
from sklearn.metrics import roc_auc_score, precision_recall_curve, f1_score, auc
Shreyan Chowdhury's avatar
Shreyan Chowdhury committed
14
15


Shreyan Chowdhury's avatar
Shreyan Chowdhury committed
16
plt.rcParams["figure.dpi"] = 288 # increase dpi for clearer plots
Shreyan Chowdhury's avatar
Shreyan Chowdhury committed
17
18


Shreyan Chowdhury's avatar
Shreyan Chowdhury committed
19
20
# PARAMS =======================
INPUT_SIZE = (96, 256)
Shreyan Chowdhury's avatar
Shreyan Chowdhury committed
21
MAX_LENGTH = 10000
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
data_roots = {
    "mtgjamendo":{
        "rechenknecht3.cp.jku.at":  "/media/rk3/shared/datasets/MTG-Jamendo",
        "rechenknecht2.cp.jku.at":  "/media/rk2/shared/datasets/MTG-Jamendo",
        "rechenknecht1.cp.jku.at":  "/media/rk1/shared/datasets/MTG-Jamendo",
        "hermine":                  "/media/verena/SAMSUNG/Data/MTG-Jamendo",
        "verena-830g5":             "/media/verena/SAMSUNG/Data/MTG-Jamendo",
        "shreyan-HP":               "/home/shreyan/mounts/home@rk3/shared/datasets/MTG-Jamendo",
        "shreyan-All-Series":       "/mnt/2tb/datasets/MTG-Jamendo"
    },
    "midlevel":{
        "rechenknecht3.cp.jku.at":  "/media/rk3/shared/datasets/midlevel",
        "rechenknecht2.cp.jku.at":  "/media/rk2/shared/datasets/midlevel",
        "rechenknecht1.cp.jku.at":  "/media/rk1/shared/datasets/midlevel",
        "hermine":"",
        "verena-830g5":"",
        "shreyan-HP":               "/mnt/2tb/datasets/MidlevelFeatures",
        "shreyan-All-Series":       "/mnt/2tb/datasets/MidlevelFeatures"
    }
}
Shreyan Chowdhury's avatar
Shreyan Chowdhury committed
42

43
use_dataset= "mtgjamendo"
Shreyan Chowdhury's avatar
Shreyan Chowdhury committed
44
45
46
# CONFIG =======================

# paths:
Verena Praher's avatar
Verena Praher committed
47
48
49
50

PATH_PROJECT_ROOT = os.path.dirname(os.path.realpath(__file__))
PATH_RESULTS = os.path.join(PATH_PROJECT_ROOT, 'results')

Shreyan Chowdhury's avatar
Shreyan Chowdhury committed
51
hostname = os.uname()[1]
Verena Praher's avatar
Verena Praher committed
52
53
username = getpass.getuser()

Verena Praher's avatar
Verena Praher committed
54
if hostname in ['rechenknecht3.cp.jku.at']:
Shreyan Chowdhury's avatar
Shreyan Chowdhury committed
55
    plt.switch_backend('agg')
56
    PATH_DATA_CACHE = '/media/rk3/shared/kofta_cached_datasets'
Shreyan Chowdhury's avatar
Shreyan Chowdhury committed
57
    USE_GPU = True
Verena Praher's avatar
Verena Praher committed
58
59
60
61
elif hostname == 'rechenknecht2.cp.jku.at':
    plt.switch_backend('agg')
    PATH_DATA_CACHE = '/media/rk2/shared/kofta_cached_datasets'
    USE_GPU = True
62
63
64
65
elif hostname == 'rechenknecht1.cp.jku.at':
    plt.switch_backend('agg')
    PATH_DATA_CACHE = '/media/rk1/shared/kofta_cached_datasets'
    USE_GPU = True
66
67
68
elif hostname == 'hermine':  # PC verena
    plt.switch_backend('agg')
    USE_GPU = True
Verena Praher's avatar
Verena Praher committed
69
70
elif hostname == 'verena-830g5': # Laptop Verena
    USE_GPU = False
Shreyan Chowdhury's avatar
Shreyan Chowdhury committed
71
72
elif hostname == 'shreyan-HP': # Laptop Shreyan
    USE_GPU = False
Shreyan Chowdhury's avatar
Shreyan Chowdhury committed
73
else:
74
75
    # PATH_DATA_CACHE = '/home/shreyan/mounts/home@rk3/shared/kofta_cached_datasets'
    PATH_DATA_CACHE = '/mnt/2tb/datasets/data_caches'
Shreyan Chowdhury's avatar
Shreyan Chowdhury committed
76
77
    USE_GPU = False

Verena Praher's avatar
Verena Praher committed
78
79
80
if username == 'verena':
    PATH_RESULTS = '/home/verena/experiments/moodwalk/'

81
PATH_DATA_ROOT = data_roots[use_dataset][hostname]
Verena Praher's avatar
Verena Praher committed
82

Shreyan Chowdhury's avatar
Shreyan Chowdhury committed
83
84
85
86
PATH_AUDIO = os.path.join(PATH_DATA_ROOT, 'MTG-Jamendo_audio')
PATH_ANNOTATIONS = os.path.join(PATH_DATA_ROOT, 'MTG-Jamendo_annotations')
PATH_MELSPEC_DOWNLOADED = os.path.join(PATH_DATA_ROOT, 'MTG-Jamendo_melspec_downloaded')
PATH_MELSPEC_DOWNLOADED_FRAMED = os.path.join(PATH_MELSPEC_DOWNLOADED, 'framed')
Shreyan Chowdhury's avatar
Shreyan Chowdhury committed
87
PATH_MELSPEC_DOWNLOADED_HDF5 = os.path.join(PATH_DATA_ROOT, 'HDF5Cache_spectrograms')
Shreyan Chowdhury's avatar
Shreyan Chowdhury committed
88
89
TRAINED_MODELS_PATH = ''

90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
def set_paths(dataset_name):
    global PATH_DATA_ROOT, PATH_AUDIO, PATH_ANNOTATIONS
    PATH_DATA_ROOT = data_roots[dataset_name][hostname]
    if dataset_name=='midlevel':
        PATH_AUDIO = os.path.join(PATH_DATA_ROOT, 'audio')
        PATH_ANNOTATIONS = os.path.join(PATH_DATA_ROOT, 'metadata_annotations')
    elif dataset_name=='mtgjamendo':
        PATH_AUDIO = os.path.join(PATH_DATA_ROOT, 'MTG-Jamendo_audio')
        PATH_ANNOTATIONS = os.path.join(PATH_DATA_ROOT, 'MTG-Jamendo_annotations')


def get_paths():
    return PATH_DATA_ROOT, PATH_AUDIO, PATH_ANNOTATIONS


Shreyan Chowdhury's avatar
Shreyan Chowdhury committed
105
106
# run name
def make_run_name(suffix=''):
107
    # assert ' ' not in suffix
Shreyan Chowdhury's avatar
Shreyan Chowdhury committed
108
109
110
    hash = hashlib.sha1()
    hash.update(str(time.time()).encode('utf-8'))
    run_hash = hash.hexdigest()[:5]
111
    name = run_hash + f' - {suffix}'
Shreyan Chowdhury's avatar
Shreyan Chowdhury committed
112
113
    return name

114
CURR_RUN_PATH = ''
Shreyan Chowdhury's avatar
Shreyan Chowdhury committed
115
116
117
filelog = logging.getLogger()
streamlog = logging.getLogger()
logger = logging.getLogger()
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

def init_experiment(comment='', name=None):
    global CURR_RUN_PATH
    global filelog, streamlog, logger
    if name is None:
        curr_run_name = make_run_name(comment)
    else:
        curr_run_name = name
    CURR_RUN_PATH = os.path.join(PATH_RESULTS, 'runs', curr_run_name)

    if not os.path.isdir(CURR_RUN_PATH):
        os.mkdir(CURR_RUN_PATH)

    # SET UP LOGGING =============================================
    fh = logging.FileHandler(os.path.join(CURR_RUN_PATH, f'{curr_run_name}.log'))
    sh = logging.StreamHandler()
    formatter = logging.Formatter('%(asctime)s\t%(name)s\t%(levelname)s\t%(message)s')
    fh.setFormatter(formatter)
    sh.setFormatter(formatter)

    # filelog logs only to file
    filelog.addHandler(fh)
    filelog.setLevel(logging.INFO)

    # streamlog logs only to terminal
    streamlog.addHandler(sh)
    streamlog.setLevel(logging.INFO)

    # logger logs to both file and terminal
    logger.addHandler(fh)
    logger.addHandler(sh)
    logger.setLevel(logging.DEBUG)

    # ============================================

Shreyan Chowdhury's avatar
Shreyan Chowdhury committed
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

def write_to_file(data, path):
    # not fully implemented. unused function as of now.
    with open(path, 'w') as f:
        if isinstance(data, np.ndarray):
            for i in data:
                f.writelines(i)


def dims_calc(obj, in_shape):
    """
    utility function to calculate output dimensions of a conv2d or maxpool2d stage
    """
    kernel_size = obj.kernel_size
    stride = obj.stride
    padding = obj.padding
    dilation = obj.dilation
    h_in = in_shape[0]
    w_in = in_shape[1]

    if isinstance(obj, nn.Conv2d):
        h_out = int(((h_in + 2*padding[0] - dilation[0]*(kernel_size[0]-1))/stride[0])+1)
        w_out = int(((w_in + 2*padding[1] - dilation[1]*(kernel_size[1]-1))/stride[1])+1)
        out_shape = [h_out, w_out, obj.out_channels]
    elif isinstance(obj, nn.MaxPool2d):
        if isinstance(padding, int):
            padding = (padding, padding)
        if isinstance(dilation, int):
            dilation = (dilation, dilation)
        if isinstance(kernel_size, int):
            kernel_size = (kernel_size, kernel_size)
        if isinstance(stride, int):
            stride = (stride, stride)

        h_out = int(((h_in + 2 * padding[0] - dilation[0] * (kernel_size[0] - 1) -1) / stride[0]) + 1)
        w_out = int(((w_in + 2 * padding[1] - dilation[1] * (kernel_size[1] - 1)-1) / stride[1]) + 1)
        out_shape = [h_out, w_out, in_shape[2]]
    else:
        out_shape = [None, None, None]
    return out_shape



196
197
198
199
200
201
202
def save(model, path):
    try:
        torch.save(model.module.state_dict(), path)
    except AttributeError:
        torch.save(model.state_dict(), path)


Shreyan Chowdhury's avatar
Shreyan Chowdhury committed
203
204
205
if __name__=='__main__':
    # TESTS

206
    c = nn.Conv2d(1, 64, 3, 1, 1) # (in_channels, out_channels, kernel_size, stride, padding)
Shreyan Chowdhury's avatar
Shreyan Chowdhury committed
207
    # m = nn.MaxPool2d(2)
208
    print(dims_calc(c, [256, 600, 1]))
Shreyan Chowdhury's avatar
Shreyan Chowdhury committed
209
210
211

    # preprocess_specs(source_root=PATH_MELSPEC_DOWNLOADED,
    #                  destination_root=PATH_MELSPEC_DOWNLOADED_FRAMED)
Shreyan Chowdhury's avatar
Shreyan Chowdhury committed
212
    pass