Intro to ML - Getting Started
Machine learning - Getting Started
With lot of tsoding’s tutorial of ML in C.
Machine learning is just the method finding a solution to a problem by tweaking the initial solution step by step.
I donno if that makes any sense so here’s a workflow,
This a kind of abstract view of stuff happening but this is the essence of ML we just “learn” from our previous mistakes.
Hands On Deck
Let’s see how we can code it out , there will be explanations along the way so its alright
Let’s set up data first,
def f ( x ):
return x*2
x = [1,2,3,4,5,6,7,8,9,10]
Here is a simple function which doubles the input.
And the input is a list of numbers from 1 to 10.
y = [ f(o) for o in x ]
and target is the output of the function for each input .
ie. y = [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
I may use the words like “target” and “output” interchangeably. Its all the same stuff.
In the end if everything goes well our model should predict the correct for a given .
To make a model we need to have,
- Data
- Architecture
- Loss function
- Optimizer
Like the diagram the model should start by setting some variables named w (weight) & b (bias).
”Why ?” u ask ?
Cause the input data , when used with the corect cofiguration of and should give us the correct output.
Just think of it as a simple radio tower from spiderman remastered, or hacking comms in batman arkham origins,
The weight is like the left dial and bias is the one on the right. The correct configuration of these two should give us the correct output.
In the game you do it yourself but in ML the computer does it for you.
Yeah, you have been making AI models all along, just didn’t know it.
Now that weve established we can use the correct combination of w and b to get the correct output, we can say that this is literally the “goal” of AI model.
Th equation / hypothesis for the model is given by,
Like in the architecture from the diagram we need to start from a random value of and and then tweak it to get the correct output.
The whole thing raises a bnch of questions,
- How does the model know which way to tweak the values ?
- How do we know if the output is correct ?
- Does the algorithm work for all problems ?
How does the model know which way to tweak the values ?
Keep in mind that the ML training is iterative (Brute forcing done gracefully), we start with a random weight and bias and nudge it with little changes until we get to the target values.
- We start with random weight and bias,
weight = random.random()*10
bias = 0
Just like the equation weight is a coefficient of input value and then a bias is added to it.
Forget about bias for a second. Just look at what we are trying to do, we are trying to remake the
f(x)functionand
f(x) = y =. Intuitively we can say that the weight should be 2 if everything goes well.
Applying we get,
prediction = (x*w) + b
How does the model know which way to tweak the values ? : Part 1
Loss Function / Error
Now we have our initial weights and biases let’s check how stupid our model is by having it predict an output and measuring the Error of our model.
To know how stupid our model is we use a Loss Function.
It is just essentially the difference,
(The answer that we want) - (Answer that we got)
y - y_prediction
But in this case if out model exceed our expectations and go beyond 2 we will have a negative loss. So let’s just square the whole value.
loss = (y - prediction)**2
Now there wont be any negative values even if our model predicts value greater than 2.
We could use this for measuring how wrong a single prediction is,
But our model should “fit” all the data. So we need to calculate the average of all the errors.
def MSELoss( weight, bias, target :list = y ):
total_loss = 0 # sum of all losses
prediction = [ (o*weight) + bias for o in x ]
for y, y_pred in zip(target , prediction):
total_loss+=(y - y_pred)**2
return total_loss/len(target) # avg = sum/n
Btw the eqn is called Mean Squared Error.
Also we could have taken the absolute value of the difference but squaring it gives a better representation of the error. The more wrong our model is the error becomes exponetially higher.
The workflow,
- Start with random weight and bias ✔️
- Predict the output as list of predictions ✔️
- Pass it to our loss function to get the error ✔️
- Tweak the weight and bias to reduce the error
How does the model know which way to tweak the values ? : Part 2
Gradients
A gradient simply measures the change in all weights with regard to the change in error. You can also think of a gradient as the slope of a function. The higher the gradient, the steeper the slope and the faster a model can learn. But if the slope is zero, the model stops learning.
The gradient in this example just gives us the slope of the loss function.
weight, bias -> gradient function -> how much to change weight and bias
The slope is basically,
(rise over run) or or now ->
derivative of a function can be found by,
The is a very small change eg: like 0.0001, 1e-6 etc.
As you can see what hapens in the function is exactly the same as fdinding rise over run.
This is not actually the derivative but the limit of the derivative as approaches 0.
It is called the finite difference method.
Anyways in this case we are just trying to find the slope of the loss function. and It is enough
def derivative(w: float, b: float):
h = 1e-3 # very small change
der_w=(MSELoss(w + h, b) - MSELoss(w,b) )/h # change in loss wrt weight
der_b=(MSELoss(w, b + h) - MSELoss(w,b) )/h # change in loss wrt bias
return der_w, der_b
now we have the slope of the loss function wrt weight and bias.
The slope gives us the steepest ascent. So to reduce the error we have to go in the opposite direction. So we subtract the slope from the weight and bias.
der_w, der_b = derivative( weight, bias )
weight = weight - der_w
bias = bias - der_b
Thats it !
The rest of the stuff is just repeating the process until the error is minimized.
Introducing to you the Epochs. It is just the number of times we repeat the process.
epochs = 50
for epoch in range(epochs):
loss = MSELoss( weight, bias)
der_w, der_b = derivative( weight, bias )
weight = weight - der_w
bias = bias - der_b
print(f'Epoch: {epoch}, Loss: {loss}, Weight: {weight}, Bias: {bias}')
As you can see in each epoch the loss is reduced and the weight and bias are updated.
The model is learning.
Now we can see that the loss is reduced is based on the derivative of the loss function wrt weight and bias.
Can we improve it ?
Yep.
This calls for a new concept called Learning Rate.
The learning rate is a variable which be tweaked to decide how “fast” you want your model to learn.
The variable is just multiplied to the “gradient” or derivative of the loss function.
epochs = 50
lr = 0.01
for epoch in range(epochs):
loss = MSELoss( weight, bias)
der_w, der_b = derivative( weight, bias )
weight = weight - lr * der_w
bias = bias - lr * der_b
print(f'Epoch: {epoch}, Loss: {loss}, Weight: {weight}, Bias: {bias} der_w: {der_w}, der_b: {der_b}')
The variables like learning rate, epochs are called Hyperparameters. We as developers set em.
Final code
import random
def f ( x ):
return x*2
x = [1,2,3,4,5,6,7,8,9,10]
y=[f(i) for i in x]
weight = random.random()*10
bias=0
def MSELoss( weight, bias, target :list = y ):
total_loss = 0 # sum of all losses
prediction = [ (o*weight) + bias for o in x ]
for y, y_pred in zip(target , prediction):
total_loss+=(y - y_pred)**2
return total_loss/len(target) # avg = sum/n
def derivative(w: float, b: float):
h = 1e-3 # very small change
der_w=(MSELoss(w + h, b) - MSELoss(w,b) )/h # change in loss wrt weight
der_b=(MSELoss(w, b + h) - MSELoss(w,b) )/h # change in loss wrt bias
return der_w, der_b
epochs = 50
lr = 0.01
for epoch in range(epochs):
loss = MSELoss( weight, bias)
der_w, der_b = derivative( weight, bias )
weight = weight - lr * der_w
bias = bias - lr * der_b
print(f'Epoch: {epoch}, Loss: {loss}, Weight: {weight}, Bias: {bias} ')
Output :
Epoch: 0, Loss: 68.83110457103848, Weight: 2.3075278158612686, Bias: -0.14708046192879462
Epoch: 1, Loss: 3.1651622617835633, Weight: 2.0869063984596234, Bias: -0.17796701243355526
Epoch: 2, Loss: 0.15232086505619233, Weight: 2.039560993013165, Bias: -0.18396747601520655
......
Epoch: 8, Loss: 0.007094484142969567, Weight: 2.0260212718297117, Bias: -0.18118087279023454
Epoch: 9, Loss: 0.007034988135597209, Weight: 2.0259109385277596, Bias: -0.18041969523581441
As you can see our model tries to get weights as close to 2 as possible and the bias as close to 0 as possible.
Now you can tweak the learning rate and epochs to see how the model behaves.
Alright then that’s it for the intro to ML.
In the next post we wil see how to make the model make an OR gate from scratch.
Note : Try rewriting the code in you own way. It will help you understand the concepts better.