code: Ayush0054/micrograd
what is a derivative ?
a derivative tells us how much a function's output changes when we nudge its input by a very small amount .
where is a very small change in the input.
Example
def f(x):
return 3*x**2 - 4*x + 5
h = 0.001
x = 3.0
print((f(x + h) - f(x)) / h) # 14.00300000000243
so at , if we nudge up a little, goes up about 14 times that amount.
what is partial derivative ?
a partial derivative is the derivative of a multivariable function with respect to one specific variable, while others are held constant
Example with 3 variables
h = 0.0001
a, b, c = 2.0, -3.0, 10.0
d1 = a*b + c
d2 = (a + h)*b + c # increase only a, keep b and c fixed
print((d2 - d1) / h) # -3.000000000010772
each input gets its own derivative, and that's exactly what .grad stores for every Value in micrograd.
Lets build Micrograd
Implementing the Value object
a Value holds its data, its gradient and a backward function.
code: base.py
class Value:
def __init__(self, data, _children=(), _op='', label=''):
self.data = data
self.grad = 0.0
self._backward = lambda: None # by default this func doesnt do anything
self._prev = set(_children)
self._op = _op
self.label = label
def __repr__(self):
return f"Value(data={self.data})"
# mathematical operation functions
def __add__(self, other):
other = other if isinstance(other, Value) else Value(other)
out = Value(self.data + other.data, (self, other), '+')
# to update the gradients of the two input objects when backpropagation happens.
def _backward():
self.grad += 1.0 * out.grad
other.grad += 1.0 * out.grad
out._backward = _backward
return out
def __radd__(self, other): # other + self
return self + other
def __mul__(self, other):
other = other if isinstance(other, Value) else Value(other)
out = Value(self.data * other.data, (self, other), '*')
def _backward():
self.grad += other.data * out.grad
other.grad += self.data * out.grad
out._backward = _backward
return out
def __pow__(self, other):
assert isinstance(other, (int, float)), "only supporting int/float powers for now"
out = Value(self.data**other, (self,), f'**{other}')
def _backward():
self.grad += other * (self.data ** (other - 1)) * out.grad
out._backward = _backward
return out
def __rmul__(self, other): # other * self
return self * other
def __truediv__(self, other): # self / other
return self * other**-1
def __neg__(self): # -self
return self * -1
def __sub__(self, other): # self - other
return self + (-other)
def tanh(self):
x = self.data
t = (math.exp(2*x) - 1) / (math.exp(2*x) + 1)
out = Value(t, (self,), 'tanh')
def _backward():
self.grad += (1 - t**2) * out.grad
out._backward = _backward
return out
def exp(self):
x = self.data
out = Value(math.exp(x), (self,), 'exp')
def _backward():
self.grad += out.data * out.grad
out._backward = _backward
return out
# backpropagation calling function
def backward(self):
topo = []
visited = set()
def build_topo(v):
if v not in visited:
visited.add(v)
for child in v._prev:
build_topo(child)
topo.append(v)
build_topo(self)
self.grad = 1.0
for node in reversed(topo):
node._backward()
Value class initialises:
datagrad(initially0.0)_backwardfunction (by default empty function)_prevholds the values that this value is created through, when we call any operation like add using two values. fora + b = c,c._prev = {a, b}. it is used bybackward()to trace the nodes on which we need to update gradients
we have implemented mathematical operation for addition, multiplication and other various operators used in micrograd and with each operator method we have also implemented backward function to calculate gradients of it, basically backward functionality is just that function partial derivatives
you can checkout derivative rules for each operation/method here
lets understand this with an example
a = Value(2.0, label='a')
b = Value(-3.0, label='b')
c = Value(10.0, label='c')
e = a*b; e.label = 'e'
d = e + c; d.label = 'd'
f = Value(-2.0, label='f')
L = d * f; L.label = 'L'
value is , see the graph
now lets calculate derivative wrt , as per rules will be
and that's why we update gradient with manually, and when doing backpropagation we initialise grad to
now lets calculate derivative wrt , as per rules it will be
since
now for derivative wrt will be
d.grad = -2.0
f.grad = 4.0
now for derivative wrt (using chain rule)
similarly for derivative wrt
c.grad = -2.0
e.grad = -2.0
now for derivative wrt
similarly for
b.grad = -4.0
a.grad = 6.0
in this example i updated gradients manually, instead of that we will use backward() (backpropagation) function which will sort the expression in topological order and from output it will call _backward() function for each node.
one more thing, we have a tanh function here which is an activation function used in neural network setting, which we will use in next step
neural networks
neural networks are just a specific class of mathematical expressions.
one neuron
a neuron takes inputs, each with its own weight, plus a bias (trigger happiness). it computes and passes the result through an activation function ().
lets write a Neuron class (neural_network.py):
class Neuron:
def __init__(self, nin):
self.w = [Value(random.uniform(-1, 1)) for _ in range(nin)]
self.b = Value(random.uniform(-1, 1))
def __call__(self, x):
# w * x + b (forward pass)
act = sum((wi * xi for wi, xi in zip(self.w, x)), self.b)
out = act.tanh()
return out
def parameters(self):
return self.w + [self.b]
it takes the number of inputs and initialises a random weight for each input, plus one bias. when called, it multiplies each input by its weight, sums them up with the bias, and passes the result through the activation function to get the output.
one layer
a layer is just a list of neurons, all looking at the same inputs (neural_network.py).
class Layer:
def __init__(self, nin, nout):
self.neurons = [Neuron(nin) for _ in range(nout)]
def __call__(self, x):
outs = [n(x) for n in self.neurons]
return outs[0] if len(outs) == 1 else outs
def parameters(self):
return [p for neuron in self.neurons for p in neuron.parameters()]
it takes the number of inputs and the number of outputs, and creates one neuron per output.
x = [2.0, 3.0]
n = Layer(2, 3)
n(x)
# [Value(data=-0.9669850169537446), Value(data=0.6958752842093446), Value(data=0.6487042565405848)]
# 3 outputs, one per neuron
multi-layer perceptron
an MLP is layers of neurons, where the output of one layer is the input to the next (neural_network.py).
class MLP:
def __init__(self, nin, nouts):
sz = [nin] + nouts
self.layers = [Layer(sz[i], sz[i + 1]) for i in range(len(nouts))]
def __call__(self, x):
for layer in self.layers:
x = layer(x)
return x
def parameters(self):
return [p for layer in self.layers for p in layer.parameters()]
x = [2.0, 3.0, -1.0] # check tinydatasets.py for the whole dataset
n = MLP(3, [4, 4, 1]) # 3 inputs, two hidden layers of 4, one output
print(n(x))
it takes no of inputs and list of sizes of layers which we want
we take size list after adding inputs and sizes of layers iterate over consecutive pair of the size and create layer object on them
and for each layer call them sequentially
example: a binary classifier
lets use the network to predict targets for a tiny dataset (tinydatasets.py).
# 4 possible inputs
xs = [
[2.0, 3.0, -1.0],
[3.0, -1.0, 0.5],
[0.5, 1.0, 1.0],
[1.0, 1.0, -1.0],
]
# their desired targets
ys = [1.0, -1.0, -1.0, 1.0]
ok, lets use the same neural network and predict the targets:
ypred = [n(x) for x in xs]
print(ypred)
# [Value(data=-0.8443431044236114), Value(data=0.09848708066320733), Value(data=-0.6971375106656454), Value(data=-0.7200555014821302)]
the outputs are nowhere near the desired targets.
calculating the loss
to get closer to the targets we need a single number that measures how wrong we are: the loss. the lower the loss, the better the predictions.
there are various ways to calculate the loss (e.g. cross entropy loss), but we're going with mean squared error:
where:
- is the actual value
- is the predicted value
- is the number of samples
loss = sum((yout - ygt) ** 2 for ygt, yout in zip(ys, ypred))
print(loss)
# Value(data=4.107026055050601)
the code skips the , so it's technically the sum of squared errors. dividing by a constant doesn't change where the minimum is, it only scales the gradients, and the learning rate absorbs that.
backpropagation
lets call loss.backward() to compute the gradients:
loss.backward()
print(n.layers[0].neurons[0].w[0].grad) # 2.989879321904987
print(n.layers[0].neurons[0].w[0].data) # 0.10671793848059208
the gradient is positive, which means increasing this weight would increase the loss. so to decrease the loss we nudge the weight in the opposite direction of its gradient. this is gradient descent.
updating the weights
for p in n.parameters():
p.data += -0.1 * p.grad # 0.1 is the step size, also called the learning rate
now lets predict again:
ypred = [n(x) for x in xs]
print(ypred)
# [Value(data=0.09303581963460031), Value(data=-0.7099192463892277), Value(data=-0.3993733906561606), Value(data=0.5070539608978654)]
we're a bit closer to the targets than before.
the training loop
to improve it more, lets wrap all of this in a training loop (tinydatasets.py):
for k in range(20):
# forward pass
ypred = [n(x) for x in xs]
loss = sum((yout - ygt) ** 2 for ygt, yout in zip(ys, ypred))
# backward pass
for p in n.parameters():
p.grad = 0.0 # reset gradients before every backward pass
loss.backward()
# update
for p in n.parameters():
p.data += -0.1 * p.grad
print(k, loss.data)
print(ypred)
# [Value(data=0.9372725055000084), Value(data=-0.9574271675817998), Value(data=-0.8977543702779872), Value(data=0.9185636209937591)]
resetting
p.grad = 0.0is very important.backward()adds to the gradients, so without the reset they keep piling up across iterations and the updates go wrong.
after 20 iterations the predictions are very close to the targets [1.0, -1.0, -1.0, 1.0].
Lets take another example (binary classification) : here we have to identify which dot is blue and which dot is red
condition for blue -> y = -1 condition for red -> y = +1
x is the input and its position is x1 , x2 x1 and x2 position decide if point is blue or red
we use make_moon function from scikit learn library
we will have 2 layer neural network
here in the loss function we also need to penalize the weight since we want to test this neural network on new dataset unlike previously we trained nn around predicting specific output. this is known as L2 regularisation
Agent summary :
On the tiny dataset the goal was to fit the given targets. On make moons the goal is to predict correctly on new points (generalization). Fitting the training data perfectly doesn’t guarantee that, because the model can also fit the noise. L2 regularization reduces this by keeping weights small, which keeps the decision boundary smooth.
import random
import numpy as np
import matplotlib.pyplot as plt
from base import Value
from neural_network import Neuron, Layer, MLP
from sklearn.datasets import make_moons, make_blobs
np.random.seed(1337)
# generate the dataset: X is (100, 2) points, y is 0 or 1
X, y = make_moons(n_samples=100, noise=0.1)
y = y * 2 - 1 # make y be -1 or 1 (for the SVM-style max-margin loss)
# visualize in 2D
plt.figure(figsize=(5, 5))
plt.scatter(X[:, 0], X[:, 1], c=y, s=20, cmap='jet')
# plt.title("make_moons")
# plt.show()
model = MLP(2, [19, 19, 1]) # 2-layer neural network
# loss function
def loss(batch_size=None):
# inline DataLoader
if batch_size is None:
Xb, yb = X, y
else:
ri = np.random.permutation(X.shape[0])[:batch_size]
Xb, yb = X[ri], y[ri]
inputs = [list(map(Value, xrow)) for xrow in Xb]
# forward the model to get scores
scores = list(map(model, inputs))
# svm "max-margin" loss
losses = [(1 + -yi*scorei).relu() for yi, scorei in zip(yb, scores)]
data_loss = sum(losses) * (1.0 / len(losses))
# L2 regularization
alpha = 1e-4
reg_loss = alpha * sum((p*p for p in model.parameters()))
total_loss = data_loss + reg_loss
# also get accuracy
accuracy = [(yi > 0) == (scorei.data > 0) for yi, scorei in zip(yb, scores)]
return total_loss, sum(accuracy) / len(accuracy)
total_loss, acc = loss()
print(total_loss, acc)
# optimization
for k in range(100):
# forward
total_loss, acc = loss()
# backward
for p in model.parameters():
p.grad = 0.0
total_loss.backward()
# update (sgd)
learning_rate = 1.0 - 0.9*k/100
for p in model.parameters():
p.data -= learning_rate * p.grad
if k % 1 == 0:
print(f"step {k} loss {total_loss.data}, accuracy {acc*100}%")
# visualize decision boundary
h = 0.25
x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1
xx, yy = np.meshgrid(np.arange(x_min, x_max, h),
np.arange(y_min, y_max, h))
Xmesh = np.c_[xx.ravel(), yy.ravel()]
inputs = [list(map(Value, xrow)) for xrow in Xmesh]
scores = list(map(model, inputs))
Z = np.array([s.data > 0 for s in scores])
Z = Z.reshape(xx.shape)
fig = plt.figure()
plt.contourf(xx, yy, Z, cmap=plt.cm.Spectral, alpha=0.8)
plt.scatter(X[:, 0], X[:, 1], c=y, s=40, cmap=plt.cm.Spectral)
plt.xlim(xx.min(), xx.max())
plt.ylim(yy.min(), yy.max())
plt.title("make_moons_output")
plt.show()
