-
Notifications
You must be signed in to change notification settings - Fork 0
/
test_utils.py
executable file
·191 lines (174 loc) · 7.85 KB
/
test_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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
import numpy as np
from termcolor import colored
from tensorflow.keras.layers import Input
from tensorflow.keras.layers import Conv2D
from tensorflow.keras.layers import MaxPooling2D
from tensorflow.keras.layers import Dropout
from tensorflow.keras.layers import Conv2DTranspose
from tensorflow.keras.layers import concatenate
from tensorflow.keras.layers import ZeroPadding2D
from tensorflow.keras.layers import Dense
# Compare the two inputs
def comparator(learner, instructor):
for a, b in zip(learner, instructor):
if tuple(a) != tuple(b):
print(colored("Test failed", attrs=['bold']),
"\n Expected value \n\n", colored(f"{b}", "green"),
"\n\n does not match the input value: \n\n",
colored(f"{a}", "red"))
raise AssertionError("Error in test")
print(colored("All tests passed!", "green"))
# extracts the description of a given model
def summary(model):
model.compile(optimizer='adam',
loss='categorical_crossentropy',
metrics=['accuracy'])
result = []
for layer in model.layers:
descriptors = [layer.__class__.__name__, layer.output_shape, layer.count_params()]
if (type(layer) == Conv2D):
descriptors.append(layer.padding)
descriptors.append(layer.activation.__name__)
descriptors.append(layer.kernel_initializer.__class__.__name__)
if (type(layer) == MaxPooling2D):
descriptors.append(layer.pool_size)
descriptors.append(layer.strides)
descriptors.append(layer.padding)
if (type(layer) == Dropout):
descriptors.append(layer.rate)
if (type(layer) == ZeroPadding2D):
descriptors.append(layer.padding)
if (type(layer) == Dense):
descriptors.append(layer.activation.__name__)
result.append(descriptors)
return result
def datatype_check(expected_output, target_output, error):
success = 0
if isinstance(target_output, dict):
for key in target_output.keys():
try:
success += datatype_check(expected_output[key],
target_output[key], error)
except:
print("Error: {} in variable {}. Got {} but expected type {}".format(error,
key, type(target_output[key]), type(expected_output[key])))
if success == len(target_output.keys()):
return 1
else:
return 0
elif isinstance(target_output, tuple) or isinstance(target_output, list):
for i in range(len(target_output)):
try:
success += datatype_check(expected_output[i],
target_output[i], error)
except:
print("Error: {} in variable {}, expected type: {} but expected type {}".format(error,
i, type(target_output[i]), type(expected_output[i])))
if success == len(target_output):
return 1
else:
return 0
else:
assert isinstance(target_output, type(expected_output))
return 1
def equation_output_check(expected_output, target_output, error):
success = 0
if isinstance(target_output, dict):
for key in target_output.keys():
try:
success += equation_output_check(expected_output[key],
target_output[key], error)
except:
print("Error: {} for variable {}.".format(error,
key))
if success == len(target_output.keys()):
return 1
else:
return 0
elif isinstance(target_output, tuple) or isinstance(target_output, list):
for i in range(len(target_output)):
try:
success += equation_output_check(expected_output[i],
target_output[i], error)
except:
print("Error: {} for variable in position {}.".format(error, i))
if success == len(target_output):
return 1
else:
return 0
else:
if hasattr(target_output, 'shape'):
np.testing.assert_array_almost_equal(target_output, expected_output)
else:
assert target_output == expected_output
return 1
def shape_check(expected_output, target_output, error):
success = 0
if isinstance(target_output, dict):
for key in target_output.keys():
try:
success += shape_check(expected_output[key],
target_output[key], error)
except:
print("Error: {} for variable {}.".format(error, key))
if success == len(target_output.keys()):
return 1
else:
return 0
elif isinstance(target_output, tuple) or isinstance(target_output, list):
for i in range(len(target_output)):
try:
success += shape_check(expected_output[i],
target_output[i], error)
except:
print("Error: {} for variable {}.".format(error, i))
if success == len(target_output):
return 1
else:
return 0
else:
if hasattr(target_output, 'shape'):
assert target_output.shape == expected_output.shape
return 1
def single_test(test_cases, target):
success = 0
for test_case in test_cases:
try:
if test_case['name'] == "datatype_check":
assert isinstance(target(*test_case['input']),
type(test_case["expected"]))
success += 1
if test_case['name'] == "equation_output_check":
assert np.allclose(test_case["expected"],
target(*test_case['input']))
success += 1
if test_case['name'] == "shape_check":
assert test_case['expected'].shape == target(*test_case['input']).shape
success += 1
except:
print("Error: " + test_case['error'])
if success == len(test_cases):
print("\033[92m All tests passed.")
else:
print('\033[92m', success," Tests passed")
print('\033[91m', len(test_cases) - success, " Tests failed")
raise AssertionError("Not all tests were passed for {}. Check your equations and avoid using global variables inside the function.".format(target.__name__))
def multiple_test(test_cases, target):
success = 0
for test_case in test_cases:
try:
target_answer = target(*test_case['input'])
if test_case['name'] == "datatype_check":
success += datatype_check(test_case['expected'], target_answer, test_case['error'])
if test_case['name'] == "equation_output_check":
success += equation_output_check(test_case['expected'], target_answer, test_case['error'])
if test_case['name'] == "shape_check":
success += shape_check(test_case['expected'], target_answer, test_case['error'])
except:
print("Error: " + test_case['error'])
if success == len(test_cases):
print("\033[92m All tests passed.")
else:
print('\033[92m', success," Tests passed")
print('\033[91m', len(test_cases) - success, " Tests failed")
raise AssertionError("Not all tests were passed for {}. Check your equations and avoid using global variables inside the function.".format(target.__name__))