This notebook showcases the implementation of the backpropagation algorithm to read hand-written digits
In [11]:
import csv
import random
import numpy as np
In [12]:
def readcsv(filename):
with open(filename, "r") as f:
reader = csv.reader(f, delimiter=",")
return list(reader)
The MNIST database was used for training
In [13]:
# Importing test and training data
training_data = np.array(readcsv("/content/sample_data/mnist_train_small.csv"), dtype=float)
test_data = np.array(readcsv("/content/sample_data/mnist_test.csv"), dtype=float)
In [14]:
# Normalizing data
normalize = lambda x: (x/255)*2-1
training_data[:, 1:] = normalize(training_data[:, 1:])
test_data[:, 1:] = normalize(test_data[:, 1:])
In [15]:
class Network:
def __init__(self, topology):
# Create network from topology with random weights and biases values between [-1, 1]
self.num_layers = len(topology)
self.weights = [np.random.uniform(-1, 1, size=(i, j)) for i, j in zip(topology[1:], topology[:-1])]
self.weights[0] = np.zeros((topology[1], topology[0]))
self.biases = [np.random.uniform(-1, 1, size=(i)) for i in topology[1:]]
def non_linearity(self, n):
return 1/(1 + np.exp(-n))
def cost_derivative(self, a, y):
return a-y
def non_linearity_prime(self, n):
return self.non_linearity(n)*(1-self.non_linearity(n))
def feedforward(self, a):
for w,b in zip(self.weights, self.biases):
z = w @ a + b
a = self.non_linearity(z)
return a
def evaluate(self, test_data):
test_results = []
for sample in test_data:
x = sample[1:]
y = sample[0]
test_results.append((np.argmax(self.feedforward(x)), y))
return sum(int(x == y) for (x, y) in test_results)
def backpropagation(self, x, y):
g_weights = [np.zeros(w.shape) for w in self.weights]
g_biases = [np.zeros(b.shape) for b in self.biases]
# feedforward inputs
zs = []
activ = x
activs = [activ]
for w,b in zip(self.weights, self.biases):
z = w @ activ + b
activ = self.non_linearity(z)
zs.append(z)
activs.append(activ)
# σ'(z[L])
sp = self.non_linearity_prime(zs[-1])
# δ[L] = ∇aC ⊙ σ'(z[L])
delta = self.cost_derivative(activs[-1], y)*sp
# get gradient of output biases
# ∇bC = 1*sj[l]
g_biases[-1] = delta
# get gradient of output weights
# ∇wC = ak[l-1]*sj[l]
g_weights[-1] = activs[-2]*delta.reshape(-1, 1)
# get gradient of hidden layers
for i in range(2, self.num_layers):
sp = self.non_linearity_prime(zs[-i])
# δ[l] = transpose(w[l+1])*(δ[l+1]) ⊙ σ'(z[l])
delta = (self.weights[-i+1].T @ delta)*sp
# ∇bC = 1*sj[l]
g_biases[-i] = delta
# ∇wC = ak[l-1]*sj[l]
g_weights[-i] = activs[-i-1] * delta.reshape(-1, 1)
return g_weights, g_biases
def update_mini_batch(self, mini_batch, eta):
g_weights = [np.zeros(w.shape) for w in self.weights]
g_biases = [np.zeros(b.shape) for b in self.biases]
# compute batch gradient
for data in mini_batch:
x = data[1:]
y = [1 if data[0]==i else 0 for i in range(10)]
delta_w, delta_b = self.backpropagation(x, y)
g_weights = [g+d for g, d in zip(g_weights, delta_w)]
g_biases = [g+d for g, d in zip(g_biases, delta_b)]
# update weights
self.weights = [w - (g/len(mini_batch))*eta for w, g in zip(self.weights, g_weights)]
self.biases = [b - (g/len(mini_batch))*eta for b, g in zip(self.biases, g_biases)]
# Stochastic gradient descent
def sgd(self, training_data, epochs, mini_batch_size, eta, test_data=None):
rng = np.random.default_rng()
rng.shuffle(training_data)
if test_data.any(): n_test = len(test_data)
for j in range(epochs):
for i in range(0, len(training_data), mini_batch_size):
self.update_mini_batch(training_data[i:i+mini_batch_size], eta)
if test_data.any():
print(f"Epoch {j+1} accuracy: {self.evaluate(test_data)} / {n_test}")
else:
print(f"Epoch {j+1} complete")
eta *= 0.1
In [16]:
import copy
net = Network([784, 15, 10])
net.sgd(training_data=training_data, epochs=3, mini_batch_size=1, eta=0.1, test_data=test_data)
Epoch 1 accuracy: 8757 / 10000 Epoch 2 accuracy: 8911 / 10000 Epoch 3 accuracy: 8936 / 10000
Here you can test the trained network
In [17]:
from IPython.display import display, Image
from PIL import Image as PIL_Image
import numpy as np
test_data = np.array(readcsv("/content/sample_data/mnist_test.csv"), dtype=float)
In [18]:
import matplotlib.pyplot as plt
test_img = np.array(random.choice(test_data))
test_norm = normalize(test_img)[1:]
prediction = net.feedforward(test_norm)
prediction = max(range(len(prediction)), key=prediction.__getitem__)
print(f"Prediction {prediction}")
test_img = test_img[1:].astype(np.uint8)
test_img.shape = (28,28)
fig, axs = plt.subplots()
axs.imshow(test_img)
plt.show()
Prediction 4