<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Joshua Raj on Medium]]></title>
        <description><![CDATA[Stories by Joshua Raj on Medium]]></description>
        <link>https://medium.com/@joshua_86438?source=rss-9039ff514ab8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*slTvrwI6DM_CF_wH</url>
            <title>Stories by Joshua Raj on Medium</title>
            <link>https://medium.com/@joshua_86438?source=rss-9039ff514ab8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 22:14:21 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@joshua_86438/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Deep Dive into how Predicting Future Weights of Neural Network is used to mitigate Data Staleness…]]></title>
            <link>https://medium.com/@joshua_86438/deep-dive-into-how-predicting-future-weights-of-neural-network-is-used-to-mitigate-data-staleness-a59689754738?source=rss-9039ff514ab8------2</link>
            <guid isPermaLink="false">https://medium.com/p/a59689754738</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Joshua Raj]]></dc:creator>
            <pubDate>Sat, 17 Sep 2022 06:41:24 GMT</pubDate>
            <atom:updated>2022-09-23T16:02:19.705Z</atom:updated>
            <content:encoded><![CDATA[<h3>Deep Dive into how Predicting Future Weights of Neural Network is used to mitigate Data Staleness while Distributed Training</h3><h4>Introducing SpecTrain as means to predict future weights of neural network to alleviate data staleness and improve speed of training via distributed training</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hJKd2L7KSkfoltE8" /><figcaption>Photo by <a href="https://unsplash.com/@jjying">JJ Ying</a> on <a href="https://unsplash.com/">Unsplash</a></figcaption></figure><p>Distributed training of neural networks has seen quite a boom in the technological field today. Well-renowned software development companies have turned their attention towards distributed training, each day coming up with intriguing new research, exceeding the limitations and fine-tuning to make it easy for the masses to learn and develop more from a more economical standpoint.</p><p>We are going to ponder, about one such limitation known as the Staleness issue which proves to be unfavorable while implementing Distributed Training using Model Parallelism.</p><p>Before we go into detail it is suggested that you have a good hunch about distributed training. Feel free to read through — <a href="https://vevesta.substack.com/p/2791ed5e-0679-4f28-ae61-62eac17d8f13"><strong>Everything you need to know about Distributed training and its often untold nuances</strong></a><strong> </strong>as it would help with a smoother progression through this article.</p><h3>The Staleness Issue</h3><p>In model parallelism, when the training proceeds in the pipelined manner, it is seen that the staleness issue is gradually induced which dampens the performance of the neural network. This staleness issue starts very subtly but in due time leads to unstable learning and decreases the model accuracy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/431/0*WFq0tI8CfwV6Ww60.png" /><figcaption><a href="https://arxiv.org/pdf/1809.02839.pdf">The light-color curve denotes the measured values. To make the trends clear, we add a thick line to show the moving average over 20 latest values.</a></figcaption></figure><p>The figure shows the comparison of model accuracy, i.e, the percentage of correct classifications, between model and data parallelism.</p><p>We observe that when compared with data parallelism the accuracy of model parallelism fluctuates more prominently. Since model parallelism is considered to be a more fitting choice for parallelizing Deep Neural Networks finding a way to resolve this issue is a huge priority.</p><h3>Pipelining and The Cause of Staleness</h3><p>The Pipeline training is basically a rotation of sample data that was split into a mini-batch, which flows through the pipeline normally forward propagating generating gradients as they move along from one GPU to another. After done with forward propagation(forward pass) of a batch these batches are made to propagate backward (backward pass) to fetch the weight updates from the forward pass. So constructively it is a to and fro action as seen in the figure below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/431/0*VoKGdr9ZnuiRxzi_.png" /><figcaption><a href="https://arxiv.org/pdf/1809.02839.pdf">Pipelining of Model Parallelism</a>-The boxes with index ‘i’ denote the time spent on processing the ‘i-th’ mini-batch. Cyan and yellow boxes indicate forward and backward tasks respectively. A round trip of processing a mini-batch is presented by the arrows.</figcaption></figure><p>As we can see in the figure, after the completion of one task the GPU asynchronously proceeds to the next task to be time efficient.</p><h4>The cause of Staleness</h4><blockquote><em>Simply put, Staleness occurs when multiple mini-batches are in progress in the pipeline, before earlier mini-batches update weights, the latter mini-batches adopt stale weights to derive gradients.</em></blockquote><p>In pipelined training, a mini-batch is processed by different GPUs are run coherently to finish the forward and backward passes. Since many mini-batches are stacked in the pipeline, weights are continuously updated at every GPU, which causes the mini-batch to adopt inconsistent versions of weights during an iteration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/444/0*97z-bziZ6AyvBGu3.png" /><figcaption><a href="https://arxiv.org/pdf/1809.02839.pdf">Pipelining</a></figcaption></figure><p>For example, in Figure the figure above, the 4th mini-batch adopts various versions of weights, ranging from W4 to W6, during its full circle. From the 4th mini-batch’s perspective, W4 and W5 are stale and the only staleness-free version of weights is W6, as W6 is derived after the 3-rd mini-batch updates the weights.</p><p>Before the weights could be optimized, another set of the data batch computes considering the same stale weights resulting in a faulty gradient. Such a weight update behavior is called the weight staleness issue and it leads to unstable and inferior convergence.</p><h3>Staleness Mitigation via SpecTrain</h3><p>SpectTrain is used to completely rectify the weight staleness and consistency issue. It uses a weight prediction method, which is also easy to apply in the pipeline. In an ideal training procedure, each iteration of a mini-batch should be updated to the same weight version. To maintain weight consistency and avoid staleness, SpecTrain predicts future weights and adopts the predicted weights, rather than the staled version of weights, through a whole iteration of a mini-batch.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/456/0*7OLWJ79u7VwaXlhR.png" /><figcaption><a href="https://arxiv.org/pdf/1809.02839.pdf">SpecTrain</a></figcaption></figure><p>As we can see in this illustration, for the same 4th mini-batch instead of adopting different and stale values, by using SpecTrain the GPUs predict the future version of the weight, which is expected to be staleness-free. The staleness-free version originally would be W6. W6 would only be adopted after W4 and W5 but by using SpecTrain the processing of the 4-th mini-batch in its entire round trip is based on W6 rather than W4, giving us the correct gradients, thus improving the accuracy overall.</p><h4>Weight Prediction</h4><p>SpecTrain predicts future weights based on the observation that smoothed gradients used in Momentum Stochastic Gradient Decent(SGD), which reflects the trend of weight updates. Momentum SGD is a well-known technique that helps to speed up and improve the stability of SGD by smoothing the weight updates. A smoothed gradient (vt) is the weighted average of recent gradients and is calculated by the following equation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/248/0*yz39_o2SC_iho6yO.png" /></figure><p>where γ is the decay factor with 0 &lt; γ ≤ 1 and ‘gt’ is the newly generated gradient. Through averaging with recent gradients by the decay factor, smoothed gradient vt reflects the trend of weight updates. Thus, smoothed gradients can be used to predict future weights.</p><h3>The Impact SpecTrain Makes</h3><p>SpecTrain was studied and compared with Data Parallelism along with a regular Model Parallelism method with no staleness reducing agents and PipeDream which is an older alternative that was used to reduce staleness in Data Parallelism.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/977/0*Y3Q3pX6ttWNWep73.png" /><figcaption><a href="https://arxiv.org/pdf/1809.02839.pdf">Learning curves when using different parallelization schemes to train Transformer</a></figcaption></figure><p>Each of the experiments is done by training each model for 5000 iterations and training loss, validation loss, and validation accuracy are recorded for every full circle or iteration to show the learning curve. As we see from the results in the study model parallelism with SpecTrain performs exceptionally better than the regular model parallelism.</p><p>The Accuracy loss that model parallelism heavily suffered from, with the use of weight prediction is on par with data parallelism, likewise, it also alleviates the instability problem by weight prediction and the learning curve of SpecTrain is similar to data parallelism, indicating that using SpecTrain can achieve near robust training process. Although it doesn’t surpass data parallelism with the features of model parallelism and the results of data parallelism can train Deep neural networks with bulky datasets with ease.</p><p>Hence by the research provided to us by <a href="https://arxiv.org/pdf/1809.02839.pdf">Efficient and Robust Parallel DNN training through model parallelism on multi-GPU platform</a>, we can say that SpecTrain resolves the staleness issue. Helping push model parallelism to its limits.</p><p>The above article is sponsored by <a href="https://www.vevesta.com/blog/33-Mitigating-Data-Staleness?utm_source=Medium-DistributedTraining-SpecTrain"><strong><em>Vevesta</em></strong></a><em>.</em></p><p><a href="https://www.vevesta.com/blog/33-Mitigating-Data-Staleness?utm_source=Medium-DistributedTraining-SpecTrain"><strong><em>Vevesta</em></strong></a><strong><em>: </em></strong>Your Machine Learning Team’s Feature and Technique Dictionary — Accelerate your Machine learning project by using features, techniques and projects used by your peers</p><p><em>The next article will be published at weekly intervals.</em> I<em>f you enjoyed my article, simply send me some claps and feedback at sbellary@vevesta.com or follow us on twitter at </em><a href="https://twitter.com/vevesta_labs">@vevesta_labs</a><em> for regular updates on my articles.</em></p><p><em>100 early birds who login to </em><a href="https://www.vevesta.com/blog/33-Mitigating-Data-Staleness?utm_source=Medium-DistributedTraining-SpecTrain"><strong><em>Vevesta</em></strong></a><em> will get a free subscription for 3 months.</em></p><h3>References</h3><ol><li><a href="https://www.vevesta.com/blog/33-Mitigating-Data-Staleness?utm_source=Medium-DistributedTraining-SpecTrain">Pipeline and SpecTrain</a></li><li><a href="https://www.vevesta.com/blog/32-Distributed-Training?utm_source=Substack-DistributedTraining-SpecTrain">Distributed Training</a></li><li><a href="https://arxiv.org/pdf/1809.02839.pdf">Robust Parallel DNN Training</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a59689754738" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Everything you need to know about Distributed training and its often untold nuances]]></title>
            <link>https://medium.com/@joshua_86438/everything-you-need-to-know-about-distributed-training-and-its-often-untold-nuances-fb37275f6cb5?source=rss-9039ff514ab8------2</link>
            <guid isPermaLink="false">https://medium.com/p/fb37275f6cb5</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[neural-networks]]></category>
            <dc:creator><![CDATA[Joshua Raj]]></dc:creator>
            <pubDate>Thu, 15 Sep 2022 04:55:18 GMT</pubDate>
            <atom:updated>2022-09-21T14:49:56.652Z</atom:updated>
            <content:encoded><![CDATA[<h4>Understanding Data Parallelism vs Model Parallelism, Their Powers and Their Kryptonite</h4><p>The idea of dividing portions of work to obtain exceptional results, in a short amount of time and thereby reducing the overall strain is exactly the gist of our topic called “Distributed Training”, which has led to some very interesting research in the field of machine learning pushing our technology another leap ahead.</p><h3>Introduction To Distributed Training</h3><p>The number of parameters in modern deep learning models is growing exponentially, and the size of the data set is also increasing at a similar rate. Therefore dividing one huge task into a number of subtasks to run them parallelly makes the whole process much more time efficient and enables us to complete complex tasks with ginormous datasets. This is what we call as distributed training.</p><p>To put it simply, by using multi-node training, we train massive deep learning models which would require ages to train otherwise. There are two main branches under distributed training, called:-</p><ol><li>Data Parallelism</li><li>Model Parallelism</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/509/0*vkmFD7zGE9KbfEDy.png" /><figcaption><a href="https://arxiv.org/pdf/1809.02839.pdf">Training With Different Parallelism</a></figcaption></figure><h3>Data Parallelism</h3><p>In data parallelism, the giant dataset is split up into parts. Each part has its own GPU. These GPUs are then connected to parallel computational machines. The gradients collected from different batches of data are then collected and the values are merged to get the final result.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/625/0*aAPoahswWNHxzXsM.png" /><figcaption><a href="https://towardsdatascience.com/deep-learning-on-supercomputers-96319056c61f">Data Parallelism</a></figcaption></figure><p>For every GPU or node, the generic parameters are kept constant and the network ideally is a feed-forward network, where a small batch of data is sent to every node, and the gradient is computed normally and sent back to the main node. Data parallelism uses inter-GPU communication for talking with other nodes and GPUs to get gradients for proper weight synchronization.</p><p>There are two approaches to data parallelism which are:-</p><ul><li><strong>Synchronous Training</strong></li></ul><p>As a part of sync training, the model sends different parts of the data into each node. Each model is totally identical to the original model, the only difference between them being the different batch of data that is being trained. The network here works in forward propagation parallelly which gives distinct results and gradients. Synchronous training uses an all-reduce algorithm that collects all the trainable parameters from various nodes and accelerators. While synchronous training can be advantageous in many ways, it is harder to modify and scale to the growing need for computation resulting in unused nodes with zero work.</p><ul><li><strong>Asynchronous Training</strong></li></ul><p>The specialty of asynchronous training is its property to scale with the amount of data available and speed up the rate at which the entire dataset contributes to the optimization. Unlike synchronous training, in asynchronous training, the nodes work independently in such a way that a worker node need not wait for any other worker node in the cluster. One way to achieve this is by using a parameter server, as it holds the parameters of the model which are responsible for updating the global state of our model and requires less communication between nodes, and also benefits from a high amount of computations per weight.</p><h4>Model Parallelism</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/468/0*NIWeFBtUXvlDahjj.png" /><figcaption><a href="https://towardsdatascience.com/deep-learning-on-supercomputers-96319056c61f">Model Parallelism</a></figcaption></figure><p>In model parallelism, instead of the data being split up into parts, the model is divided into separate parts and now these individual parts will have their own GPU. That is, each GPU takes as input the data flowing into a particular layer, processes data across several subsequent layers in the neural network, and then sends the data to the next GPU.</p><p>The batch of GPUs is then calculated sequentially in this manner, starting with the first one onto the final GPU, making this into a forward propagation. Backward propagation on the other hand begins with the final and ends at the first GPU. Model parallelism also needs an acute amount of inter-GPU communication to transfer all intermediate data between sub-models.</p><p>Model parallelism has some obvious benefits. It can be used to train a model such that it does not fit into just a single GPU. But when computation is moving sequentially, for example, when the first GPU is in computation, the others simply lie idle. This can be resolved by shifting to an asynchronous style of GPU functioning.</p><p>A study titled <a href="https://arxiv.org/pdf/1809.02839.pdf">‘Efficient and Robust Parallel DNN Training through Model Parallelism as Multi-GPU Platform</a>’ tested model parallelism versus data parallelism. We shall take a deeper look into the results of the given theory.</p><h3>Drawbacks of Data Parallelism and How Model Parallelism Overcomes it</h3><p>So far, we have seen how to distribute the data and train the model in multiple devices with different chunks of data and this approach works most of the time and is easy to implement as well. Following are the advantages of using Model Parallelism:</p><ul><li>In some rare situations, the size of the model may be too large for any single worker, which is why we need model parallelism wherein we split the model itself to make computing faster.</li><li>As said earlier, it is harder to modify and scale to the growing need for computation resulting in unused nodes or workers with zero work. But in model parallelization, since all models are split up and work coherently there is much less loss in computation.</li><li>Both data parallelism and model parallelism need inter-GPU communications. The study shows that practically data parallelism requires more inter-GPU communication generally than model parallelism.</li><li>While some of the implemented data-parallelization required almost no communication between GPUs when model parallelism is applied since these models have fewer intermediate data between layers.</li><li>In the figure below, we see how different parallelizations use GPU cross-talking and the likely hood of time wasted while communicating.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/469/0*XbyPaNj7em7FZtel.png" /><figcaption><a href="https://arxiv.org/pdf/1809.02839.pdf">The amount of inter-GPU data transfers per mini-batch when applying different parallelization approaches on a 4-GPU system</a></figcaption></figure><ul><li>This dependency on inter-GPU communications of data parallelism leads up to a considerable slowdown. On average 26.7% of training time is spent on inter-GPU data transfer when data parallelism is applied.</li><li>The figure below has the amount of time Data Parallelism uses for Inter-GPU communication vs the time it takes to process and compute the gradients.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/464/0*Z6EYsCealwGtPlg3.png" /><figcaption><a href="https://arxiv.org/pdf/1809.02839.pdf">Percentage of time spent on inter-GPU communications when applying data parallelism on a 4-GPU system.</a></figcaption></figure><h3>Advantages of Data Parallelism Over Model Parallelism</h3><ul><li>Studies showed that models using data parallelism increase in their accuracy as training proceeds, but the accuracy starts fluctuating with model parallelism.</li><li>For model parallelism, if training proceeds in the pipelined manner, it induces the staleness issue. This staleness issue leads to unstable learning and worse model accuracy.</li><li>In the figure below, the depicted graph we’re able to see how staleness causes a loss in training accuracy starting from the 2700 iteration leading to the drop ahead to the 5000s.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/431/0*9GFOar4oISs17vee.png" /><figcaption><a href="https://arxiv.org/pdf/1809.02839.pdf">The light-color curve denotes the measured values. To make the trends clear, we add a thick line to show the moving average over 20 latest values.</a></figcaption></figure><ul><li>Data parallelism partitions training data across a whole array of GPUs, therefore, the workload across the GPUs could be easily maintained.</li><li>While in, model parallelism, achieving this load balance is more grueling a task. Since the complexity of different Deep Neural Network(DNN) layers varies, it would require loads of time and hard work to partition model layers to GPUs in a balanced way.</li></ul><h3>Conclusion</h3><ul><li>Distributed training is used to train huge deep learning models which would require an extremely large amount of time to train generically.</li><li>Both, data and model parallelism have their own advantages which could be used following their availability and necessity.</li><li>The concept of distributed training has piqued the interest of scientists all around the world and the algorithms and methodologies are leading to more discoveries.</li><li>Distributed training implements GPUs for training, hence it is the groundwork for learning how GPUs are used to train models and push data.</li></ul><p>The above article is sponsored by <a href="https://www.vevesta.com/blog/32-Distributed-Training?utm_source=Medium-DistributedTraining"><strong><em>Vevesta</em></strong></a><em>.</em></p><p><a href="https://www.vevesta.com/blog/32-Distributed-Training?utm_source=Medium-DistributedTraining"><strong><em>Vevesta</em></strong></a><strong><em>: </em></strong>Your Machine Learning Team’s Feature and Technique Dictionary — Accelerate your Machine learning project by using features, techniques and projects used by your peers</p><p><em>The next article will be published at weekly intervals.</em> I<em>f you enjoyed my article, simply send me some claps and feedback at sbellary@vevesta.com or follow us on twitter at </em><a href="https://twitter.com/vevesta_labs">@vevesta_labs</a><em> for regular updates on my articles.</em></p><p><em>100 early birds who login to </em><a href="https://www.vevesta.com/blog/32-Distributed-Training?utm_source=Medium-DistributedTraining"><strong><em>Vevesta</em></strong></a><em> will get a free subscription for 3 months.</em></p><h3>References</h3><ol><li><a href="https://www.vevesta.com/blog/32-Distributed-Training?utm_source=Medium-DistributedTraining">Distributed Training — Vevesta</a></li><li><a href="https://leimao.github.io/blog/Data-Parallelism-vs-Model-Paralelism/">Lei mao-Distributed Training</a></li><li><a href="https://neptune.ai/blog/distributed-training">Neptune.ai</a></li><li><a href="https://towardsdatascience.com/deep-learning-on-supercomputers-96319056c61f">Towards Data Science</a></li><li><a href="https://arxiv.org/abs/1312.6186">GPU Asynchronous Stochastic Gradient Descent to Speed Up Neural Network Training</a></li><li><a href="https://analyticsindiamag.com/data-parallelism-vs-model-parallelism-how-do-they-differ-in-distributed-training/">Analytics India Mag</a></li><li><a href="https://arxiv.org/pdf/1809.02839.pdf">Robust Parallel DNN Training</a></li><li><a href="https://vevesta.substack.com/p/distributed-training-deep-learning">Distributed Training — Substack</a></li><li><a href="https://www.vevesta.com/blog/33-Mitigating-Data-Staleness?utm_source=Medium-DistributedTraining-SpecTrain">DistributedTraining — SpecTrain</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fb37275f6cb5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Everything you need to know about Activation Functions]]></title>
            <link>https://medium.com/@joshua_86438/everything-you-need-to-know-about-activation-functions-b9ef00359d5f?source=rss-9039ff514ab8------2</link>
            <guid isPermaLink="false">https://medium.com/p/b9ef00359d5f</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Joshua Raj]]></dc:creator>
            <pubDate>Tue, 06 Sep 2022 15:03:40 GMT</pubDate>
            <atom:updated>2022-09-12T18:01:54.608Z</atom:updated>
            <content:encoded><![CDATA[<h4>The need, the types, and the drawbacks of different activation functions</h4><p>Our human brain learns any objective presented to it with unprecedented speed and accuracy. It has left humankind baffled as to how remarkable our brain is and its ability to learn patterns. Recognition is the core feature in our evolution from savages to intelligent beings. Similarly, activation functions allow machines to differ and learn from their output. Although simple to understand, it’s an incredible feat to make machines capable of mastering many arduous tasks which are difficult for us; human beings.</p><p>Before we look into activation functions, we must know what a neural network is and what this paradigm consists of.</p><h3>Introduction to Neural Networks</h3><p>A Neural Network is a Machine Learning mechanism that potentially mirrors the way a human brain works. To make any impulsive action, a brain gets subjected to countless triggers from the sensors, this load of the received information is processed with the blink of an eye and delivers an output to make a decisive reaction. The more complex the work more neurons take part in the decision-making process and form a complex network, sharing the information within themselves.</p><p>An Artificial Neural Network mimics this behavior to solve problems beyond the capabilities of human computing. The network below is a neural network made of interconnected neurons where each neuron is uniquely distinguished by its weight and bias.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/771/0*T-EOy7Q5mOgJCPSm.png" /></figure><p><a href="https://www.v7labs.com/blog/neural-networks-activation-functions#h1">A Neural Network</a></p><h3>What is an Activation Function?</h3><blockquote><em>The Activation function calculates the weighted sum of the inputs accumulating the bias along with it and then makes the decision whether to activate the neuron or not.</em></blockquote><p>The input is fed to the input layer, the neurons perform a linear transformation on this input using the weights and biases.</p><p>So we consider a neuron,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/608/0*hwM4l6D3p-yHVtrG.png" /></figure><p>The value of Y can be anything ranging from -inf to +inf. Here the neuron doesn’t know the limits of this value, so to take control of this resolution “activation functions” are added to guide the neurons. It governs each neuron in the artificial neural network, to check the Y value produced by a neuron and decide whether this neuron should be enabled or not.</p><p>The aftermath from the activation function moves ahead to the hidden layer or another and the same process is repeated. This forward movement of information is known as feed-forward propagation. Which snowballs to the desired result.</p><p>However, if the result is far off from what was expected, using the output of the feed-forward propagation, the error is calculated. Depending on this error value, the weights and biases of the neurons are optimized. This process is known as back-propagation.</p><h3>The need for Activation Functions</h3><p>The purpose of the activation function is to introduce non-linearity into the output of a neuron. A neural network without activation functions is essentially a linear regression model. Although a linear equation is a polynomial of one degree, which is simple to solve, a neuron can not learn with just a linear function attached. So, the activation function does the non-linear transformation to the inputs concerning the error and gifts the machine an ability to learn.</p><p>The choice of activation function in the hidden layer will control how well the network model learns the training dataset. The choice of activation function in the output layer will define the type of predictions the model can make. This ensures that neurons build a network suitable for the given task and the weights are shared accordingly.</p><h3>Types of Activation Functions</h3><p>Activation functions are further classified into two types,</p><ol><li>Fixed shape activation functions</li><li>Trainable activation functions</li></ol><p>We must see the activation functions of both these categories to have a clear understanding of how each differs from the other.</p><h4>Fixed Shape Activation Functions</h4><p>Being called the “fixed-shape activation functions”, it defines all the activation functions that are deprived of parameters that can be modified during the training phase. All the classic activation functions used in neural network literature, such as sigmoid, tanh, ReLU, fall into this category.</p><p>Out of all the functions of this taxonomy, ReLU or Rectified Linear Unit has left the deep learning community as a whole to be in awe and has led the researchers to solve problems that were considered to be an enigma. It has left a significant impact, so much so that it’s considered the rudimentary foundation of deep learning.</p><p>To understand the real significance of Relu we have a brief overview of the sigmoid function and the vanishing gradients.</p><h4>The Vanishing Gradient</h4><p>The sigmoid function is shaped like the S alphabet as given below. It is non-linear.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/453/0*7uDTyYQIBYhT1MSs.png" /></figure><p>The Mathematical and diagrammatic Representation of the <a href="https://towardsdatascience.com/activation-functions-neural-networks-1cbd9f8d91d6">Sigmoid Function</a> is as follows:-</p><ul><li>It has a smooth gradient and transforms the values between 0 to 1</li><li>The sigmoid function is especially used for models where we have to predict the probability as an output. Since the probability of anything exists only between the range of 0 and 1.</li><li>This function has steep Y values to the corresponding X values. This means any changes in the values of X in that region will cause values of Y to change drastically, meaning it tends to bring the Y values to either end of the curve and thus is a good binary classifier.</li></ul><p>As the function only trains within the closed range of roughly -6 to 6. the Y values tend to respond very less to changes in X. This is because beyond the limits on either side of the gradients are insignificant. It gives rise to a problem of “vanishing gradients”. Because of this reason, using the sigmoid function in a deep network is not preferred.</p><p><strong>ReLU</strong> is the first workaround to overcome the undesired outcomes of the sigmoid function.</p><h4>ReLU</h4><p>ReLU or Rectified Linear Unit is another non-linear activation function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/0*MuPwdRpb5gUMRNC2.png" /></figure><p>The Mathematical and diagrammatic Representation of the <a href="https://towardsdatascience.com/activation-functions-neural-networks-1cbd9f8d91d6">ReLU Function</a> is as follows</p><ul><li><strong>ReLU</strong> is simply outputting the non-negative output of a neuron. However, as you might have noted, ReLU simply does not exist in the negative space.</li><li>The derivatives are never dead in the positive region. As the values are output as it is without any dampening, values will not vanish as we saw in the sigmoid function.</li><li>The main advantage of using the ReLU function over other activation functions is the sparsity of the activation. It does not activate all the neurons at the same time, since for all the negative values the result is zero. Hence is more computationally effective.</li></ul><h4>The Downfall of ReLU</h4><p>Since this function has no presence in the negative X direction, the gradient can go towards 0. For activations in that region of ReLu, the gradient will be 0 because of which the weights will get disjointed during descent. The neurons which go into this state will become an empty husk that responds to no stimuli. The neuron never learns and causes almost a sigmoid-like saturation. This is called the dying ReLu problem.</p><h4>Trainable activation functions</h4><p>This class contains all the activation functions, the shape of which is learned during the training phase. It implies that, unlike the fixed shape activation functions, these functions can morph and fit the function giving it a superior edge over the fixed shape functions. We will thus delve deeper and look at the successor of ReLU known as Parametric ReLU</p><h4>Parametric ReLU</h4><p>Leaky ReLU, is a variant of a ReLU function, but it has a small slope for negative values instead of a flat slope. The slope coefficient is determined before training, meaning that it is a fixed-shaped activation function and the slope is not learnt during training.</p><p>Introducing the ReLU variation function that partially learns its shape from the training set, Parametric ReLU tries to parameterize the negative input thus enabling the recovery of the dying ReLU.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/777/0*rPNB6v-wqIVXdKlI.png" /></figure><p><a href="https://www.v7labs.com/blog/neural-networks-activation-functions#h1">PReLU Function</a></p><p>The mathematical function of PReLU is given as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/288/0*CoTG6Xm0tHiJ8J2w.png" /></figure><p>Where <em>“a” </em>is the slope parameter for negative values.</p><ul><li>The network also learns the value of <strong>a</strong> and changes it every training iteration for faster and more optimum convergence.</li><li>Since the negative pre-activations produce negative values instead of 0, we do not have the problem regarding weights being updated only in one direction that was associated with ReLU.</li><li>This fixes the problem of the dying ReLU problem and enhances the same function by being parameterized and adaptable.</li></ul><h3>Conclusion</h3><ul><li>Linear functions evolved to be able to solve intricate problems by the use of Activation functions.</li><li>Activation functions administer the firing or avoiding of a neuron, which helps the weights to shift to the neuron which proves better results and also a well-built neural network altogether.</li><li>The sigmoid function is exceptional at solving binary classification problems</li><li>Activation functions must be chosen by looking at the range of the input values. However, ReLU or PReLU is a good starting point with sigmoid or softmax to the output layer.</li><li>The undeniable advantage that the Trainable functions have over the Fixed Shape Functions.</li><li>There is still a wide field of research getting conducted on activation functions and how to get them to peak performance with little to no tweaking.</li></ul><p>The above article is sponsored by <a href="https://www.vevesta.com/?utm-source=Medium-ActivationFunction"><strong><em>Vevesta</em></strong></a><em>.</em></p><p><a href="https://www.vevesta.com/?utm-source=Medium-ActivationFunction"><strong><em>Vevesta</em></strong></a><strong><em>: </em></strong>Your Machine Learning Team’s Feature and Technique Dictionary — Accelerate your Machine learning project by using features, techniques and projects used by your peers</p><p><em>The next article will be published at weekly intervals.</em> I<em>f you enjoyed my article, simply send me some claps and feedback at sbellary@vevesta.com or follow us on twitter at </em><a href="https://twitter.com/vevesta_labs">@vevesta_labs</a><em> for regular updates on my articles.</em></p><p><em>100 early birds who login to </em><a href="https://www.vevesta.com/?utm-source=Medium-ActivationFunction"><strong><em>Vevesta</em></strong><em> </em></a><em>will get a free subscription for 3 months.</em></p><h3>References</h3><ol><li><a href="https://www.vevesta.com/?utm-source=Medium-ActivationFunction">Activation Functions — Vevesta</a></li><li><a href="https://vevesta.substack.com/p/everything-you-need-to-know-about-c2c">Activation Functions — Substack</a></li><li><a href="https://arxiv.org/pdf/2005.00817.pdf">A survey on modern trainable activation functions</a></li><li><a href="https://towardsdatascience.com/common-activation-functions-and-why-you-must-know-them-ec90e54a7079">Towards Data Science</a></li><li><a href="https://blog.paperspace.com/vanishing-gradients-activation-function/">Blogs Paper Space</a></li><li><a href="https://deepai.org/machine-learning-glossary-and-terms/activation-function">Deep ai</a></li><li><a href="https://www.v7labs.com/blog/neural-networks-activation-functions#h1">V7 Labs</a></li><li><a href="https://www.geeksforgeeks.org/activation-functions-neural-networks/#:~:text=Definition%20of%20activation%20function%3A%2D,the%20output%20of%20a%20neuron">Geeks for Geeks</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b9ef00359d5f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why should you be looking at Few-Shot Learning?]]></title>
            <link>https://medium.com/@joshua_86438/why-should-you-be-looking-at-few-shot-learning-2614576600d3?source=rss-9039ff514ab8------2</link>
            <guid isPermaLink="false">https://medium.com/p/2614576600d3</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Joshua Raj]]></dc:creator>
            <pubDate>Fri, 26 Aug 2022 18:28:15 GMT</pubDate>
            <atom:updated>2022-09-12T18:02:34.368Z</atom:updated>
            <content:encoded><![CDATA[<h4>Unlike Transfer Learning, Few-Shot learning is more about training unfamiliar tasks and optimizing the hyperparameters for networks that are not trained at all</h4><p>In a fast-growing society, speed and efficiency are widely appreciated by people especially when it’s accompanied by sure-found results. At the same age where human speed and flexibility are praised coherently machines with the ability to adapt and grow to the constant change in data are considered to be crucial for such a rapid moving time. In the machine learning world, <a href="https://arxiv.org/abs/1803.02999">Reptile</a> is one of such quick adapting training algorithms that can be applied to learning problems and models by meta-learning which can be imagined as a machine learning to learn better for faster and more accurate computation.</p><h3>What is few-shot learning?</h3><p>As the name suggests few-shot learning is a sub-genre of machine learning in which a model is trained in an objective aspect so that it can swiftly get used to any given task with limited data within a small number of training repetitions. This method to train a model is generally used to classify or distinguish objects from the given data samples. Few-shot learning can also be called as One shot or Zero Shot learning depending on the number of data samples used to train the model.</p><p>To gain deeper insight into Reptile it is essential that we understand what is Model Agnostic Meta-Learning.</p><h3>Model Agnostic Meta-Learning</h3><p>Model Agnostic Meta-Learning or MAML, a few-shot algorithm, that can learn a new task with the small amount of data presented to it, and fine-tunes the parameters of any standard model via meta-learning to enhance that model for smoother adaptation. Being called model agnostic, it can be directly applied to any learning problem and model that is trained with a gradient descent procedure. The gradient descent procedure is fundamental in machine learning and is used to reduce the cost/loss function. It’s easily applicable and hence considered one of the fundamentals to learn in machine learning.</p><h3>Th e Working of MAML Algorithms</h3><p>To comprehend the working of MAML algorithms we must use the figure below to visualize the approach this algorithm uses.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/341/0*Yvg0FWiZN3Wku95j.png" /><figcaption><a href="https://arxiv.org/pdf/1703.03400.pdf">Model-Agnostic Meta-Learning for Fast Adaptation of Deep Networks</a></figcaption></figure><p>We have an initial set of parameters θ and ▽L1,▽L2, and ▽L3 are new tasks. We can visualize each meta-iteration as a branch of a tree and each task attached can be seen as the twigs from the branches and the data provided for the task being the leaves, the end goal is updating the tree’s parameters to feint towards the sun for maximum production of energy.</p><p>So to obtain better results on a new task we must learn the prime set of initial parameters by each meta-iteration and train the model’s initial parameters such that we get closer to our result from the least amount of gradient steps adapting rapidly to each of the new classification tasks that will then be fine-tuned as per the favorable inner parameter by meta-learning, by each inner iteration of the task and would result in a crystal clear classification of the tasks given.</p><p>This from a feature learning standpoint is building an internal representation or input to output mapping that our system can hold and make so that it’s susceptible to managing many tasks altogether. If they are favorable then just fine-tuning the parameters gives us better results. In other words, the algorithm maximizes the sensitivity of the loss functions from the tasks, changing and optimizing the parameter to bring improvements in the task loss.</p><h3>How MAML Differs From Transfer Learning</h3><ul><li>Transfer learning aims at improving the process of learning new tasks using the experience and knowledge gained by solving a predecessor problem that is somewhat similar. It takes a more creatural approach by absorbing and applying to solve problems, constantly training from similar tasks.</li><li>While MAML being a unit of its own applies its algorithms to any given data presented and adapts to the number of information fed to it. Much like a shapeshifter, it basically shifts and learns to train itself towards the outcome through each repetition. It’s more about speeding up and optimizing the hyperparameters for networks that are not trained at all.</li><li>MAML has a slight upper hand as it constantly evolves to the task presented all while maintaining its speed and fluidity, while Transfer Learning bogs down when presented; an unfamiliar task that makes MAML more dependable.</li></ul><h3>Introduction to Reptile</h3><p>The Reptile algorithm was developed by OpenAI to perform model agnostic meta-learning. Reptile is a simplification of MAML, obtained by ignoring second-order derivatives. This algorithm was specially designed with the intention to execute a task rapidly by repeatedly sampling a task, training on it, and moving the initialization towards the trained weights on that task. Just like MAML, Reptile works by performing stochastic gradient descent using the difference between parameters trained on a batch of fresh data and the model parameters prior to training over a fixed number of meta-iterations. Which proves to give outstanding results for few-shot learning. We use the Algorithm on an omniglot dataset and check the results.</p><h4>Implementing of Reptile on Omniglot Dataset</h4><p>We look at the execution of Reptile</p><pre>import matplotlib.pyplot as plt<br>import numpy as np<br>import random<br>import tensorflow as tf<br>from tensorflow import keras<br>from tensorflow.keras import layers<br>import tensorflow_datasets as tfds</pre><h4>Defining The Hyperparameters</h4><pre>learning_rate = 0.003<br>meta_step_size = 0.25</pre><pre>inner_batch_size = 25<br>eval_batch_size = 25</pre><pre>meta_iters = 2000<br>eval_iters = 5<br>inner_iters = 4</pre><pre>eval_interval = 1<br>train_shots = 20<br>shots = 5<br>classes = 5</pre><h3>The Omniglot dataset</h3><p>The <a href="https://github.com/brendenlake/omniglot/">Omniglot dataset</a> is a dataset of 1,623 characters taken from 50 different alphabets, with 20 different handwritten examples for each character. For the few-shot learning task, k samples from the 20 examples for each character are chosen randomly from n randomly-chosen classes from the class list. These n values are used to create a new set of temporary labels to use to test the model&#39;s ability to learn a new task given only a few examples. In other words, if you are training on 5 classes, your new class labels will be one among 0, 1, 2, 3, or 4.</p><pre>class Dataset:<br>    # This class will facilitate the creation of a few-shot dataset<br>    # from the Omniglot dataset that can be sampled from quickly while also<br>    # allowing to create new labels at the same time.<br>    def __init__(self, training):<br>        # Download the tfrecord files containing the omniglot data and convert to a<br>        # dataset.<br>        split = &quot;train&quot; if training else &quot;test&quot;<br>        ds = tfds.load(&quot;omniglot&quot;, split=split, as_supervised=True, shuffle_files=False)<br>        # Iterate over the dataset to get each individual image and its class,<br>        # and put that data into a dictionary.<br>        self.data = {}</pre><pre>        def extraction(image, label):<br>            # This function will shrink the Omniglot images to the desired size,<br>            # scale pixel values and convert the RGB image to grayscale<br>            image = tf.image.convert_image_dtype(image, tf.float32)<br>            image = tf.image.rgb_to_grayscale(image)<br>            image = tf.image.resize(image, [28, 28])<br>            return image, label</pre><pre>        for image, label in ds.map(extraction):<br>            image = image.numpy()<br>            label = str(label.numpy())<br>            if label not in self.data:<br>                self.data[label] = []<br>            self.data[label].append(image)<br>        self.labels = list(self.data.keys())</pre><pre>    def get_mini_dataset(<br>        self, batch_size, repetitions, shots, num_classes, split=False<br>    ):<br>        temp_labels = np.zeros(shape=(num_classes * shots))<br>        temp_images = np.zeros(shape=(num_classes * shots, 28, 28, 1))<br>        if split:<br>            test_labels = np.zeros(shape=(num_classes))<br>            test_images = np.zeros(shape=(num_classes, 28, 28, 1))</pre><pre>        # Get a random subset of labels from the entire label set.<br>        label_subset = random.choices(self.labels, k=num_classes)<br>        for class_idx, class_obj in enumerate(label_subset):<br>            # Use enumerated index value as a temporary label for mini-batch in<br>            # few shot learning.<br>            temp_labels[class_idx * shots : (class_idx + 1) * shots] = class_idx<br>            # If creating a split dataset for testing, select an extra sample from each<br>            # label to create the test dataset.<br>            if split:<br>                test_labels[class_idx] = class_idx<br>                images_to_split = random.choices(<br>                    self.data[label_subset[class_idx]], k=shots + 1<br>                )<br>                test_images[class_idx] = images_to_split[-1]<br>                temp_images[<br>                    class_idx * shots : (class_idx + 1) * shots<br>                ] = images_to_split[:-1]<br>            else:<br>                # For each index in the randomly selected label_subset, sample the<br>                # necessary number of images.<br>                temp_images[<br>                    class_idx * shots : (class_idx + 1) * shots<br>                ] = random.choices(self.data[label_subset[class_idx]], k=shots)</pre><pre>        dataset = tf.data.Dataset.from_tensor_slices(<br>            (temp_images.astype(np.float32), temp_labels.astype(np.int32))<br>        )<br>        dataset = dataset.shuffle(100).batch(batch_size).repeat(repetitions)<br>        if split:<br>            return dataset, test_images, test_labels<br>        return dataset<br></pre><pre>import urllib3</pre><pre>urllib3.disable_warnings()  # Disable SSL warnings that may happen during download.<br>train_dataset = Dataset(training=True)<br>test_dataset = Dataset(training=False)</pre><h4>Visualizing the dataset</h4><pre>_, axarr = plt.subplots(nrows=5, ncols=5, figsize=(20, 20))</pre><pre>sample_keys = list(train_dataset.data.keys())</pre><pre>for a in range(5):<br>    for b in range(5):<br>        temp_image = train_dataset.data[sample_keys[a]][b]<br>        temp_image = np.stack((temp_image[:, :, 0],) * 3, axis=2)<br>        temp_image *= 255<br>        temp_image = np.clip(temp_image, 0, 255).astype(&quot;uint8&quot;)<br>        if b == 2:<br>            axarr[a, b].set_title(&quot;Class : &quot; + sample_keys[a])<br>        axarr[a, b].imshow(temp_image, cmap=&quot;gray&quot;)<br>        axarr[a, b].xaxis.set_visible(False)<br>        axarr[a, b].yaxis.set_visible(False)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cS_3lWpeH5nFugVh.png" /></figure><h4>Building the model</h4><pre>def conv_bn(x):<br>    x = layers.Conv2D(filters=64, kernel_size=3, strides=2, padding=&quot;same&quot;)(x)<br>    x = layers.BatchNormalization()(x)<br>    return layers.ReLU()(x)<br></pre><pre>inputs = layers.Input(shape=(28, 28, 1))<br>x = conv_bn(inputs)<br>x = conv_bn(x)<br>x = conv_bn(x)<br>x = conv_bn(x)<br>x = layers.Flatten()(x)<br>outputs = layers.Dense(classes, activation=&quot;softmax&quot;)(x)<br>model = keras.Model(inputs=inputs, outputs=outputs)<br>model.compile()<br>optimizer = keras.optimizers.SGD(learning_rate=learning_rate)</pre><h4>Training the model</h4><pre>training = []<br>testing = []<br>for meta_iter in range(meta_iters):<br>    frac_done = meta_iter / meta_iters<br>    cur_meta_step_size = (1 - frac_done) * meta_step_size<br>    # Temporarily save the weights from the model.<br>    old_vars = model.get_weights()<br>    # Get a sample from the full dataset.<br>    mini_dataset = train_dataset.get_mini_dataset(<br>        inner_batch_size, inner_iters, train_shots, classes<br>    )<br>    for images, labels in mini_dataset:<br>        with tf.GradientTape() as tape:<br>            preds = model(images)<br>            loss = keras.losses.sparse_categorical_crossentropy(labels, preds)<br>        grads = tape.gradient(loss, model.trainable_weights)<br>        optimizer.apply_gradients(zip(grads, model.trainable_weights))<br>    new_vars = model.get_weights()<br>    # Perform SGD for the meta step.<br>    for var in range(len(new_vars)):<br>        new_vars[var] = old_vars[var] + (<br>            (new_vars[var] - old_vars[var]) * cur_meta_step_size<br>        )<br>    # After the meta-learning step, reload the newly-trained weights into the model.<br>    model.set_weights(new_vars)<br>    # Evaluation loop<br>    if meta_iter % eval_interval == 0:<br>        accuracies = []<br>        for dataset in (train_dataset, test_dataset):<br>            # Sample a mini dataset from the full dataset.<br>            train_set, test_images, test_labels = dataset.get_mini_dataset(<br>                eval_batch_size, eval_iters, shots, classes, split=True<br>            )<br>            old_vars = model.get_weights()<br>            # Train on the samples and get the resulting accuracies.<br>            for images, labels in train_set:<br>                with tf.GradientTape() as tape:<br>                    preds = model(images)<br>                    loss = keras.losses.sparse_categorical_crossentropy(labels, preds)<br>                grads = tape.gradient(loss, model.trainable_weights)<br>                optimizer.apply_gradients(zip(grads, model.trainable_weights))<br>            test_preds = model.predict(test_images)<br>            test_preds = tf.argmax(test_preds).numpy()<br>            num_correct = (test_preds == test_labels).sum()<br>            # Reset the weights after getting the evaluation accuracies.<br>            model.set_weights(old_vars)<br>            accuracies.append(num_correct / classes)<br>        training.append(accuracies[0])<br>        testing.append(accuracies[1])<br>        if meta_iter % 100 == 0:<br>            print(<br>                &quot;batch %d: train=%f test=%f&quot; % (meta_iter, accuracies[0], accuracies[1])<br>            )</pre><h3>Output</h3><pre>batch 0: train=0.000000 test=0.600000<br>batch 100: train=0.600000 test=0.800000<br>batch 200: train=1.000000 test=0.600000<br>batch 300: train=0.600000 test=0.800000<br>batch 400: train=0.800000 test=1.000000<br>batch 500: train=1.000000 test=0.600000<br>batch 600: train=1.000000 test=1.000000<br>batch 700: train=1.000000 test=1.000000<br>batch 800: train=1.000000 test=0.600000<br>batch 900: train=1.000000 test=1.000000<br>batch 1000: train=0.800000 test=1.000000<br>batch 1100: train=1.000000 test=0.600000<br>batch 1200: train=0.800000 test=1.000000<br>batch 1300: train=0.800000 test=1.000000<br>batch 1400: train=1.000000 test=1.000000<br>batch 1500: train=0.800000 test=1.000000<br>batch 1600: train=1.000000 test=1.000000<br>batch 1700: train=1.000000 test=0.800000<br>batch 1800: train=1.000000 test=1.000000<br>batch 1900: train=0.800000 test=1.000000</pre><p>As we can see here our model is gradually getting better at the new test set and adapting to a new classification problem. Thus we see that the few-shot learning through Reptile gives you definite results in fewer computations.</p><h3>Conclusion</h3><ul><li>The Reptile Algorithm learns the optimal set of initial parameters for adapting to new classification tasks in a minimum number of shots or sampled data going through less number of training rounds making it the most pre-eminent choice of the few-shot Learning techniques.</li><li>It is more involving for a Machine Learning apprentice and a detrimental step to understanding other complex learning methods which apply the teacher-student inner-outer loop.</li><li>Has more space for research since it’s one of the few fast-responding learning techniques with fewer number of samples given.</li><li>Building more generalized models which can learn to solve whole arrays of tasks, making it more versatile and dependable.</li></ul><h3><strong>Source Code:</strong></h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f81fe5e4f3350aee0086ac997d72a733/href">https://medium.com/media/f81fe5e4f3350aee0086ac997d72a733/href</a></iframe><h3>Credits:</h3><p>The above article is sponsored by <a href="https://www.vevesta.com/?utm_source=Medium-MAML"><strong><em>Vevesta</em></strong></a><em>.</em></p><p><a href="https://www.vevesta.com/?utm_source=Medium-MAML"><strong><em>Vevesta</em></strong></a><strong><em>: </em></strong>Your Machine Learning Team’s Feature and Technique Dictionary — Accelerate your Machine learning project by using features, techniques and projects used by your peers</p><p><em>The next article will be published at weekly intervals.</em> I<em>f you enjoyed my article, simply send me some claps and feedback at joshua@vevesta.com or follow us on Twitter at </em>@vevesta1<em> for regular updates on my articles.</em></p><p><em>100 early birds who login into </em><a href="https://www.vevesta.com/?utm_source=Medium-MAML"><strong><em>Vevesta</em></strong></a><em> will get free subscription for 3 months</em></p><h3>References:</h3><ol><li><a href="https://www.vevesta.com/blog/22-Few-Shot-Learning?utm_source=Medium-MAML">Few-Shot Technique With Reptile — Vevesta</a></li><li><a href="https://arxiv.org/abs/1803.02999">On First-Order Meta-Learning Algorithms</a></li><li><a href="https://arxiv.org/pdf/1703.03400.pdf">Model-Agnostic Meta-Learning for Fast Adaptation of Deep Networks</a></li><li><a href="https://keras.io/examples/vision/reptile/">Few-shot classification of the Omniglot dataset using Reptile.</a></li><li><a href="https://towardsdatascience.com/icml-2018-advances-in-transfer-multitask-and-semi-supervised-learning-2a15ef7208ec">Towards Data Science</a></li><li><a href="http://transfer-learning-machine-learning/">transfer-learning-machine-learning</a></li><li><a href="https://www.youtube.com/watch?v=qEHZ1DeBF-M&amp;ab_channel=ConnorShorten">Few-Shot Learning with Reptile — Keras Code Examples</a></li><li><a href="https://vevesta.substack.com/p/why-should-you-be-looking-at-few">Few-Shot Technique With Reptile — Substack</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2614576600d3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Layman’s Guide to Lottery Ticket Hypothesis In Neural Network]]></title>
            <link>https://medium.com/@joshua_86438/laymans-guide-to-lottery-ticket-hypothesis-in-neural-network-5f3c77940309?source=rss-9039ff514ab8------2</link>
            <guid isPermaLink="false">https://medium.com/p/5f3c77940309</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Joshua Raj]]></dc:creator>
            <pubDate>Sat, 20 Aug 2022 17:25:55 GMT</pubDate>
            <atom:updated>2022-09-12T19:35:45.950Z</atom:updated>
            <content:encoded><![CDATA[<h4>Finding lighter trainable subnetworks from fully-connected feed-forward networks with similar performance</h4><h3>Idea behind Lottery Ticket Hypothesis</h3><p>Imagine we have a fully functioning car that can only be used by a single person but its too cost expensive and needs heavy maintenance so you trim and tinker it down and use the cores of the car to make a vehicle that carries the essence and materials of the car and by doing so is more lightweight, faster and therefore is more functionally efficient, which you couldn’t do before but by using a special technique you’re able to accomplish this transformation that is the idea behind the lottery ticket hypothesis.</p><h3>Definition Of Lottery Ticket Hypothesis</h3><p>“A randomly initialized dense neural network contains a subnetwork that is initialized such that when trained in isolation it can match the test accuracy of the original network after training for at most the same number of iterations.”</p><h3>Introduction to Lottery Ticket Hypothesis</h3><p>The work by<a href="https://arxiv.org/pdf/1803.03635v5.pdf"> Frankle and Carbin (2018)</a> has presented a surprising phenomenon: pruned neural networks can be trained to achieve performance as compared with the unpruned neural network when resetting their weights to their initial values.</p><p>It’s found that after the application these pruning techniques automatically uncover trainable subnetworks from fully-connected feed-forward networks. We call these trainable subnetworks, “winning tickets” since those that we find have won the initialization lottery with a combination of weights and connections capable of learning. These winning tickets when trained in isolation can reach test accuracy comparable to the original network in a similar number of iterations. However, what is observed is that the sparse architectures produced by pruning are quite tough to train from the start. to understand fully Lottery Ticket Hypothesis we must first know what is pruning and their types.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/0*svrZuwzGw55qPPxQ.png" /></figure><p><a href="https://towardsdatascience.com/saga-of-the-lottery-ticket-hypothesis-af30091f5cb">Saga of the Lottery Ticket Hypothesis</a></p><h3>Pruning</h3><p>In theory, the pruned subnetwork should perform similarly to the dense network, though this may not be the case if a large number of parameters or weights are removed. Thus, the goal of the pruning process is to find and remove parameters that do not significantly affect the performance of the network.</p><p>In total there are four types of pruning namely</p><ol><li>Structured and Unstructured,</li><li>Scoring,</li><li>Iterative and fine-tuning,</li><li>Scheduling.</li></ol><p>In the lottery ticket hypothesis, we’ll only be needing structured, unstructured, and iterative pruning so we must take a deeper look into them.</p><h3>Types of pruning</h3><h4>Structured and Unstructured Pruning:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/867/0*p_CprYvh2__5OGIf.png" /></figure><p><a href="https://www.researchgate.net/figure/Different-types-of-pruning-algorithm-Unstructured-pruning-removes-any-unimportant_fig3_342989407">A Beginners Guide to Neural Network Pruning</a></p><p>In the Unstructured pruning approach, there are no limitations to how one wants to prune the neural network. The liberty to alter each or all weights and can remove them completely, making the pruning process more experimental. Since only the weights are varied in the neural network this process is also called Weight Pruning. This results in a sparse neural network. On the contrary, in the structured pruning method entire group of weight, or as we call it neurons in a feed-forward network is removed altogether. This is also known as Unit/Neuron Pruning and the resultant is a dense neural network.</p><p>Both the methods are widely applied in neural networks and each comes with a trade of its own but arguably unstructured pruning is considered to be preferable since it places no restrictions on the order of pruning.</p><h4>Iterative Pruning:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/896/0*tMnx-e6Be3JNY3ns.png" /></figure><p><a href="https://towardsdatascience.com/saga-of-the-lottery-ticket-hypothesis-af30091f5cb">Saga of the Lottery Ticket Hypothesis</a></p><p>Some methods prune the desired amount all at once, which is often referred to as One-shot Pruning. The network is trained all at once and bulk <em>p</em>% of the weights are pruned off of the network. certain systems, known as Iterative Pruning, repeat the process of pruning the network to some extent and retraining it until the desired pruning rate is obtained so for each round it prunes <em>p</em>¹/<em>n</em>% of the parameters, trains, and reprunes repeating this <em>n</em> times. It’s used for approaches that require fine-tuning, it is most typical to continue training the network with the weights that were trained before pruning. Another method could be re-initializing the network with the same resultant weights. Now that we have understood the basic idea about pruning let’s look at the theory behind the Lottery ticket hypothesis.</p><h3>Limitations of Pruning and How Lottery Ticket Hypothesis Overcame The Barrier-</h3><p>Originally pruning is a common practice, it has been used to decrease the storage size of networks, and decrease the energy consumption and the inference time but the problem which arose was that these pruned weight networks couldn’t be trained from scratch or with random parameters. Hence once pruned the network could only be fine-tuned with no chance of experimentation as the network couldn’t be trained from scratch but that was the limitation that was overcome by the lucky ticket hypothesis.</p><p>The initialization is the key to training these pruned networks from scratch. Once the winning ticket which is our subnetwork with peak required conditions is found the same initialization parameters are maintained. In this way, the winning ticket; both its structure and its weights; exists within the randomly-initialized dense network. Thus, this subnetwork is shown to have won the “initialization lottery”, as it can be trained from scratch to higher accuracy than that of a fully-trained dense network or randomly re-initialized subnetwork with the same structure. Their connections have initial weights that make training particularly effective.</p><p>Let’s suppose we have with us a neural network with its own initial parameters and after training all the way to convergence it will have a different set of weight and parameters. Now we prune the neural network to find the winning ticket. Once the winning ticket is found to retrain this subnetwork we’ll have to reinitialize this pruned network with the same parameter the network had when it started out. By this we ensure that we have the same structure and initial weights helping us to retrain from scratch and reach better accuracy as the outcome. These lottery tickets tend to be 10% to 20% of the original size of the network.</p><h3>The Four steps to identify the Winning ticket:</h3><p>1. Randomly initialize a neural network.</p><p>2. Train the network for a number of iterations, arriving at parameters at the respected number of iterations.</p><p>3. Prune the parameters currently attained, creating a mask.</p><p>4. Reset the remaining parameters to their original values, creating the winning ticket we require for retraining the pruned network.</p><p>Conditions to be met: Randomly re-initializing winning tickets prior to training is damaging to performance. Hence rewinding parameters to their initial, random values is essential to matching or exceeding dense network performance.</p><h3>Summary:</h3><ul><li>Neural network pruning techniques can reduce the parameter counts of trained networks by over 90%, decreasing storage requirements and improving the computational performance of inference without compromising accuracy.</li><li>We consistently find winning tickets that are less than 10–20% of the size of several fully-connected and convolutional feed-forward architectures for MNIST and CIFAR10. Above this size, the winning tickets that we find learn faster than the original network and reach higher test accuracy.</li><li>Winning tickets are shown to have better generalization properties than the original dense network in many cases.</li></ul><h3>Conclusion:</h3><ul><li>It improves training performance and also helps to accelerate the training of neural networks.</li><li>There is a massive speed storage improvement.</li><li>It helps to design better networks by getting more areas for experimentation.</li><li>Improve theoretical understanding of neural networks.</li></ul><h3>Credits:</h3><p><em>Subscribe to receive a copy of our newsletter directly delivered to your inbox.</em></p><p>The above article is sponsored by <a href="https://www.vevesta.com/?utm_source=Medium-LotteryTicket"><strong><em>Vevesta</em></strong></a><em>.</em></p><p><a href="https://www.vevesta.com/?utm_source=Medium-LotteryTicket"><strong><em>Vevesta</em></strong></a><strong><em>: </em></strong>Your Machine Learning Team’s Feature and Technique Dictionary — Accelerate your Machine learning project by using features, techniques and projects used by your peers</p><p><em>100 early birds who login into </em><a href="https://www.vevesta.com/?utm_source=Medium-LotteryTicket"><strong><em>Vevesta</em></strong></a><em> will get free subscription for 3 months</em></p><h3>References:</h3><ol><li><a href="https://www.vevesta.com/blog/20-Lottery-Ticket-Hypothesis?utm_source=Medium-LotteryTicket">Lottery Ticket Hypothesis — Vevesta</a></li><li><a href="https://arxiv.org/abs/1803.03635">The Lottery Ticket Hypothesis: Finding Sparse, Trainable Neural Networks</a>.</li><li><a href="https://analyticsindiamag.com/a-beginners-guide-to-neural-network-pruning/">A Beginners Guide to Neural Network Pruning</a>.</li><li><a href="http://proceedings.mlr.press/v119/malach20a/malach20a.pdf">Proving the Lottery Ticket Hypothesis: Pruning is All You Need</a>.</li><li><a href="https://towardsdatascience.com/saga-of-the-lottery-ticket-hypothesis-af30091f5cb">Saga of the Lottery Ticket Hypothesis</a>.</li><li><a href="https://www.researchgate.net/figure/Different-types-of-pruning-algorithm-Unstructured-pruning-removes-any-unimportant_fig3_342989407">Research gate</a></li><li><a href="https://vevesta.substack.com/p/laymans-guide-to-lottery-ticket-hypothesis?utm_source=Medium-LotteryTicket">Lottery Ticket Hypothesis — Substack</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5f3c77940309" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>