Sunday, March 27, 2022

Difference between Epoch, Batch and Iterations

In neural nets, we have to specify the number of epochs while we train the model. 

One Epoch is defined as the complete forward & backward pass of the neural net over the complete training dataset. We need to remember that Gradient Descent is an iterative process and hence we need multiple passes (or epochs) to find the optimal solution. In each epoch, the weights and biases are updated. 

Batch size is the number of records in one batch. One Epoch may consist of multiple batches. The training dataset is split into batches because of memory space requirements. A large dataset cannot be fit into memory all at once. With increase in Batch size, required memory space increases. 

Iterations is the number of batches needed to complete one epoch. So if we have 2000 records and a batch size of 500, then we will need 4 iterations to complete one epoch. 

If the number of epochs are low, then it results in underfitting the data. As the number of epochs increases, more number of times the weight are changed in the neural network and the curve goes from underfitting to optimal to overfitting curve. Then how do we determine the optimal number of epochs?

It is done by splitting the training data into 2 subsets - a) 80% for training the neural net  b) 20% for validating the model after each epoch. The fundamental reason we split the dataset into a validation set is to prevent our model from overfitting. The model is trained on the training set, and, simultaneously, the model evaluation is performed on the validation set after every epoch.

Then we use something called as the "early stopping method"-  we essentially keep training the neural net for an arbitrary number of epochs and monitor the performance on the validation dataset after each epoch. When there is no sign of performance improvement on your validation dataset, you should stop training your network. This helps us arrive at the optimal number of epochs. 

A good explanation of these concepts is available here - https://www.v7labs.com/blog/train-validation-test-set. Found the below illustration really useful to understand the split of data between train/validate/test sets. 



Saturday, March 26, 2022

Ruminating on Convolutional Neural Networks

Convolutional Neural Nets (CNNs) have made Computer Vision a reality. But to understand CNNs, we need to get basics right - What exactly is a convolution? What is a kernel/filter?

The kernel or filter is a small matrix that is multiplied by the source image matrix to extract features. So you can have a kernel that identifies edges or corners of a photo. Then there could be kernels that detect patterns - e.g. eyes, stripes.

A convolution is a mathematical operation where a kernel (aka filter) moves across the input image and does a dot product of the kernel and the original image. This dot product is saved as a new matrix and is called as the feature map. An excellent video visualizing this operation is available here - https://youtu.be/pj9-rr1wDhM

Image manipulation software such as Photoshop also use kernels for effects such as 'blur background'. 

One fundamental advantage of the convolution operation is that if a particular filter is designed to detect a specific type of feature in the input, then applying that filter systematically across the entire input image allows us to discover that feature anywhere in the image. Also note that a particular convolutional layer can have multiple kernels/filters. So after the input layer (a single matrix), the convolutional layer (having 6 filters) will produce 6 output matrices. A cool application to visualize this is here - https://www.cs.ryerson.ca/~aharley/vis/conv/flat.html

A suite of tens or even hundreds of other small filters can be designed to detect other features in the image. After a convolutional layer, we also typically add a pooling layer. Pooling layers are used to downsize the features maps - keeping the important parts and discarding the rest. The output matrices of the pooling layer are smaller in size and faster to process. 

So as you can see, the fundamental difference between a densely connected layer and a convolutional layer is that dense fully connected layers learn global patterns (involving all pixels) whereas convolution layers learn local features (edges, corners, textures, etc.) 

Using CNNs, we can create a hierarchy of patterns - i.e. the second layer learns from the first layer. CNNs are also reusable, so we can take an image classification model trained on https://www.image-net.org/ dataset and add additional layers to customize it for our purpose. 

Friday, March 25, 2022

Ruminating on Activation Function

 Activation functions play an important role in neural nets. An activation function transforms the weighted sum of the input into an output from a node. 

