-
Notifications
You must be signed in to change notification settings - Fork 5
/
evaluationlib.py
215 lines (158 loc) · 6.9 KB
/
evaluationlib.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
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import datasetlib
def show_loss_curves(history):
"""
Shows loss curves.
Parameters:
history (History): keras History from previous training using keras.Model.fit().
"""
# Show loss curves
plt.figure()
plt.title('Training performance')
plt.plot(history.epoch, history.history['loss'], label='training')
plt.plot(history.epoch, history.history['val_loss'], label='validation')
plt.xlabel('Epochs')
plt.ylabel('Loss')
plt.legend()
def confusion_matrix(cm, title='', cmap=plt.cm.Blues, labels=[]):
"""
Plot confusion matrix using matplotlib.
Parameters:
cm (xxx): confusion matrix.
title (string): title for the box.
cmap (?): colormap for matplotlib.
labels (List): labels for axis.
"""
plt.imshow(cm, interpolation='nearest', cmap=cmap)
plt.title(title)
plt.colorbar()
tick_marks = np.arange(len(labels))
plt.xticks(tick_marks, labels, rotation=45)
plt.yticks(tick_marks, labels)
plt.tight_layout()
plt.ylabel('True label')
plt.xlabel('Predicted label')
def plot_confusion_matrix(model, title, x_test, y_test, batch_size, classes):
"""
Makes a prediction, then builds the confusion matrix and plots it.
Parameters:
model (Model): keras.Model used for prediction.
x_test (List): training set data.
y_test (List): training set labels.
batch_size (int): batch dimension.
classes (List): labels for axis.
"""
# Plot confusion matrix
test_y_hat = model.predict(x_test, batch_size=batch_size)
confusion_m = np.zeros([len(classes), len(classes)])
confnorm = np.zeros([len(classes), len(classes)])
for i in range(0, x_test.shape[0]):
j = list(y_test[i, :]).index(1)
k = int(np.argmax(test_y_hat[i, :]))
confusion_m[j, k] = confusion_m[j, k] + 1
for i in range(0, len(classes)):
confnorm[i, :] = confusion_m[i, :] / np.sum(confusion_m[i, :])
confusion_matrix(confnorm, title, labels=classes)
def plot_double_input_confusion_matrix(model, title, iq_test, transformed_test, y_test, batch_size, classes):
"""
Makes a prediction, then builds the confusion matrix and plots it.
Parameters:
model (Model): keras.Model used for prediction.
y_test (List): training set labels.
batch_size (int): batch dimension.
classes (List): labels for axis.
"""
# Plot confusion matrix
test_y_hat = model.predict((iq_test, transformed_test), batch_size=batch_size)
confusion_m = np.zeros([len(classes), len(classes)])
confnorm = np.zeros([len(classes), len(classes)])
for i in range(0, iq_test.shape[0]):
j = list(y_test[i, :]).index(1)
k = int(np.argmax(test_y_hat[i, :]))
confusion_m[j, k] = confusion_m[j, k] + 1
for i in range(0, len(classes)):
confnorm[i, :] = confusion_m[i, :] / np.sum(confusion_m[i, :])
confusion_matrix(confnorm, title, labels=classes)
def plot_confusion_matrix_each_snr(model, neural_network_name, snrs, dataset_df, X_test, Y_test, test_index, classes):
# Plot confusion matrix
acc = {}
for snr in snrs:
# extract classes @ SNR
all_snrs = datasetlib.snrs(dataset_df)
all_snrs = np.array(all_snrs)
test_SNRs = list(all_snrs[test_index])
this_snr_indexes = np.where(np.array(test_SNRs) == snr)
test_X_i = X_test[this_snr_indexes]
test_Y_i = Y_test[this_snr_indexes]
# estimate classes
test_Y_i_hat = model.predict(test_X_i)
conf = np.zeros([len(classes), len(classes)])
confnorm = np.zeros([len(classes), len(classes)])
for i in range(0, test_X_i.shape[0]):
j = list(test_Y_i[i, :]).index(1)
k = int(np.argmax(test_Y_i_hat[i, :]))
conf[j, k] = conf[j, k] + 1
for i in range(0, len(classes)):
confnorm[i, :] = conf[i, :] / np.sum(conf[i, :])
plt.figure()
confusion_matrix(confnorm, labels=classes, title=neural_network_name + " (SNR=%d)" % (snr))
cor = np.sum(np.diag(conf))
ncor = np.sum(conf) - cor
print("Overall Accuracy: ", cor / (cor + ncor))
acc[snr] = 1.0 * cor / (cor + ncor)
return acc
def plot_double_input_confusion_matrix_each_snr(model, neural_network_name, snrs, dataset_df, iq_test, transformed_test, Y_test, test_index, classes):
# Plot confusion matrix
acc = {}
for snr in snrs:
# extract classes @ SNR
all_snrs = datasetlib.snrs(dataset_df)
all_snrs = np.array(all_snrs)
test_SNRs = list(all_snrs[test_index])
this_snr_indexes = np.where(np.array(test_SNRs) == snr)
test_X_i = (iq_test[this_snr_indexes], transformed_test[this_snr_indexes])
test_Y_i = Y_test[this_snr_indexes]
# estimate classes
test_Y_i_hat = model.predict(test_X_i)
conf = np.zeros([len(classes), len(classes)])
confnorm = np.zeros([len(classes), len(classes)])
for i in range(0, len(test_X_i[0])):
j = list(test_Y_i[i, :]).index(1)
k = int(np.argmax(test_Y_i_hat[i, :]))
conf[j, k] = conf[j, k] + 1
for i in range(0, len(classes)):
confnorm[i, :] = conf[i, :] / np.sum(conf[i, :])
plt.figure()
confusion_matrix(confnorm, labels=classes, title=neural_network_name + " (SNR=%d)" % (snr))
cor = np.sum(np.diag(conf))
ncor = np.sum(conf) - cor
print("Overall Accuracy: ", cor / (cor + ncor))
acc[snr] = 1.0 * cor / (cor + ncor)
return acc
def accuracy_dataframe(acc):
"""
Makes a prediction, then builds the confusion matrix and plots it.
Parameters:
acc (Matrix): first column is SNR, second column is accuracy.
Returns:
.* (DataFrame): pandas.DataFrame containing SNR and accuracy.
"""
accuracy_perc = {}
for el in acc.items():
accuracy_perc[el[0]] = int(el[1] * 100)
return pd.DataFrame(data=accuracy_perc, index=["Accuracy %"])
def accuracy_curve(snrs, acc, neural_network_name):
"""
Makes a prediction, then builds the confusion matrix and plots it.
Parameters:
snrs (List): unique list of SNRs.
acc (Matrix): first column is SNR, second column is accuracy.
neural_network_name (string): name of the used neural network.
"""
# Plot accuracy curve
plt.plot(snrs, list(map(lambda x: acc[x], snrs)))
plt.xlabel("Signal to Noise Ratio")
plt.ylabel("Classification Accuracy")
plt.title(neural_network_name)