File size: 2,776 Bytes
da7cd93
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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
import datetime
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim

from matplotlib import pyplot as plt
from data_loader_interface import load_imu
from sklearn.metrics import accuracy_score, f1_score, confusion_matrix, classification_report, average_precision_score
from torch.utils.data import Dataset, DataLoader, TensorDataset, ConcatDataset
from einops import rearrange
from torch.optim.lr_scheduler import StepLR


def test(model, test_loader, output_file):
    running_loss = 0.0
    predlist = torch.zeros(0, dtype=torch.long, device='cpu')
    lbllist = torch.zeros(0, dtype=torch.long, device='cpu')
    number_of_nan_loss = 0
    
    with torch.no_grad(), open(output_file, 'w') as f:
        for batch_idx, (data) in enumerate(test_loader):
            data = data.float().to('cpu')
            outputs = model(data)
            _, predicted = torch.max(outputs.data, 1)
            predlist = torch.cat([predlist, predicted.view(-1).cpu()])
            # lbllist = torch.cat([lbllist, labels.view(-1).cpu()])

            for i, prediction in enumerate(predicted):
                f.write(f"{prediction.item()}\n")

    return running_loss / len(test_loader), predlist


class MyDataset_labeled(Dataset):
    def __init__(self, x):
        self.x_data = torch.from_numpy(np.array(x)).to(torch.float)
        self.len = x.shape[0]

    def __getitem__(self, idx):
        return self.x_data[idx]

    def __len__(self):
        return self.len


def model_defining(test_data_array, name_model, output_file):
    
    test_losses = []
    accuracies = []
    f1_scores = []
    cm_list = []
    cr_list = []

    model = torch.load(str(name_model) + ".pth", map_location=torch.device('cpu'))
    model.eval()

    test_data = load_imu(test_data_array)
    test_data = rearrange(test_data, 'n t c -> n c t')

    test_dataset = MyDataset_labeled(test_data)
    test_dataloaders = DataLoader(test_dataset, batch_size=256, shuffle=False, drop_last=False)

    print("Data loaded ...")

    test_loss, predlist = test(model, test_dataloaders, output_file)
    test_losses.append(test_loss)


def main():

    name_model = "./models_chadwick/training_3S_model_validation/S3_101_102_103_validation_epoch_10"
    train_subjects = []
    test_subjects = ['104'] 
    output_file = "S3_101_102_103_validation_epoch_10_tested_104_predicted.txt"
    label_file = "S3_101_102_103_validation_epoch_10_tested_104_label.txt"
    classification_file = "S3_101_102_103_validation_epoch_10_tested_104_classification.txt"

    model_defining(train_subjects, test_subjects, name_model, output_file, label_file, classification_file)


if __name__ == "__main__":
    main()