Simply put, an activation function defines the output of a neuron given a set of inputs. It is called "activation" to mimic the working of a brain neuron. Our neurons get activated due to some stimulus. Similarly the activation function will decide which neurons in our neural net get activated. 

Each hidden layer of a neural net needs to be assigned an activation function. Even the output layer of a neural net would use an activation function. 

The ReLU (Rectified Linear Unit) function is the most common function used for activation. 

The ReLU function is a simple function: max(0.0, x). So essentially it takes the max of either 0 or x. Hence all negative values are ignored. 

Other activation functions are Sigmoid and Tanh. The sigmoid activation function generates an output value between 0 and 1. 

An excellent video explaining activation function is here - https://youtu.be/m0pIlLfpXWE

The activation functions that are typically used for the output layer are Linear, Sigmoid (Logistic) or Softmax. A good explanation of when to use what is available here - https://machinelearningmastery.com/choose-an-activation-function-for-deep-learning/


Ruminating on Gradient Descent

Gradient Descent is the most popular optimization algorithm used to train machine learning models - by minimizing the cost function. In deep learning, neural nets use back-propagation that internally use a cost function (aka lost function) like Gradient Descent. 

The Gradient descent function essentially uses calculus to find the direction of travel and then to find the local minimal of a function. The following 2 videos are excellent tutorials to understand Gradient Descent and their use in neural nets. 

https://youtu.be/IHZwWFHWa-w

https://youtu.be/sDv4f4s2SB8

Once you understand these concepts, it will help you also realize that there is no magic involved when a neural net learns by itself -- ultimately a neural net learning by itself just means minimizing a cost function (aka loss function).

Neural nets start with random values for their weights (of the channels) and biases. Then by using the cost function, these hundreds of weights/biases are shifted towards the optimal value - by using optimization techniques such as gradient descent. 

Ruminating on 'Fitting the line to data'

 In linear regression, we need to find the best fit line over a set of points (data). StatQuest has an excellent video explaining how we fit a line to the data using the principle of 'least squares' - https://www.youtube.com/watch?v=PaFPbb66DxQ

The best fit line is the one where the sum of the squares of the distances from the actual points to the line is the minimum. Hence this becomes an optimization problem in Maths that can be calculated. We square the distances to take care of negative values/diffs. 

In stats, the optimization function that minimizes the sum of the squared residuals is also called as a 'loss function'. 

The equation of any line can be stated as: y = ax + b

where a is the slope of the line and b is the y-intercept. Using derivates we can find the most optimal values of 'a' and 'b' for a given dataset. 

Wednesday, March 23, 2022

Ruminating on CUDA and TPU

 CUDA  is a parallel computing platform (or a programming model - available as an API) that was developed by Nvidia to enable developers leverage the full parallel processing power of its GPUs. 

For deep learning (training neural nets) requires a humongous amount of processing power and it is here that HPCs with thousands of GPU cores (e.g. A100 GPU) are essential. 

Nvidia has also released a library for use in neural nets called as cuDNN. CUDA Deep Neural Network library (cuDNN) is a GPU-accelerated library of primitives for deep neural networks. cuDNN provides highly tuned implementations for standard routines such as forward and backward convolution, pooling, normalization, and activation layers.

Many deep learning frameworks rely on CUDA & the cuDNN library for parallelizing work on  GPUs - Tensorflow, Caffe2, H2O.ai, Keras, PyTorch. 

To address the growing demand for training ML models, Google came up with it's own custom integrated circuit called as TPU (Tensor Processing Unit). A TPU is basically a ASIC (application-specific integrated circuit) designed by Google for use in ML. TPU's are tailored for TensorFlow and can handle massive multiplications and additions for neural networks, at great speeds while reducing the use of too much power and floor space. 

Examples: Google Photos use TPU's to process more than 100 million photos every day. TPU's also power Google RankBrain - that part of Google's algorithm that uses machine-learning and artificial intelligence to better understand the intent of a search query. 

Tuesday, March 22, 2022

Understanding what is a Tensor?

