File size: 1,547 Bytes
452723c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
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
50
51
52
53
54
55
56
57
"""Model utility functions."""

import torch
import os.path
import numpy as np
import matplotlib.pyplot as plt
from src.utils.logging_util import LoggingUtils

logger = LoggingUtils.configure_logger(log_name=__name__)



def save_model(model, filepath="model.pth"):
    """Funtion to save model weights to a file."""
    
    save_dir = os.path.dirname(filepath)
    if not os.path.exists(save_dir):
        os.makedirs(save_dir)

    torch.save(model.state_dict(), filepath)
    logger.info(f"Model saved to {filepath}")


def load_model(model_class, filepath, device, model_args):
    """Function to load model weights and initialize the model."""
    
    model = model_class(**model_args).to(device)
    model.load_state_dict(torch.load(filepath, map_location=device))
    model.eval()
    logger.info(f"Model loaded from {filepath}")
    return model


def display_num_param(net):
    nb_param = 0
    for param in net.parameters():
        nb_param += param.numel()
    print('Number of parameters: {} ({:.2f} million)'.format(nb_param, nb_param/1e6))


def get_error(scores, labels):
    bs=scores.size(0)
    predicted_labels = scores.argmax(dim=1)
    indicator = (predicted_labels == labels)
    num_matches=indicator.sum()
    return 1-num_matches.float()/bs


def show(X):
    if X.dim() == 3 and X.size(0) == 3:
        plt.imshow( np.transpose(  X.numpy() , (1, 2, 0))  )
        plt.show()
    elif X.dim() == 2:
        plt.imshow(   X.numpy() , cmap='gray'  )
        plt.show()
    else:
        logger.error("WRONG TENSOR SIZE")