-
Notifications
You must be signed in to change notification settings - Fork 0
/
train_cnn.py
71 lines (56 loc) · 2 KB
/
train_cnn.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
'''
Description: Script to train the network and measure its performance on the test set.
'''
from CNN.network import *
from CNN.utils import *
from tqdm import tqdm
import argparse
import matplotlib.pyplot as plt
import pickle
parser = argparse.ArgumentParser(description='Train a convolutional neural network.')
parser.add_argument('save_path', metavar = 'Save Path', help='name of file to save parameters in.')
if __name__ == '__main__':
args = parser.parse_args()
save_path = args.save_path
cost = train(save_path = save_path)
params, cost = pickle.load(open(save_path, 'rb'))
[f1, f2, w3, w4, b1, b2, b3, b4] = params
# Plot cost
plt.plot(cost, 'r')
plt.xlabel('# Iterations')
plt.ylabel('Cost')
plt.legend('Loss', loc='upper right')
plt.show()
# Get test data
m = 144
X = extract_data('dataset_50x50_MNIST/t10k-images-idx3-ubyte.gz', m, 50)
y_dash = extract_labels('dataset_50x50_MNIST/t10k-labels-idx1-ubyte.gz', m).reshape(m,1)
# Normalize the data
X-= int(np.mean(X)) # subtract mean
X/= int(np.std(X)) # divide by standard deviation
test_data = np.hstack((X,y_dash))
X = test_data[:,0:-1]
X = X.reshape(len(test_data), 3, 50, 50)
y = test_data[:,-1]
corr = 0
digit_count = [0 for i in range(2)]
digit_correct = [0 for i in range(2)]
print()
print("Computing accuracy over test set:")
t = tqdm(range(len(X)), leave=True)
for i in t:
x = X[i]
pred, prob = predict(x, f1, f2, w3, w4, b1, b2, b3, b4)
digit_count[int(y[i])]+=1
if pred==y[i]:
corr+=1
digit_correct[pred]+=1
t.set_description("Acc:%0.2f%%" % (float(corr/(i+1))*100))
print("Overall Accuracy: %.2f" % (float(corr/len(test_data)*100)))
x = np.arange(10)
digit_recall = [x/y for x,y in zip(digit_correct, digit_count)]
plt.xlabel('Digits')
plt.ylabel('Recall')
plt.title("Recall on Test Set")
plt.bar(x,digit_recall)
plt.show()