Found this excellent video on YouTube by Prof. Daniel Fleisch that explains tensors in a very simple and engaging way - https://youtu.be/f5liqUk0ZTw

Tensors are are generalizations of vectors & matrices to N-dimensional space.

  • A scalar is a 0 dimensional tensor
  • A vector is a 1 dimensional tensor
  • A matrix is a 2 dimensional tensor
  • A nd-array is an N dimensional tensor
The inputs, outputs, and transformations within neural networks are all represented using tensors.  A tensor can be visualized as a container which can house data in N dimensions.

Wednesday, March 09, 2022

Topic Modeling vs. Topic Classification

Topic Modeling is an unsupervised method of infering "topics" or classification tags within a cluster of documents. Whereas topic classification is a supervised ML approach wherein we define a list of topics and label a few documents with these topics for training. 

A wonderful article explaining the differences between both the approaches is here - https://monkeylearn.com/blog/introduction-to-topic-modeling/

Some snippets from the above article:

"Topic modeling involves counting words and grouping similar word patterns to infer topics within unstructured data. By detecting patterns such as word frequency and distance between words, a topic model clusters feedback that is similar, and words and expressions that appear most often. With this information, you can quickly deduce what each set of texts are talking about.

 If you don’t have a lot of time to analyze texts, or you’re not looking for a fine-grained analysis and just want to figure out what topics a bunch of texts are talking about, you’ll probably be happy with a topic modeling algorithm.

However, if you have a list of predefined topics for a set of texts and want to label them automatically without having to read each one, as well as gain accurate insights, you’re better off using a topic classification algorithm."

Ruminating on the log scale

Today, I was trying to explain my colleague on the usecases where a log scale could be more useful than a linear scale and I found this wonderful video that explains this concept like a boss! - https://youtu.be/eJF9hiv3c-A

One of the fundamental advantages of using the log scale is that you can illustrate both small and large values on the same graph. Log scales are also consistent because each unit increase signifies the same multiplier effect - e.g. Log10 has 10* multiplier. 

I also never knew the following scales used popularly are actually log scales:

  • Audio volume (decibel) - 10x increase from 50 decibel to 60 decibel
  • Acidity (ph scale)
  • Richter scale (earthquakes)
  • Radioactivity (measure of radiation)

Ruminating on AI Knowledge Base

Many AI systems need a knowledge base that enables logical inference over the knowledge stored in it. This knowledge base is typically encoded using open standards such as RDF (Resource Description Framework).  

To read RDF file, we typically use SPARQL - which is an RDF query language—that is, a semantic query language for databases—able to retrieve and manipulate data stored in RDF. 

A simple Python library to use SPARQL - https://sparqlwrapper.readthedocs.io/

Also some other helper classes if you are not comfortable with SPARQL - https://github.com/qcri/RDFframes

Other popular datastores that support RDF formats are GraphDB and Neo4J

The best example of a knowledge base (or graph) is the "Google Knowledge Graph" - a knowledge base used by Google and its services to enhance its search engine's results with information gathered from a variety of sources. The information is presented to users in an infobox next to the search results.

Tuesday, March 08, 2022

Ruminating on Audio Sample Rate and Bit Depth

 Whenever we are dealing with AI-driven speech recognition, it is important to understand the fundamental concepts of sample rate and bit dept. The following article gives a good overview with simple illustrations. 

https://www.izotope.com/en/learn/digital-audio-basics-sample-rate-and-bit-depth.html

To convert a sound wave into data, we have to measure the amplitude of the wave at different points of time. The number of samples per second is called as the sample rate. So a sample rate of 16kHz means 16,000 samples were taken in one second. 

The bit depth determines the number of possible amplitude values we can record for each sample - e.g. 16-bit, 24-bit, and 32-bit. With a higher audio bit depth, more amplitude values are available for us to record. The following diagram form the above article will help illustrating this concept. 


Free audiobooks

