-
Notifications
You must be signed in to change notification settings - Fork 5
/
test.py
108 lines (46 loc) · 1.49 KB
/
test.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
89
90
91
92
93
'''
Testing module to test the presence of Anomalous Events in a Video
The module computes reconstruction loss between input bunch and
the reconstructed batch from the model, and flagges the batch as anomalous
if loss value is greater than a given threshold.
Author: Harsh Tiku
'''
from keras.models import load_model
import numpy as np
def mean_squared_loss(x1,x2):
''' Compute Euclidean Distance Loss between
input frame and the reconstructed frame'''
diff=x1-x2
a,b,c,d,e=diff.shape
n_samples=a*b*c*d*e
sq_diff=diff**2
Sum=sq_diff.sum()
dist=np.sqrt(Sum)
mean_dist=dist/n_samples
return mean_dist
'''Define threshold for Sensitivity
Lower the Threshhold,higher the chances that a bunch of frames will be flagged as Anomalous.
'''
threshold=0.1
# model=load_model('AnomalyDetector.h5')
model=load_model('model.h5')
# X_test=np.load('test.npy')
X_test = np.load('training.npy')
frames=X_test.shape[2]
#Need to make number of frames divisible by 10
flag=0 #Overall video flagq
frames=frames-frames%10
X_test=X_test[:,:,:frames]
X_test=X_test.reshape(-1,227,227,10)
X_test=np.expand_dims(X_test,axis=4)
for number,bunch in enumerate(X_test):
n_bunch=np.expand_dims(bunch,axis=0)
reconstructed_bunch=model.predict(n_bunch)
loss=mean_squared_loss(n_bunch,reconstructed_bunch)
if loss>threshold:
print("Anomalous bunch of frames at bunch number {}".format(number))
flag=1
else:
print('Bunch Normal')
if flag==1:
print("Anomalous Events detected")