utils.py 8.23 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
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":{
33
        "rechenknecht3.cp.jku.at":  "/media/rk3/shared/midlevel",
34
35
36
37
38
39
40
41
        "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
73
74
    PATH_DATA_CACHE = '/home/shreyan/mounts/home@rk2/shared/kofta_cached_datasets'

Shreyan Chowdhury's avatar
Shreyan Chowdhury committed
75
else:
76
77
    # 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
78
79
    USE_GPU = False

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

83
PATH_DATA_ROOT = data_roots[use_dataset][hostname]
Verena Praher's avatar
Verena Praher committed
84

Shreyan Chowdhury's avatar
Shreyan Chowdhury committed
85
86
87
88
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
89
PATH_MELSPEC_DOWNLOADED_HDF5 = os.path.join(PATH_DATA_ROOT, 'HDF5Cache_spectrograms')
Shreyan Chowdhury's avatar
Shreyan Chowdhury committed
90
91
TRAINED_MODELS_PATH = ''

92
93
94
95
96
97
98
99
100
101
102
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')


103
104
105
106
107
108
109
110
111
112
113
def get_paths(dataset_name):
    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')
    else:
        PATH_AUDIO = os.path.join(PATH_DATA_ROOT, 'audio')
        PATH_ANNOTATIONS = os.path.join(PATH_DATA_ROOT, 'annotations')
114
115
116
    return PATH_DATA_ROOT, PATH_AUDIO, PATH_ANNOTATIONS


Shreyan Chowdhury's avatar
Shreyan Chowdhury committed
117
118
# run name
def make_run_name(suffix=''):
119
    # assert ' ' not in suffix
Shreyan Chowdhury's avatar
Shreyan Chowdhury committed
120
121
122
    hash = hashlib.sha1()
    hash.update(str(time.time()).encode('utf-8'))
    run_hash = hash.hexdigest()[:5]
123
    name = run_hash + f' - {suffix}'
Shreyan Chowdhury's avatar
Shreyan Chowdhury committed
124
125
    return name

126
CURR_RUN_PATH = ''
Shreyan Chowdhury's avatar
Shreyan Chowdhury committed
127
curr_run_name = ''
Shreyan Chowdhury's avatar
Shreyan Chowdhury committed
128
129
130
filelog = logging.getLogger()
streamlog = logging.getLogger()
logger = logging.getLogger()
131
132

def init_experiment(comment='', name=None):
Shreyan Chowdhury's avatar
Shreyan Chowdhury committed
133
    global CURR_RUN_PATH, curr_run_name
134
135
136
137
138
    global filelog, streamlog, logger
    if name is None:
        curr_run_name = make_run_name(comment)
    else:
        curr_run_name = name
Shreyan Chowdhury's avatar
Shreyan Chowdhury committed
139
    CURR_RUN_PATH = os.path.join(PATH_RESULTS, 'runs', 'running - '+curr_run_name)
140
141

    if not os.path.isdir(CURR_RUN_PATH):
142
        os.makedirs(CURR_RUN_PATH)
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165

    # 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
166
167
def exit_experiment(status, exp):
    global CURR_RUN_PATH
Shreyan Chowdhury's avatar
Shreyan Chowdhury committed
168
169
    if status=='failed':
        os.rename(CURR_RUN_PATH, os.path.join(PATH_RESULTS, 'runs', 'failed - '+curr_run_name))
Shreyan Chowdhury's avatar
Shreyan Chowdhury committed
170
        CURR_RUN_PATH = os.path.join(PATH_RESULTS, 'runs', 'failed - '+curr_run_name)
Shreyan Chowdhury's avatar
Shreyan Chowdhury committed
171
172
    elif status=='stopped':
        os.rename(CURR_RUN_PATH, os.path.join(PATH_RESULTS, 'runs', 'stopped - '+curr_run_name))
Shreyan Chowdhury's avatar
Shreyan Chowdhury committed
173
        CURR_RUN_PATH =  os.path.join(PATH_RESULTS, 'runs', 'stopped - '+curr_run_name)
Shreyan Chowdhury's avatar
Shreyan Chowdhury committed
174
175
    else:
        os.rename(CURR_RUN_PATH, os.path.join(PATH_RESULTS, 'runs', curr_run_name))
Shreyan Chowdhury's avatar
Shreyan Chowdhury committed
176
    exp.save_dir = CURR_RUN_PATH
Shreyan Chowdhury's avatar
Shreyan Chowdhury committed
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219

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



220
221
222
223
224
225
226
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
227
228
229
if __name__=='__main__':
    # TESTS

230
    c = nn.Conv2d(1, 64, 3, 1, 1) # (in_channels, out_channels, kernel_size, stride, padding)
Shreyan Chowdhury's avatar
Shreyan Chowdhury committed
231
    # m = nn.MaxPool2d(2)
232
    print(dims_calc(c, [256, 600, 1]))
Shreyan Chowdhury's avatar
Shreyan Chowdhury committed
233
234
235

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