-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathutility.py
More file actions
76 lines (65 loc) · 2.02 KB
/
utility.py
File metadata and controls
76 lines (65 loc) · 2.02 KB
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
import torch
import torch.optim as optim
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from scipy.io import loadmat, savemat
import matplotlib.pyplot as plt
from sklearn.decomposition import PCA
from sklearn.model_selection import train_test_split
import random
from sklearn.metrics import confusion_matrix
def cal_results(matrix):
shape = np.shape(matrix)
number = 0
sum = 0
AA = np.zeros([shape[0]], dtype=np.float)
for i in range(shape[0]):
number += matrix[i, i]
AA[i] = matrix[i, i] / np.sum(matrix[i, :])
sum += np.sum(matrix[i, :]) * np.sum(matrix[:, i])
OA = number / np.sum(matrix)
AA_mean = np.mean(AA)
pe = sum / (np.sum(matrix) ** 2)
Kappa = (OA - pe) / (1 - pe)
return OA, AA_mean, Kappa, AA
def accuracy(output, target, topk=(1,)):
maxk = max(topk)
batch_size = target.size(0)
_, pred = output.topk(maxk, 1, True, True)
pred = pred.t()
correct = pred.eq(target.view(1, -1).expand_as(pred))
res = []
for k in topk:
correct_k = correct[:k].view(-1).float().sum(0)
res.append(correct_k.mul_(100.0/batch_size))
return res, target, pred.squeeze()
class AvgrageMeter(object):
def __init__(self):
self.reset()
def reset(self):
self.avg = 0
self.sum = 0
self.cnt = 0
def update(self, val, n=1):
self.sum += val * n
self.cnt += n
self.avg = self.sum / self.cnt
def cal_results(matrix):
shape = np.shape(matrix)
number = 0
sum = 0
AA = np.zeros([shape[0]], dtype=np.float)
for i in range(shape[0]):
number += matrix[i, i]
AA[i] = matrix[i, i] / np.sum(matrix[i, :])
sum += np.sum(matrix[i, :]) * np.sum(matrix[:, i])
OA = number / np.sum(matrix)
AA_mean = np.mean(AA)
pe = sum / (np.sum(matrix) ** 2)
Kappa = (OA - pe) / (1 - pe)
return OA, AA_mean, Kappa, AA
def output_metric(tar, pre):
matrix = confusion_matrix(tar, pre)
OA, AA_mean, Kappa, AA = cal_results(matrix)
return OA, AA_mean, Kappa, AA