-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.py
89 lines (73 loc) · 2.56 KB
/
utils.py
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
84
85
86
87
88
import numpy as np
import matplotlib.pyplot as plt
import math
def false_alarm_rate(target, predicted, show_fig: bool = False):
"""
Calculate AUC and false alarm auc
:param target: [n,1]
:param predicted: [n,1]
:param show_fig: default false
:return: PD_PF_AUC, PF_tau_AUC
"""
target = np.array(target)
predicted = np.array(predicted)
if target.shape != predicted.shape:
assert False, 'Wrong shape!'
target = (target - target.min()) / (target.max() - target.min())
predicted = (predicted - predicted.min()) / (predicted.max() - predicted.min())
anomaly_map = target
normal_map = 1 - target
num = 30000
taus = np.linspace(0, predicted.max(), num=num)
PF = np.zeros([num, 1])
PD = np.zeros([num, 1])
for index in range(num):
tau = taus[index]
anomaly_map_1 = np.double(predicted >= tau)
PF[index] = np.sum(anomaly_map_1 * normal_map) / np.sum(normal_map)
PD[index] = np.sum(anomaly_map_1 * anomaly_map) / np.sum(anomaly_map)
if show_fig:
plt.figure(1)
plt.plot(PF, PD)
plt.figure(2)
plt.plot(taus, PD)
plt.figure(3)
plt.plot(taus, PF)
plt.show()
PD_PF_auc = np.sum((PF[0:num - 1, :] - PF[1:num, :]) * (PD[1:num] + PD[0:num - 1]) / 2)
PF_tau_auc = np.trapz(PF.squeeze(), taus.squeeze())
return PD_PF_auc, PF_tau_auc
def normalize(data):
"""
normalize data to [0, 1]
:param data: input data
:return: data in [0, 1]
"""
data = (data - data.min()) / (data.max() - data.min())
return data
def channel_align(x, target_channels):
"""
Set the number of channels of x to target_channels.
:param x: tensor
:param target_channels: int
:return: channel aligned x
"""
channels = x.shape[-1]
if channels == target_channels:
return [x]
x_new = []
if channels / target_channels < 2:
if channels < target_channels:
right = int((target_channels- channels) / 2)
left = int(target_channels - channels - right)
x = np.pad(x, ((0, 0), (0, 0), (left, right)), mode='reflect')
elif channels > target_channels:
c = np.sort(np.random.choice(channels, target_channels, replace=False))
x = x[:,:,c]
x_new.append(x)
else:
n = math.floor(channels / target_channels)
c = np.sort(np.random.choice(channels, target_channels * n, replace=False))
for i in range(n):
x_new.append(x[:, :, c[target_channels * i:target_channels * (i+1)]])
return x_new