]> piware.de Git - handwriting-recognition.git/blob - nnet.py
ddf8ba68b948bfda759c4d8b5696f0efd6c39559
[handwriting-recognition.git] / nnet.py
1 # based on https://www.kdnuggets.com/2019/08/numpy-neural-networks-computational-graphs.html
2 import numpy as np
3
4 # use a constant seed to keep things reproducible
5 rg = np.random.default_rng(1)
6
7
8 class LinearLayer:
9     '''
10     ini_type: initialization type for weight parameters: plain, xavier, or he
11     '''
12     def __init__(self, input_shape, n_out, ini_type="plain"):
13         # initialize weights
14         n_in = input_shape[0]
15         if ini_type == 'plain':
16             self.W = rg.standard_normal(size=(n_out, n_in)) * 0.01  # set weights 'W' to small random gaussian
17         elif ini_type == 'xavier':
18             self.W = rg.standard_normal(size=(n_out, n_in)) / (np.sqrt(n_in))  # set variance of W to 1/n
19         elif ini_type == 'he':
20             # Good when ReLU used in hidden layers
21             # Delving Deep into Rectifiers: Surpassing Human-Level Performance on ImageNet Classification
22             # Kaiming He et al. (https://arxiv.org/abs/1502.01852)
23             # http: // cs231n.github.io / neural - networks - 2 /  # init
24             self.W = rg.standard_normal(size=(n_out, n_in)) * np.sqrt(2/n_in)  # set variance of W to 2/n
25
26         self.b = np.zeros((n_out, 1))
27         self.shape = (self.W.shape[0], input_shape[1])
28
29     def forward(self, A_prev):
30         self.A_prev = A_prev
31         return self.W @ self.A_prev + self.b
32
33     def backward(self, upstream_grad, learning_rate=0.1):
34         # derivative of Cost w.r.t W
35         dW = upstream_grad @ self.A_prev.T
36         # derivative of Cost w.r.t b, sum across rows
37         db = np.sum(upstream_grad, axis=1, keepdims=True)
38         # derivative of Cost w.r.t A_prev
39         dA_prev = self.W.T @ upstream_grad
40
41         # update parameters
42         self.W -= learning_rate * dW
43         self.b -= learning_rate * db
44
45         return dA_prev
46
47
48 class SigmoidLayer:
49     def __init__(self, shape):
50         self.shape = shape
51
52     def forward(self, Z):
53         assert Z.shape == self.shape
54         self.A = 1 / (1 + np.exp(-Z))  # compute activations
55         return self.A
56
57     def backward(self, upstream_grad, learning_rate=0.1):
58         # couple upstream gradient with local gradient, the result will be sent back to the Linear layer
59         return upstream_grad * self.A * (1 - self.A)
60
61
62 def label_vectors(labels, n):
63     y = np.zeros((n, labels.size))
64     for i, l in enumerate(labels):
65         y[l][i] = 1.0
66     return y
67
68
69 def forward(layers, X):
70     assert X.shape[1] == layers[0].shape[1], f'input length {X.shape[1]} does not match first layer width {layers[0].shape[1]}'
71     cur = X
72     for layer in layers:
73         cur = layer.forward(cur)
74     return cur
75
76
77 def classify(y):
78     # the recognized digit is the index of the highest-valued output neuron
79     return np.argmax(y, axis=0), np.max(y, axis=0)
80
81
82 def accuracy(layers, X, labels):
83     '''Count percentage of test inputs which are being recognized correctly'''
84
85     assert X.shape[1] == layers[0].shape[1], f'input length {X.shape[1]} does not match first layer width {layers[0].shape[1]}'
86     assert layers[0].shape[1] == labels.size, f'first layer width {layers[0].shape[1]} does not match number of labels {labels.size}'
87     output = forward(layers, X)
88     classes = classify(output)[0]
89     return 100 * (np.sum(classes == labels) / classes.size)
90
91
92 def cost_sqe(Y, output):
93     '''
94     This function computes and returns the Cost and its derivative.
95     The is function uses the Squared Error Cost function -> (1/2m)*sum(Y - output)^2
96     Args:
97         Y: label vectors of data
98         output: Predictions(activations) from a last layer, the output layer
99     Returns:
100         cost: The Squared Error Cost result
101         dOutput: gradient of Cost w.r.t the output
102     '''
103     m = Y.shape[1]
104
105     cost = (1 / (2 * m)) * np.sum(np.square(Y - output))
106     cost = np.squeeze(cost)  # remove extraneous dimensions to give just a scalar
107
108     dOutput = -1 / m * (Y - output)  # derivative of the squared error cost function
109     return cost, dOutput
110
111
112 def train(layers, X, Y, learning_rate=0.1, cost_fn=cost_sqe):
113     output = forward(layers, X)
114     cost, dOutput = cost_fn(Y, output)
115
116     cur = dOutput
117     for layer in reversed(layers):
118         cur = layer.backward(cur, learning_rate)
119
120     return cost