Understanding the method behind the magic from the ground - up
By Arya Dharod3 Apr 2023
What gave you that awesome Netflix movie recommendation last night? What helps drive Waymo’s self-driving cars? What personalises your feed on Instagram, Facebook, YouTube and Twitter? What technology do you think powers your virtual assistants at home – your Alexa, Bixby, and Siri?
That’s right.
Artificial intelligence.
The buzzword of 2023.
A lot of us looove throwing around fancy jargon like ‘neural networks’, ‘weights’ and ‘biases’ when trying to impress a less technical friend with our knowledge of Machine Learning.
But how many of us understand how Artificial Intelligence and Machine Learning work as technologies, at their very core (yes, including the messy math behind the entire thing). I for one didn’t until a few weeks ago, so I’m guessing many of you reading this article are in a similar position.
My intention for you by the end of this article is:
· To have enough knowledge of the technical concepts and processes that drive Artificial Intelligence and Machine Learning, to actually know what you are talking about when you casually throw around jargon like ‘supervised and unsupervised learning’, ‘convolutional neural networks’ and ‘deep learning’.
In this article I aim to cover:
· Supervised and unsupervised learning
· Neural networks
· Natural language processing
· Reinforcement learning
· Convolutional and recurrent neural networks
· Data Science and its connection to ML
· The power of AI – Real world applications
So get yourself a biscuit, apple, coffee, whatever, because this isn’t the shortest article out there.
The 7 steps of machine learning
I want to start off simple by breaking down the 7 steps of machine learning, as explained beautifully by Yufeng Guo, a Machine Learning Expert at Google. The example we will work with is segregating between images of a lion and a tiger. Let’s assume we are differentiating then on the basis of just colour – a lion’s skin is yellowish, light brown colour whereas a tiger’s skin is orange with black stripes. In AI jargon, the skin colour here becomes the ‘feature’ which we use to train our model.
· Step 1: Gathering data.
Here our intention is to collect data which is varied and accurate. The quality of data we collect for training our model directly impacts the quality of our model’s prediction. Similar to how the quality of raw materials impacts the quality of the finished product.
So we collect images of lions and tigers (standing, sleeping, side angle, front angle – variety is key!) along with their exact skin colour value, as measured by say, an RGB value. Next, we ourselves manually classify the different images as either lions or tigers – our manual classifications will later be used in Step 4, when we begin training the model and giving the model feedback on whether its prediction matches with our answer.
· Step 2: Data preparation.
We must now segregate the data into 2 parts: ‘Training data’ and ‘Testing data’. We use most of these images to train the model (training data), but we need to save the last few images for testing how accurate our model is when it views an unseen image (testing data). A good ratio to follow for training data: testing data is 70:30 or 80:20.
· Step 3: Choosing an appropriate model
There are many different types of AI models, some of which are better at classifying images, others at understanding audio, others at understanding text. For our case, we would most likely choose a Convolutional neural network (more on this later) because it is a great model for classifying images.
· Step 4: Training the model.
This is the meat of machine learning. We give our model image after image and show the model what the right answer is: In our case, whether the image is a lion or a tiger. As time goes on, the model will learn to identify certain key patterns or characteristics in an image that tells whether the given animal is a lion or tiger. For example, ‘Look – the tiger’s skin colour is always orange with black stripes while a lion has no stripes on its skin’.
· Step 5: Evaluation
We now test our model, trial after trial, checking how accurate the model is in classifying lions and tigers. Like a strict math teacher, we assess our model’s performance during every trial, tell the model what images it got wrong along with its overall performance %, and then make the model run another trial to see whether its accuracy improves.
And so the model improves, trial after slow trial, much like a toddler learning how to walk. In the beginning the model may be doing nothing more than randomly classifying the given images into lions and tigers but over time, with feedback and iteration, its percentage improves and its get better with its classifications on every trial, eventually reaching a point of super high accuracy.
· Step 6: Parameter tuning
Now the model is highly accurate with its classification, maybe 90 – 95% of the time. But we, the model’s creator, are stubborn and want the model to be right 100% (or at least 99.99%) of the time. This is the stage where we tune certain ‘parameters’ in our model. We’ll talk more about parameters when we get to weights and biases but for now, just know that parameters are certain key features/conditions we set the model up with, which directly affects the model’s accuracy. For example, when taking a basketball shot we may want to tune certain parameters like the height of our jump, position of our elbow, how much we bend our knees, in order to improve the accuracy of our shots.
The bottom line is by tuning these parameters after testing our model, we can slowly increase the model’s accuracy from 90% all the way to nearly 100% (because there will always be certain super confusing images that your model just cannot classify correctly).
· Step 7: Prediction.
All our hard work pays off in this step. Now it’s time to take our model to school or to our parents/siblings and demonstrate our skills. We input random, unseen images of lions and tigers and the model predicts and classifies the images correctly, nearly all the time. Hooray!
I hope everything makes sense so far. Let’s dive into some deeper topics to really understand the technicalities behind AI and ML.
Supervised and unsupervised learning
These are the 2 major models/processes which we use to train any ML model. The example I will use throughout this explanation is of a list of numbers from 1 to 100.
Supervised learning
In supervised learning, we generally have a fixed, clearly defined purpose or intention for the ML model. In this case, let’s say we want the model to sort numbers into odd and even. In supervised learning, it is a pre-requisite to have some already labelled data. In our case, this could mean we have already labelled the numbers from 1 to 50 as either an odd or even number. This data has become our training data.
Now we begin training the model. We ask it to sort the numbers from 1 to 50 into odd and even numbers. The model complies and sorts the numbers from 1 to 50 into odd and even numbers pretty well, but with a few mistakes. We point out the mistakes to the model, for example ‘Model, you classified 5 as an even number whereas 5 is actually an odd number’. The model keeps this feedback in mind and gets better and better, trial after trial.
Eventually we can show the model some unseen, unlabelled data like the numbers from 50-100 in our case, with the hope that the model will now be trained well enough to separate these numbers too into odd and even numbers, with high accuracy.
Advantages of supervised learning:
· Models can become highly accurate if given enough labelled data to train with
· Accuracy improves over time, trial after trial because of ‘back propagation’. Back propagation is basically the feedback we give to the model after every trial which helps the model gain more and more accuracy over time (more on back propagation later).
Limitations of supervised learning:
· Cannot work without huge quantities of labelled data which are not always available
· What if the labels of the data themselves are faulty? Will this reduce the accuracy of our model? (PS. Of course it will!).
· Leads to Over-fitting. The model has been trained to give its answers with high levels of certainty, making it so brittle that it may not serve our purpose anymore. For example, if we gave the model a negative number which it has no idea how to classify, the model could break or worse, just classify the negative number randomly into an arbitrary group with high levels of certainty. This may not seem like a huge issue with a simple model like this, but what if AI models in self – driving cars or nuclear missiles overfit the data, and show high levels of certainty for an inaccurate answer?
Unsupervised learning
Unsupervised learning involves no labelled data, and usually our intention/purpose for using unsupervised learning is just to classify the data into multiple groups with similar characteristics. This can be used by businesses for example to identify hidden patterns or trends in consumer behaviour like say, ‘Customers who bought Product A had an 80% probability of buying Product B’. The model is completely based on grouping similar data items close together and contrasting data items far away.
In our case, maybe our model groups data into odd and even numbers – this is one possibility. But the model could also group numbers into prime numbers and others, square numbers and others, single digit and double digit numbers, etc. The model could even do more fascinating groupings like grouping numbers into perfect numbers and others.
PS. A perfect number is a number that is equal to the sum of its divisors. For example, 28 is a perfect number because the sum of its divisors is 28. 1+2+4+7+14=28.
Pros:
· The best option when there is no labelled data
· No ‘Over-fitting’ problem like in supervised learning. The model would probably just put the negative number closer to 0 and far away from 100, in our case.
· Great for identifying hidden trends and patterns in data, and more generally, sorting through large quantities of unsorted, messy data
Cons:
· Not as powerful as supervised learning because there is no clear intent/purpose other than classifying the data into multiple similar groups.
· Tough to know whether a solution is good or bad. In our case, is a solution with prime and non-prime numbers good or bad? We really don’t know because the model has no clear purpose with the data, other than sorting it based on a characteristics of its own choice.
Semi supervised learning
Semi supervised learning is the ‘best of both worlds’, taking the strengths of both supervised and unsupervised learning together, so that they can complement each other. Semi supervised learning involves a data set where we have a few labels, which aren’t enough for a supervised learning approach, but would allow us to get a fairly clear idea of the intent/purpose behind the module, and how our model should classify data items into groups. There is no over-fitting because the model is also free to group the data items based on certain characteristics, of its own discretion.
Semi supervised learning is the future. Data sets are getting larger and larger and humans won’t have time to label all the data items. So we call in the experts, ask them to label just a few data items based on their expertise, and let our ML models do the rest. The experts can then come back in to check a model’s classification of the data items, and give the model feedback, to further improve accuracy next time. Essentially, the model does most of the heavy lifting and the human experts just come in briefly to ensure that the model is on the right track.
Neural networks
Neural network. Does the name sound familiar? Biology, psychology, neuroscience students? Neural networks are the incredibly complex connections between the millions of neurons in the human brain, which transmit signals through electrical impulses, and are responsible for all our cognitive activities like learning, reading, walking, and memorizing random dates for that annoying history test next week. So what is the term ‘neural network’ doing in an article about AI?
Well, like in every other case, humanity’s scientific and technological breakthroughs are nothing more than an inspiration and replication of nature’s creations. AI models use neural networks, inspired by the neural networks inside the human brain, in order to learn specific tasks and improve their accuracy over time.
Neural networks have one job: to learn how to turn inputs into desired outputs. For this section, I will take the example of converting input factors like age, education, gender, profession to predict an individual’s future salary.
The variables of age, education, gender, profession, etc. become the input layer of the neural network, which we feed into the network, in the form of input ‘nodes’. The outputted future salary predicted by the network will also be in the form of a single node. Now the question is:How do we get from our multiple input nodes like age, gender, profession, current salary, etc. to our output node of predicted future salary?
This is where our hidden layers of the network come in, between the input and output node. This is where all the complex calculations take place to convert our input variables into the final predicted salary. It can be difficult to grasp what really goes in these hidden layers as this will differ from network to network. Let me try to explain one possible example using our salary predictor network.
For example, the network may combine the 2 input nodes of age and education, saying to hidden layer #1 that an individual aged below 30 combined with an Ivy League education results in a higher probability of increased future salary. Then in hidden layer #2 this higher probability may be combined with gender to indicate that perhaps females will earn 20% less than males in a specific field, say, software engineering or marketing. Through multiple hidden layers each performing complex calculations, we finally receive our outputted predicted future salary.
Time to define the term: ‘Activation function’. This is similar to the concept of ‘action potential’ in the brain’s neural network, where the next neuron will only be triggered if the previous neuron crosses a certain threshold of activation (measured by the electrical impulse). It works the same way in our ML model. Only if the previous node crosses a certain minimum threshold of activation, only then will the node in the next layer of the network activate and pass on the intended message to the next layer of the network.
Nowadays, even the individuals who program the neural network have only a vague idea of the calculations the network is actually performing in its hidden layers, often referred to as a ‘black box’. Obviously, this is extremely problematic. When our network starts predicting random future salaries like Bob making 10x his salary within the next 3 months, we (the ML engineers who created the model) have no idea what mistake the network is making, and hence, we don’t know how to correct the flaw.
Parameter tuning
Once the network has gone through a few trials, we probably realise that its accuracy can be improved by fine – tuning certain parameters. ‘Parameters’ are essentially the different variables in our AL model which can be adjusted to change the output our model gives us. The 2 most important parameters we will fine tune are ‘weights’ and ‘biases’.
To simplify this, let’s assume our ML model follows a liner regression and head back in time to some 8th grade math: The equation of a line.
X is the function’s input. Y is the function’s output. That leaves ‘m’ and ‘c’ as the values we can adjust in order to give the function a different output. M is the gradient/slope of the function, and c is the y-intercept. In Machine Learning, M becomes the model’s ‘weight’ and C becomes the model’s ‘bias’.
Our model may begin by randomly assigning a value to M and C, resulting in an output that is probably very inaccurate. But over time and training, we can compare our model’s output to the correct output and have the neural network adjust the value of the weights and biases, to produce an answer that is hopefully closer to the correct answer. Eventually our network will settle on the exact, correct value for the weights and biases, resulting in near 100% accuracy of the model’s predictions.
2 commonly used Machine Learning jargon are ‘gradient descent’ and ‘back propagation’. While I won’t go deep into these 2 terms, below are their high – level definitions.
· Gradient descent: It is an algorithm that helps the ML model identify the direction its next step should take in order to reach the minimum of the function, aka. solving the optimization problem. The minimum of a function is usually the best possible output, for example the maximum returns with the lowest possible investment.
· Back propagation: It is an algorithm designed to find and refine errors in an ML model, by going backwards from the model’s output, through the hidden layers, and finally to the input, fine – tuning the model’s weights, biases and other parameters along the way, in order to improve accuracy of the model’s predictions.
You will hear the term ‘Deep learning’ come up in a lot of AI/ML conversations. Deep learning is a sub-branch of Machine learning that just involves more complex neural networks, with greater number of hidden layers, used to make better predictions/ recommendations, due to its complex nature. Deep learning is great when huge datasets are available to train a model, however when training data is limited, ML is a more feasible option.
Natural language processing
E-mail filters, search engines, your smart assistants like Alexa, Siri and Bixby, chatbots, customer support automation, language translators – That’s ‘Natural language processing’ running its magic in the real world.
Natural language processing (NLP) can be defined as the ability of computers to understand and produce meaningful text, just like a human being. NLP can be divided into 2 categories:
· Natural language understanding: Understanding and drawing meaning from language. This involves your search engine recommendations, and e-mail filters.
· Natural language generation: Being able to output meaningful language that human beings can understand. This involves your chatbots, smart assistants, or AI models that summarize entire documents for you in a mere paragraph.
In both cases, the key is to understand the meanings of different words, in different contexts. The ambiguous nature of human languages is due to the fact that the same word can be used in 2 completely different contexts, with 2 completely different meanings – this is what makes it so difficult to train machines with NLP. For example, the word plane could either mean aeroplane of the mathematical plane, leaving it up to AI to understand which ‘plane’ it is, based on the sentence’s context.
Let’s break down the steps of NLP:
· Segmentation: We begin by finding an article or document we want our AI model to comprehend. The first task is then to break down the entire document into sub-sections, generally breaking the article/document down into single sentences.
· Tokenizing: We then break down a sentence into its individual words. We teach the model the meaning of each and every individual word in the sentence, while also removing less significant words in sentences like ‘the’, ‘was’, ‘in’, ‘and’ (connectors and prepositions), while focusing more on proper and common nouns in the sentence like car, basketball, bat, computer, etc. This makes the learning process faster.
Take the sentence ‘Cricket was invented in England’ as an example. The key words in the sentence here are ‘Cricket’, ‘invented’ and ‘England’ which the AI should focus upon, while it can play less attention to the words ‘was’ and ‘in’, as they don’t contribute significantly to the meaning of the entire sentence.
· Stemming: To further simplify things for our AI, we group words with the same base together, because they essentially have the same meaning. For example, ‘skip’, ‘skipping’, ‘skipped’, ‘skips’ all mean similar things, with slight differences in the suffix used. Hence, learning the meaning of just the word ‘skip’ will be enough for our AI model to recognize other forms of the same word in unseen sentences. This also makes the learning process hell a lot faster for our model.
· Part of speech tagging: It’s now time for our AI model to take a seat in 2nd grade English class and learn to differentiate between nouns, verbs, adjectives, pronouns, prepositions, and adverbs. This is of great help to the model’s accuracy because certain types of words only appear logically at one part of a sentence. For example, the sentence ‘Henry is running very _____’ will usually be followed by an adjective like fast, slow, clumsily, etc. but it would be illogical to place a noun, pronoun, preposition or another verb to finish this sentence.
· Named entity tagging: We now introduce our machine to pop culture references including specific slang, movies, books, significant personalities. For example, our machine should know that when an American says ‘That’s sick!’ he isn’t referring to ‘hospital sick’ rather he is trying to say, ‘That’s amazing/That’s crazy!’.
NLP takes time, effort and tons of language data because even we as humans struggle to understand the complexities of a new language, don’t we? But after sufficient training, our model will become accurate enough to be able to converse with human beings in manner natural enough that eventually talking to Siri/Alexa feels no different than talking to a dear friend.
Reinforcement learning
As children, we learn by doing, through a process of reinforcement based on reward and punishment. Stand on your feet without falling and we get applause and hugs from our parents (reward), which encourages us to perform this action more and more. Touch fire and our skin immediately burns (punishment) which encourages us to perform this action less. Through this constant cycle of action-feedback-learning, our brains automatically learn what is ‘right’ and ‘wrong’ in the environment we find ourselves in. This is a super effective and efficient way to train our ML models too.
Reinforcement learning involves an autonomous agent (our AI model, in this case) learning to navigate an uncertain environment (could be a road, a video game, a maze) with the goal of maximizing a numerical reward.
Let me explain Reinforcement Learning taking the simple example of an online tennis match. The goal of our AI model here is to win the match, which boils down to the basic level of winning a single point. Our AI model tries all kinds of experiments: it serves fast and slow, it hits the ball left and right, it tries volleys, smashes, forehand, backhand, all the possible moves in this online tennis match. Slowly through reinforcement the model learns which moves maximise its reward (the reward here is winning the point) and which moves lead to punishment (losing the point). Eventually, the model will learn that faster serves with top spin maximise the chance of winning the point, rather than slower serves with no top spin. Or the model learns to avoid hitting the ball straight back to the opponent, preferring instead to move the opponent around the court by hitting left and right, because that again maximises the possibility of winning the point. Eventually, after years of training, we have an extremely powerful model which can probably beat the world’s best online tennis player in a one-on-one match. This is what makes Reinforcement Learning so powerful as a training model – in certain cases, nothing works more effectively than the old carrot-and-stick approach.
Reinforcement learning has shown outstanding results in the past few years. Consider the recent example of the AI model that defeated Lee Sedol, the world’s top ranked player of AlphaGo, in a one-on-one AlphaGo match. The AlphaGo game requires the machine to take decisions in an uncertain environment during each and every move, but through practice, training and feedback, the model was able to achieve noteworthy success.
Convolutional and recurrent neural networks
These are the 2 most common types of neural networks, existing in the world today.
Convolutional neural networks:
These networks specialise in image recognition and image classification, because they are great with recognising visual patterns, like differentiating between straight lines, curves, circles, etc.
Consider the image above. It is a complex mixture of straight lines, curves, dots, waves and other visual patterns. The Convolutional neural network (CNN, for short) will be able to differentiate between the edges, lines, circles, etc. in an image to eventually make sense of the entire image as a whole, and maybe then, combined with NLP, the CNN can take an image as an input and output a tagline that accurately describes the picture, in this case perhaps ‘Modern coastal city at sunset’ or something similar.
Let’s dive a little deeper into how CNN’s work, using the example of recognizing hand-written digits. While it may be super simple for you to recognize the digits below as a 9, even this simple task of identifying hand-written digits requires a lot of training for our neural network.
Let’s take the hand-written digit 9. Our CNN would need to divide the entire box the image is located in into multiple pixels. Each pixel would be assigned a value between 0 to 1, with 0 standing for pitch black and 1 standing for white. In this way, the CNN would be able to differentiate between blank space and the white pixels that combine to form our hand-written digit 9.
So the above process is computed in the first hidden layer of the CNN. Now the second layer could be involved in differentiating between curves, edges, and straight lines of the number 9. In the image below, each tiny edge is denoted with a different colour. The CNN has now broken the digit 9 down into a pattern of edges.
Moving onto the third layer, now the CNN combines all these tiny edges to break the digit 9 into 2 parts: The circle on top and the line at the bottom.
Finally, in the output layer the CNN will be able to predict that the given hand-written digit is a 9, because of the circle on top and the single line extending down below. Or more accurately, the CNN will actually output a certain probability for each digit of the dataset. Let’s assume our dataset includes numbers from 0 to 10, the dataset would output the probability that the inputted hand-written digit is a 0,1,2….9 or 10.
For example, the network could output that there is a 0.012 probability that the given digit is a 4 because the structure of 4 is very different from 9. However, because the structure of 1 or 7 is more similar to 9, the network could output a 0.3 probability that the given digit is a 1 or 7. However, if our network is well – trained, the highest probability would definitely be that of the digit 9, say 0.7 or 0.8, and thus the network would output its prediction as the digit with the highest probability score, in our case, the digit 9.
CNN’s are all around you when you ask AI/ML models to classify images for you into cats and dogs, tigers and lions, or even in self-driving cars when the car is required to differentiate between a person and a lamppost. CNN’s are however limited only to images/visuals and have limited applications in other areas of Machine Learning, such as NLP.
Recurrent neural networks
These networks are great for sequential/contextual data, where the previous state directly affects the next state. For example, when writing a Harry Potter chapter or composing a musical piece, it is key that our AI model knows the sentence/note that came previously which will directly influence the sentence/note that comes next, in order to maintain a coherent flow. Thus our Recurrent Neural Network (RNN) will remember all its previous states and analysis up to the point where it creates a new state. Each and every layer in the neural network will thus receive its activation and input, along with ‘context’ – all prior states.
To draw a visualisation of this process in action, let’s start with the input layer. The output of the input layer now becomes the ‘context’ for the next layer. The output of this next layer now becomes the ‘context’ for the layer after that. So on and so forth, ensuring that the final output of the network is coherent and follows a logical flow, ensuring a logically flowing novel chapter or a sweet-sounding melody where each note builds on the previous one.
The major drawback with RNN’s is that because the network must remember all previous states at any given time, this becomes computationally expensive, requiring both high storage space and processing power. This becomes a huge limitation for the widespread adoption of RNN’s by the public, whereas CNN’s can be programmed by even the common man interested in building an ML model.
The power of AI to solve real – world problems
Whether we accept it or not, Artificial Intelligence will probably permeate all aspects and levels of our daily lives, in the years and decades to come. So we as innovators and leaders interested in solving the world’s biggest problems, might as well utilise the power of AI to help achieve our goals faster, cheaper and more effectively.
Here are just a few examples of AI in action solving real – world problems:
· AI in self – driving cars: Reducing car accidents significantly
· AI for quicker, more accurate disease diagnosis: Faster treatment, less severity of the disease, leading to less medical deaths
· AI optimizing traffic routes in a city: While the adjustments AI makes may be tiny – saving 3, 5, 10 minutes on a particular route, add up the saved time and that’s a HUGE reduction in annual CO2 vehicle emissions.
· AI to detect financial frauds by identifying anomalies in data: Could save the US government billions of dollars of tax money which it loses annually due to tax evasion
· Transforming e-learning through personalization leading to greater engagement: Apps like Duolingo and Khan academy are leading the way here, with the simple hypothesis that student engagement, retention and performance can be greatly enhanced by making the learning process more individualized.
· Improving athlete performance with real – time, personalized feedback: Could significantly reduce injury rates among professional athletes.
We’ve come to the end of this article, and I hope that I’ve accomplished my initial mission of giving you a deeper understanding into the underlying technicalities behind Artificial Intelligence and Machine Learning.
If this article helped you, please do 2 things before you close this tab: