utils.py 4.98 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
Shreyan Chowdhury's avatar
Shreyan Chowdhury committed
22
23
24
25
26


# CONFIG =======================

# paths:
Verena Praher's avatar
Verena Praher committed
27
28
29
30

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
31
hostname = os.uname()[1]
Verena Praher's avatar
Verena Praher committed
32
33
34
username = getpass.getuser()

if hostname in ['rechenknecht3.cp.jku.at', 'rechenknecht2.cp.jku.at']:
Shreyan Chowdhury's avatar
Shreyan Chowdhury committed
35
    plt.switch_backend('agg')
36
    PATH_DATA_ROOT = '/media/rk3/shared/datasets/MTG-Jamendo'
37
    PATH_DATA_CACHE = '/media/rk3/shared/kofta_cached_datasets'
Shreyan Chowdhury's avatar
Shreyan Chowdhury committed
38
    USE_GPU = True
39
40
41
42
elif hostname == 'hermine':  # PC verena
    plt.switch_backend('agg')
    PATH_DATA_ROOT = '/media/verena/SAMSUNG/Data/MTG-Jamendo'
    USE_GPU = True
Verena Praher's avatar
Verena Praher committed
43
44
45
elif hostname == 'verena-830g5': # Laptop Verena
    PATH_DATA_ROOT = '/media/verena/SAMSUNG/Data/MTG-Jamendo'
    USE_GPU = False
Shreyan Chowdhury's avatar
Shreyan Chowdhury committed
46
47
48
elif hostname == 'shreyan-HP': # Laptop Shreyan
    PATH_DATA_ROOT = '/home/shreyan/mounts/home@rk3/shared/datasets/MTG-Jamendo'
    USE_GPU = False
Shreyan Chowdhury's avatar
Shreyan Chowdhury committed
49
50
else:
    PATH_DATA_ROOT = '/mnt/2tb/datasets/MTG-Jamendo'
51
    PATH_DATA_CACHE = os.path.join(PATH_DATA_ROOT, 'HDF5Cache_spectrograms')
Shreyan Chowdhury's avatar
Shreyan Chowdhury committed
52
53
    USE_GPU = False

Verena Praher's avatar
Verena Praher committed
54
55
56
57
if username == 'verena':
    PATH_RESULTS = '/home/verena/experiments/moodwalk/'


Shreyan Chowdhury's avatar
Shreyan Chowdhury committed
58
59
60
61
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
62
PATH_MELSPEC_DOWNLOADED_HDF5 = os.path.join(PATH_DATA_ROOT, 'HDF5Cache_spectrograms')
Shreyan Chowdhury's avatar
Shreyan Chowdhury committed
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
TRAINED_MODELS_PATH = ''

# run name
def make_run_name(suffix=''):
    assert ' ' not in suffix
    hash = hashlib.sha1()
    hash.update(str(time.time()).encode('utf-8'))
    run_hash = hash.hexdigest()[:5]
    name = run_hash + suffix
    return name

curr_run_name = make_run_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 =============================================
filelog = logging.getLogger()
streamlog = logging.getLogger()
logger = logging.getLogger()
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)

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

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



147
148
149
150
151
152
153
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
154
155
156
if __name__=='__main__':
    # TESTS

157
    c = nn.Conv2d(1, 64, 3, 1, 1) # (in_channels, out_channels, kernel_size, stride, padding)
Shreyan Chowdhury's avatar
Shreyan Chowdhury committed
158
    # m = nn.MaxPool2d(2)
159
    print(dims_calc(c, [256, 600, 1]))
Shreyan Chowdhury's avatar
Shreyan Chowdhury committed
160
161
162

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