utils.py 4.49 KB
Newer Older
Shreyan Chowdhury's avatar
Shreyan Chowdhury committed
1
2
3
4
5
6
7
8
9
10
11
import os
import time
import hashlib
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
12
from sklearn.metrics import roc_auc_score, precision_recall_curve, f1_score, auc
Shreyan Chowdhury's avatar
Shreyan Chowdhury committed
13
14


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


Shreyan Chowdhury's avatar
Shreyan Chowdhury committed
18
19
20
21
22
23
24
25
26
# PARAMS =======================
INPUT_SIZE = (96, 256)
MAX_FRAMES = 40


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

# paths:
hostname = os.uname()[1]
27
if hostname in ['rechenknecht3.cp.jku.at']:
Shreyan Chowdhury's avatar
Shreyan Chowdhury committed
28
    plt.switch_backend('agg')
29
    PATH_DATA_ROOT = '/media/rk3/shared/datasets/MTG-Jamendo'
Shreyan Chowdhury's avatar
Shreyan Chowdhury committed
30
    USE_GPU = True
31
32
33
34
elif hostname == 'hermine':  # PC verena
    plt.switch_backend('agg')
    PATH_DATA_ROOT = '/media/verena/SAMSUNG/Data/MTG-Jamendo'
    USE_GPU = True
Shreyan Chowdhury's avatar
Shreyan Chowdhury committed
35
36
37
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
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
else:
    PATH_DATA_ROOT = '/mnt/2tb/datasets/MTG-Jamendo'
    USE_GPU = False

PATH_PROJECT_ROOT = os.path.dirname(os.path.realpath(__file__))
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')
PATH_RESULTS = os.path.join(PATH_PROJECT_ROOT, 'results')
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



132
133
134
135
136
137
138
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
139
140
141
142
143
144
if __name__=='__main__':
    # TESTS

    # c = nn.Conv2d(512, 256, 1, 1, 0) # (in_channels, out_channels, kernel_size, stride, padding)
    # m = nn.MaxPool2d(2)
    # print(dims_calc(c, [37, 17, 512]))
Shreyan Chowdhury's avatar
Shreyan Chowdhury committed
145
146
147

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