-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathutils.py
83 lines (63 loc) · 2.38 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
import pickle as pkl # For loading the dataset file
def load_dataset(filename="mnist.pkl"):
"""Load MNIST images & labels from a pickle file.
Input:
- filename: A string for the name of the pickle file containing the MNIST samples.
Output:
- data_dict: A dictionary that contains the images and the labels.
"""
infile = open(filename, 'rb')
data_dict = pkl.load(infile)
infile.close()
return data_dict
def load_network(filename="network_3layer.pkl"):
"""Load a network from a pickle file.
Input:
- filename: A string for the name of the pickle file containing the network.
Output:
- network: A list of layers, e.g.
[['linear', Weights], 'relu', ['linear', Weights], ...]
"""
infile = open(filename, 'rb')
network = pkl.load(infile)
infile.close()
return network
def display_image(X):
"""Display an image using ASCII chars.
Input:
- X: An image as a vector; i.e. a list with D elements.
Output: None.
"""
for i in range(0, 28*28):
if i % 28 == 0 and i > 0: print("")
print("." if X[i] < 125 else "@", end="")
print("")
def display_network(network):
"""Display a network's layers and layer sizes.
Input:
- network: A list of layers, e.g.
[['linear', Weights], 'relu', ['linear', Weights], ...]
Output: None.
"""
print([layer[0]+": " + str(len(layer[1][0]))+"->"+str(len(layer[1])) if type(layer) == list else layer for layer in network])
def calculate_accuracy(dataset, network, predictor):
"""Calculate the accuracy of a network's predictions.
Input:
- dataset: A dictionary that contains the images and the labels.
- network: A list of layers, e.g.
[['linear', Weights], 'relu', ['linear', Weights], ...]
- predictor: The forward-pass function that takes the network and a sample, and returns the outputs
of the last layer.
Output: Accuracy (%).
"""
X_test = dataset['X_test']
y_test = dataset['y_test']
N = len(X_test)
correct = 0
for i in range(N):
X = X_test[i]
y = y_test[i]
output = predictor(network, X)
y_pred = output.index(max(output))
if y == y_pred: correct += 1
return (correct / N) * 100