The below site has more than 16,000 audio books that are completely free for everyone!

https://librivox.org/

Would recommend everyone to check this out. 


Ruminating on the Turing Test

 The Turing Test was made famous by Alan Turing in the year 1950. The Turing Test essentially tests a computer's ability to communicate indistinguishably from a human. The Turing Test was also called as the 'Imitation Game' by Alan earlier. 

A good introduction to the Turing Test can be found here - https://youtu.be/3wLqsRLvV-c

Though many claim that the turing test was passed by a AI chatbot called Eugene Goostman, but in reality it is not so. No computer has ever passed the Turing Test - https://isturingtestpassed.github.io/

Intelligent chatbots have really come a long way - The Google Duplex Demo e.g. https://youtu.be/0YaAFRirkfk

Maybe when we achieve AGI (Artificial General Intelligence), then the Turing Test would be accurately passed :)

Sunday, March 06, 2022

Ruminating on n-gram models

N-gram is a fundamental concept in NLP and is used in many language models. In simple terms, N-gram is nothing but a sequence on N words - e.g. San Francisco (is a 2-gram) and The Three Musketeers (is a 3-gram). 

N-grams are very useful because they can be used for making next word predictions, correcting spellings or grammar. Ever wondered how Gmail is able to suggest auto-completion of sentences? This is possible because Google has created a language model that can predict next words.

N-grams are also used for correcting spelling errors - e.g. “drink cofee” could be corrected to “drink coffee” because the language model can predict that 'drink' and 'coffee' being together have a high probability. Also the 'edit distance' between 'cofee' and 'coffee' is 1, hence it is a typo.

Thus N-grams are used to create probabilistic language models called n-gram models. N-gram models predict the occurrence of a word based on its N – 1 previous word. 

The 'N' depends on the type of analysis we want to do - e.g. Research has also shown that trigrams and 4-grams work the best for spam filtering. 

Some good info on N-grams is available at the Standford University site - https://web.stanford.edu/~jurafsky/slp3/slides/LM_4.pdf

Google books also has a "N-Gram" viewer displays a graph showing how those phrases have occurred in a corpus of books (e.g., "British English", "English Fiction", "French") over the selected years. I found this to be useful in understanding what topic was popular in which years: https://books.google.com/ngrams

Ruminating on Text Normalization

Text normalization is the process of converting text to a standard form before we use them for training AI NLP models. The following techniques are typically used for normalizing text. 

Tokenization:  Tokenization is the process of breaking down sentences into words. In many Latin-derived languages, "space" is considered to be a word delimeter. But there are special cases such as 'New York', 'Rock-n-Roll' etc. Also Chinese and Japanese languages do not have spaces between words. We may laso wante to tokenize emoticons and hashtags. 

Lemmatization: In this process, we check if words have the same 'root' - e.g. sings, sang. We then normalize the words to the common root word. 

Stemming: Stemming can be considered a form of Lemmatization wherein we just strip the suffixes from the end of the word - e.g. troubled and troubles can be stemmed to 'troubl'.

Lemmatization is more computationally intensive than Stemming because it actually maps the word to a dictionary and finds the root word. Whereas Stemming just uses some crude heuristic process that chops off the ends of words in the hope of getting the root word. Stemming is thus much faster when you are dealing with a large corupus of text. The following examples will make the difference clear. 

  • The word "better" has "good" as its lemma. This link is missed by stemming, as it requires a dictionary look-up.
  • The word "walk" is the base form for word "walking", and hence this is matched in both stemming and lemmatisation.
  • If you lemmatize the word 'Caring', it would return 'Care'. If you stem, it would return 'Car' and this is erroneous.

Sentence Segmentation: This entails breaking up a long sentence into smaller sentences using chars such as '! ; ?'. 

Spelling Correction and UK/US differences: As part of the normalization activity, we may also want to correct some common spelling mistakes and also normalize the different spelling between UK/US like neighbour/neighbor.