<?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 Salmen Zouari on Medium]]></title>
        <description><![CDATA[Stories by Salmen Zouari on Medium]]></description>
        <link>https://medium.com/@salmenzouari?source=rss-2c5a4e892d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*7LWzj1jEemsMZQpc</url>
            <title>Stories by Salmen Zouari on Medium</title>
            <link>https://medium.com/@salmenzouari?source=rss-2c5a4e892d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 14:45:32 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@salmenzouari/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[Automating Data Augmentation]]></title>
            <link>https://salmenzouari.medium.com/automating-data-augmentation-f2bdf1f1c0da?source=rss-2c5a4e892d------2</link>
            <guid isPermaLink="false">https://medium.com/p/f2bdf1f1c0da</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[data-augmentation]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Salmen Zouari]]></dc:creator>
            <pubDate>Wed, 11 Aug 2021 17:43:22 GMT</pubDate>
            <atom:updated>2021-08-11T17:43:22.471Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*ae1tW5ngf1zhPRyh7aaM1Q.png" /></figure><h3>Why Data Augmentation?</h3><p>Modern machine learning models, such as deep neural networks, may have billions of parameters and require massive labeled training datasets — which are often not available. The technique of artificially expanding labeled training datasets — known as data augmentation — has quickly become critical for combating this data scarcity problem. Today, data augmentation is used as a secret sauce in nearly every state-of-the-art model for image classification, and is becoming increasingly common in other modalities such as natural language understanding as well. The goal of this blog post is to provide an overview of recent efforts in this exciting research area.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uZyvnu5f5Hk2m1_M.png" /><figcaption>Figure 1. Heuristic data augmentations apply a deterministic sequence of transformation functions tuned by human experts.The augmented data will be used for training downstream models.</figcaption></figure><p>Heuristic data augmentation schemes often rely on the composition of a set of simple transformation functions (TFs) such as rotations and flips (see Figure 1). When chosen carefully, data augmentation schemes tuned by human experts can improve model performance. However, such heuristic strategies in practice can cause large variances in end model performance, and may not produce augmentations needed for state-of-the-art models.</p><h3>The Open Challenges in Data Augmentation</h3><p>The limitations of conventional data augmentation approaches reveal huge opportunities for research advances. Below we summarize a few challenges that motivate some of the works in the area of data augmentation.</p><ul><li>From <strong>manual</strong> to <strong>automated</strong> search algorithms: As opposed to performing suboptimal manual search, how can we design learnable algorithms to find augmentation strategies that can outperform human-designed heuristics?</li><li>From <strong>practical</strong> to <strong>theoretical</strong> understanding: Despite the rapid progress of creating various augmentation approaches pragmatically, understanding their benefits remains a mystery because of a lack of analytic tools. How can we theoretically understand various data augmentations used in practice?</li><li>From <strong>coarse-grained</strong> to <strong>fine-grained</strong> model quality assurance: While most existing data augmentation approaches focus on improving the overall performance of a model, it is often imperative to have a finer-grained perspective on critical subpopulations of data. When a model exhibits inconsistent predictions on important subgroups of data, how can we exploit data augmentations to mitigate the performance gap in a prescribed way?</li></ul><p>In this blog, we will describe ideas and recent research works leading the way to overcome these challenges above.</p><h3>Practical Methods of Learnable Data Augmentations</h3><p>Learnable data augmentation is promising, in that it allows us to search for more powerful parameterizations and compositions of transformations. Perhaps the biggest difficulty with automating data augmentation is how to search over the space of transformations. This can be prohibitive due to the large number of transformation functions and associated parameters in the search space. How can we design learnable algorithms that explore the space of transformation functions efficiently and effectively, and find augmentation strategies that can outperform human-designed heuristics? In response to the challenge, we highlight a few recent methods below.</p><p><strong>TANDA: Transformation Adversarial Networks for Data Augmentations</strong></p><p>To address this problem, TANDA (<a href="https://arxiv.org/abs/1709.01643">Ratner et al. 2017</a>) proposes a framework to learn augmentations, which models data augmentations as sequences of Transformation Functions (TFs) provided by users. For example, these might include <em>“rotate 5 degrees”</em> or <em>“shift by 2 pixels”</em>. At the core, this framework consists of two components (1) <strong>learning a TF sequence generator</strong> that results in useful augmented data points, and (2) <strong>using the sequence generator</strong> to augment training sets for a downstream model. In particular, the TF sequence generator is trained to produce realistic images by having to fool a discriminator network, following the GANs framework (<a href="https://arxiv.org/abs/1406.2661">Goodfellow et al. 2014</a>). The underlying assumption here is that the transformations would either lead to realistic images, or indistinguishable garbage images that are off the manifold. As shown in Figure 1, the objective for the generator is to produce sequences of TFs such that the augmented data point can fool the discriminator; whereas the objective for the discriminator is to produce values close to 1 for data points in the original training set and values close to 0 for augmented data points.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zXTDGCQHjXbUJAZu.png" /><figcaption>Figure 2. Automating data augmentation with TANDA (Ratner et al. 2017). A TF sequence generator is trained adversarially to produce augmented images that are realistic compared to training data.</figcaption></figure><p><strong>AutoAugment and Further Improvement</strong> Using a similar framework, AutoAugment (<a href="https://arxiv.org/abs/1805.09501">Cubuk et al. 2018</a>) developed by Google demonstrated state-of-the-art performance using learned augmentation policies. In this work, a TF sequence generator learns to directly optimize for validation accuracy on the end model. Several subsequent works including RandAugment (<a href="https://arxiv.org/abs/1909.13719">Cubuk et al. 2019</a>) and Adversarial AutoAugment (<a href="https://arxiv.org/abs/1912.11188">Zhang et al. 2019</a>) have been proposed to reduce the computational cost of AutoAugment, establishing new state-of-the-art performance on image classification benchmarks.</p><h3>Theoretical Understanding of Data Augmentations</h3><p>Despite the rapid progress of practical data augmentation techniques, precisely understanding their benefits remains a mystery. Even for simpler models, it is not well-understood how training on augmented data affects the learning process, the parameters, and the decision surface. This is exacerbated by the fact that data augmentation is performed in diverse ways in modern machine learning pipelines, for different tasks and domains, thus precluding a general model of transformation. How can we theoretically characterize and understand the effect of various data augmentations used in practice? To address this challenge, our lab has studied data augmentation from a kernel perspective, as well as under a simplified linear setting.</p><p><strong>Data Augmentation As a Kernel</strong></p><p><a href="http://proceedings.mlr.press/v97/dao19b/dao19b.pdf">Dao et al. 2019</a> developed a theoretical framework by modeling data augmentation as a Markov Chain, in which augmentation is performed via a random sequence of transformations, akin to how data augmentation is performed in practice. We show that the effect of applying the Markov Chain on the training dataset (combined with a k-nearest neighbor classifier) is akin to using a kernel classifier, where the kernel is a function of the base transformations.</p><p>Built on the connection between kernel theory and data augmentation, Dao et al. 2019 show that a kernel classifier on augmented data approximately decomposes into two components: (i) an averaged version of the transformed features, and (ii) a data-dependent variance regularization term. This suggests a more nuanced explanation of data augmentation — namely, that it improves generalization both by inducing invariance and by reducing model complexity. Dao et al. 2019 validate the quality of our approximation empirically, and draw connections to other generalization-improving techniques, including recent work on invariant learning (<a href="https://papers.nips.cc/paper/8199-learning-invariances-using-the-marginal-likelihood">van der Wilk et al. 2018</a>) and robust optimization (<a href="https://papers.nips.cc/paper/6890-variance-based-regularization-with-convex-objectives.pdf">Namkoong &amp; Duchi, 2017</a>).</p><p><strong>Data Augmentation Under A Simplified Linear Setting</strong></p><p>One limitation of the above works is that it is challenging to pin down the effect of applying a particular transformation on the resulting kernel. Furthermore, it is not yet clear how to apply data augmentation efficiently on kernel methods to get comparable performance to neural nets. In more recent work, we consider a simpler linear setting that is capable of modeling a wide range of linear transformations commonly used in image augmentation, as shown in Figure 3.</p><p><strong>Theoretical Insights</strong>. We offer several theoretical insights by considering an over-parametrized linear model, where the training data lies in a low-dimensional subspace. We show that label-invariant transformations can add new information to the training data, and estimation error of the ridge estimator can be reduced by adding new points that are outside the span of the training data. In addition, we show that mixup (<a href="https://arxiv.org/pdf/1710.09412.pdf">Zhang et al., 2017</a> can play an effect of regularization through shrinking the weight of the training data relative to the L2 regularization term on the training data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*MfEVFj-2Rk2A3A6J.png" /><figcaption>Figure 3. Illustration of common linear transformations applied in data augmentation.</figcaption></figure><p><strong>Theory-inspired New State-of-the-art</strong>. One insight from our theoretical investigation is that different (compositions of) transformations show very different end performance. Inspired by this observation, we’d like to make use of the fact that certain transformations are better performing than others. We propose an uncertainty-based random sampling scheme which, among the transformed data points, picks those with the highest losses, i.e. those “providing the most information” (see Figure 4). Our sampling scheme achieves higher accuracy by finding more useful transformations compared to RandAugment on three different CNN architectures, establishing new state-of-the-art performance on common benchmarks. For example, our method outperforms RandAugment by <strong>0.59</strong>% on CIFAR-10 and <strong>1.24</strong>% on CIFAR-100 using Wide-ResNet-28–10. Please check out our full paper <a href="http://stanford.edu/~senwu/publications/data_augmentation_draft.pdf">here</a>. Our code will be released soon for you to try out!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jmjQxvV_Cct_Jief.png" /><figcaption>Figure 4. Uncertainty-based random sampling scheme for data augmentation. Each transformation function is randomly sampled from a set of pre-specified operations. We select among the transformed data points with highest loss for end model training.</figcaption></figure><h3>New Direction: Data Augmentations for Model Patching</h3><p>Most machine learning research carried out today is still solving fixed tasks. However, in the real world, machine learning models in deployment can fail due to unanticipated changes in data distribution. This raises the concerning question of how we can move from model building to model maintenance in an adaptive manner. In our latest work, we propose model patching — the first framework that exploits data augmentation to mitigate the performance issues of a flawed model in deployment.</p><p><strong>A Medical Use Case of Model Patching</strong></p><p>To provide a concrete example, in skin cancer detection, researchers have shown that standard classifiers have drastically different performance on two subgroups of the cancerous class, due to the classifier’s association between colorful bandages with benign images (see Figure 5, left). This subgroup performance gap has also been studied in parallel research from our group (<a href="https://arxiv.org/abs/1909.12475">Oakden-Rayner et al., 2019</a>), and arises due to classifier’s reliance on subgroup-specific features, e.g. colorful bandages.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jonsJkkiWtlgNx85.png" /><figcaption>Figure 5: A standard model trained on a skin cancer dataset exhibits a subgroup performance gap between images of malignant cancers with and without colored bandages. GradCAM illustrates that the vanilla model spuriously associates the colored spot with benign skin lesions. With model patching, the malignancy is predicted correctly for both subgroups.</figcaption></figure><p>In order to fix such flaws in a deployed model, domain experts have to resort to manual data cleaning to erase the differences between subgroups, e.g. removing markings on skin cancer data with Photoshop (<a href="https://www.ncbi.nlm.nih.gov/pubmed/31411641">Winkler et al. 2019</a>), and retrain the model with the modified data. This can be extremely laborious! Can we somehow learn transformations that allow augmenting examples to balance population among groups in a prescribed way? This is exactly what we are addressing through this new framework of model patching.</p><p><strong>CLAMP: Class-conditional Learned Augmentations for Model Patching</strong></p><p>The conceptual framework of model patching consists of two stages (as shown in Figure 6).</p><ul><li><strong>Learn inter-subgroup transformations</strong> between different subgroups. These transformations are class-preserving maps that allow semantically changing a datapoint’s subgroup identity (e.g. add or remove colorful bandages).</li><li><strong>Retrain to patch the model</strong> with augmented data, encouraging the classifier to be robust to their variations.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gvdB11aH3A2botHG.png" /><figcaption>Figure 6: Model Patching framework with data augmentation. The highlighted box contains samples from a class with differing performance between subgroups A and B. Conditional generative models are trained to transform examples from one subgroup to another (A-&gt;B and B-&gt;A) respectively.</figcaption></figure><p>We propose CLAMP, an instantiation of our first end-to-end model patching framework. We combine a novel consistency regularizer with a robust training objective that is inspired by recent work of Group Distributionally Robust Optimization (GDRO, <a href="https://arxiv.org/abs/1911.08731">Sagawa et al. 2019</a>). We extend GDRO to a class-conditional training objective that jointly optimizes for the worst-subgroup performance in each class. CLAMP is able to balance the performance of subgroups within each class, reducing the performance gap by up to <strong>24</strong>x. On a skin cancer detection dataset ISIC, CLAMP improves robust accuracy by <strong>11.7</strong>% compared to the robust training baseline. Through visualization, we also show in Figure 5 that CLAMP successfully removes the model’s reliance on the spurious feature (colorful bandages), shifting its attention to the skin lesion — true feature of interest.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f2bdf1f1c0da" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Trains a Convolutional Neural Network to classify the CIFAR10 dataset:]]></title>
            <link>https://salmenzouari.medium.com/trains-a-convolutional-neural-network-to-classify-the-cifar10-dataset-10cb0130f936?source=rss-2c5a4e892d------2</link>
            <guid isPermaLink="false">https://medium.com/p/10cb0130f936</guid>
            <category><![CDATA[cifar-10]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[convolutional-network]]></category>
            <dc:creator><![CDATA[Salmen Zouari]]></dc:creator>
            <pubDate>Thu, 18 Feb 2021 13:04:12 GMT</pubDate>
            <atom:updated>2021-02-18T13:04:12.012Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*hk3JlQa8gd4ZnpKGXwv8OA.jpeg" /></figure><h3>Abstract</h3><p>In this blog post we will provide a guide through for transfer learning with the main aspects to take into account in the process, some tips and an example implementation in Keras using ResNet50 as the trained model. The task is to transfer the learning of a ResNet50 trained with Imagenet to a model that identify images from CIFAR-10 dataset. Several methods were tested to achieve a greater accuracy which we provide to show the variety of options for a training. However with the final model of this blog we get an accuracy of 96% on test set.</p><h3>Introduction</h3><p>Learning something new takes time and practice but we find it easy to do similar tasks. This is thanks to human association involved in learning. We have the capability to identify patterns from previous knowledge an apply it into new learning.</p><p>When we meet a person than is faster or better than us in something like a video game or coding it is almost certain that he has do it before or there is an association with a previous similar activity.</p><p>If we know how to ride a bike, we don’t need to learn from zero how to ride a motorbike. If we know how to play football, we don’t need to learn from zero how to play futsal. If we know how to play the piano, we don’t need to learn from zero how to play another instrument.</p><p>The same is applicable to machines, if we train a model with a database, it’s not necessary to retrain from zero all the model to adjust to a new similar dataset. Both Imagenet and CIFAR-10 have images that can train a model to classify images. Then, it is very promising if we can save time training a model (because it can really take long time) and start using the weights of a previously trained model. We are going through this concept of transfer learning with all what you need to also build a model on your own.</p><h3>Materials and Methods</h3><p><strong>Setting our environment</strong></p><p>We are going to use Keras which is an open source library written in Python for neural networks. We work over it with tensorflow in a <a href="https://colab.research.google.com/">Google Colab</a>, a Jupyter notebook environment that runs in the cloud.</p><p>The first thing we do is importing the libraries needed with the line of code below. Running the version as 1.x is optional, without that first line it will run the last version of tensorflow for Colab. We also use numpy and a function of tensorflow but depending on how you build your own model is not necessary to import them.</p><pre>%tensorflow_version 1.ximport tensorflow.keras as K</pre><p>Training a model uses a lot of resources so we recommend using a <a href="https://colab.research.google.com/notebooks/gpu.ipynb">GPU</a> configuration in the Colab. This will speed up the process and allow more testing. We will talk about some other ways to improve computation soon.</p><p><strong>Database</strong></p><p>CIFAR-10 is commonly used in Deep Learning for testing models of Image Classification. It has 60,000 color images comprising of 10 different categories. The image size is 32x32 and the dataset has 50,000 training images and 10,000 test images. One can find the CIFAR-10 dataset <a href="https://www.cs.toronto.edu/~kriz/cifar.html">here.</a></p><p>The categories are airplane, automobile, beer, cat, deer, dog, frog, horse, ship, truck. We can take advantage of the fact that these categories and a lot more are into the Imagenet collection.</p><p>To load a database with Keras, we use:</p><pre>K.datasets.cifar10.load_data()</pre><p><strong>Preprocess</strong></p><p>Now that the data is loaded, we are going to build a preprocess function for the data. We have X as a numpy array of shape (m, 32, 32, 3) where m is the number of images, 32 and 32 the dimensions, and 3 is because we use color images (RGB). We have a set of X for training and a set of X for validation. Y is a numpy array of shape (m, ) that we want to be our labels. Since we work with 10 different categories, we make use of <a href="https://www.youtube.com/watch?v=v_4KWmkwmsU">one-hot encoding</a> with a function of Keras that makes our Y into a shape of (m, 10). That also applies for the validation.</p><p>As we said before, we are going to use ResNet50 but there are also many other <a href="https://keras.io/api/applications/">models available</a> with pre-trained weights such as <a href="https://keras.io/api/applications/vgg/#vgg16-function">VGG16</a>, ResNet101, <a href="https://keras.io/api/applications/inceptionv3">InceptionV3</a> and DenseNet121. Each one has its own preprocess function for the inputs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/621/0*jsibWuEGOJcvDws5.png" /><figcaption>Preprocess data using predefined function from Keras</figcaption></figure><p>Next, we are going to call our function with the parameters loaded from the CIFAR10 database. It’s important to get to know your data to monitor the steps and know how to build your model. Let’s print the shapes of our x_train and y_train before and after the preprocessing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*4nrJc8pcgtgEVh5zJrvh3g.png" /></figure><p>Here we unpack both train and test variables directly and bring them to the preprocess function.</p><pre>((50000, 32, 32, 3), (50000, 1))<br>((50000, 32, 32, 3), (50000, 10))</pre><h3>Using weights of a trained neural network</h3><p>A pretrained model from the Keras Applications has the advantage of allow you to use weights that are already calibrated to make predictions. In this case, we use the weights from Imagenet and the network is a ResNet50. The option <strong>include_top=False </strong>allows feature extraction by removing the last dense layers. This let us control the output and input of the model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/504/1*AJh9ZErADaF6MkVE-hpSIQ.png" /><figcaption>Using weights of a trained ResNet50</figcaption></figure><p>From this point it all comes to testing and a bit of creativity. The starting point is very advantageous since we have weights that already serve for image classification but since we are using it on a completely new dataset, there is a need for adjustments. Our objective is to build a model that has high accuracy in their classifications. In this case, if an image of a dog is presented, it successfully identifies it as a dog and not as a train, for example.</p><p>Let’s say we want to achieve an accuracy of more than 88% on training data but we also wish that it doesn’t have overfitting. How do we get this? Well at this point our models may diverge, this is where we test what tools we can use for that objective. The important here is to learn about transfer learning and making robust models. We follow an example but we can run with different approaches that we will discuss.</p><p>The two approaches you can take in transfer learning are:</p><ul><li>Feature extraction</li><li>Fine tuning</li></ul><p>This refers on how you use the layers of your pretrained model. We have already a very huge amount of parameters because of the number of layer of the ResNet50 but we have calibrated weights. We can choose to ‘freeze’ those layers (as many as you can) so those values doesn’t change, and by that way saving time and computational cost. However as the dataset is entirely different is not a bad idea to train all the model</p><p>In this case, we ‘freeze’ all layers except for the last block of the ResNet50. The way to do this in Keras is with:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/311/1*4wN39ggconDYIhHThvUpQQ.png" /><figcaption>Set some layers as non-trainable</figcaption></figure><p>We can check that we did it correctly with:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/407/1*Kj5HTVUqo050xn4G-dlw8Q.png" /><figcaption>Print the layers to check which are trainable</figcaption></figure><p>The output is something like this (the are more layer that we omit). <em>False</em> means that the layer is ‘freezed’ or is not trainable and <em>True</em> that when we run our model, the weights are going to be adjusted.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/282/1*bIxaI_EWwUQcq_PI8kv5Ww.png" /></figure><p>Later, we need to connect our pretrained model with the new layers of our model. We can use <strong>global pooling</strong> or a <strong>flatten</strong> layer to connect the dimensions of the previous layers with the new layers. With just a flatten layer and a dense layer with softmax we can perform close the model and start making classification.</p><pre>model = K.models.Sequential()<br>model.add(res_model)<br>model.add(K.layers.Flatten())<br>model.add(K.layers.Dense(10, activation=&#39;softmax&#39;))</pre><p>The final layers are below, you can see the complete code <a href="https://github.com/salmenz/holbertonschool-machine_learning/blob/master/supervised_learning/0x09-transfer_learning/0-transfer.py">here</a>. However we explain some more aspects to improve the model and make a good classification. We present the main aspects taken into account to build the model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/655/1*seBGilY8vBb8xxa9TXXOww.png" /><figcaption>The complete model using a Sequential structure. Note that the variable res_model is the pretrained ResNet50</figcaption></figure><p>We have regularizers to help us avoid overfitting and optimizers to get a faster result. Each of them can also affect our accuracy, so we present what to take into account. The most important are:</p><ul><li>Batch size: It is recommended to use a number of batch size with powers of 2 (8, 16, 32, 64, 128, …) because it fits with the memory of the computer.</li><li>Learning rate: For transfer learning it is recommended a very low learning rate because we don’t want to change too much what is previously learned.</li><li>Number of layers: This depends on how much you relay from the layers of the pretrained model. We found that if we leave all the model for training just a flatten layer and a dense with softmax is enough but since we incorporated the feature extraction it was required more layers at the end.</li><li>Optimization methods: We tested with SGD and RMSprop. SGD with a very low learning required more epochs (30) to complete a razonable training. We used RMSprop with 5 epochs to get our result.</li><li>Regularization methods: To avoid overfitting we used Batch normalization and dropout in-between the dense layers.</li><li>Callbacks: In Keras, we can use callbacks in our model to perform certain actions in the training such as weight saving.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/515/1*y8r8YpE7gTlQZYZbKtcM2g.png" /><figcaption>This callback saves the weights obtained in the training</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/643/1*HKDJ7bHg-lFdqCE9qOVrPw.png" /><figcaption>We save the model in a file called “cifar10.h5”</figcaption></figure><h3>Results</h3><p>We obtained an accuracy of 96% on training set and 94% on validation with 10 epochs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0mu-ca03z54OQVlEk4pCSg.png" /></figure><p>The summary of the model is below. We found that batch normalization and dropout greatly reduces overfitting and it helps get better accuracy on validation set. The method of ‘freezing layers’ allows a faster computation but hits the accuracy so it was necessary to add dense layers at the end. The shape of the layers holds part of the structure of the original ResNet50 like it was a continuation of it but with the features we mentioned.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/559/1*nfMOqZMPL-xfiJyOKJpFrw.png" /></figure><p>For ResNet50 what helped more to achieve a high accuracy was to resize the input from 32 x 32 to 224 x 224. This is because of how the model was constructed which in this sense was not compatible with the dataset but it was easy to solve by fitting it to the original size of the architecture. There was the option of using UpSampling to do this task but we find that the use of Keras layers lambda was way faster.</p><h3>Discussion</h3><p>We confirmed that ResNet50 works best with input images of 224 x 224. As CIFAR-10 have 32 x 32 images, it was necessary to perform a resize. With this adjustment alone, the model can achieve a high accuracy, I think it was the most important for ResNet50.</p><p>A good recommendation when building a model using transfer learning is to first test optimizers to get a low bias and good results in training set, then look for regularizers if you see overfitting over the validation set.</p><p>The discussion over using freezing on the pretrained model continues. It reduces computation time, reduces overffiting but lowers accuracy. When the new dataset is very different from the datased used for training it may be necessary to use more layer for adjustment.</p><p>On the selecting of hyperparameters, it is important for transfer learning to use a low learning rate to take advantage of the weights of the pretrained model. This choice as the optimizer choice (SGD, Adam, RMSprop) will impact the number of epochs needed to get a successfully trained model.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=10cb0130f936" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Regularization Techniques Machine Learning]]></title>
            <link>https://salmenzouari.medium.com/regularization-techniques-machine-learning-be3cd1b0e55c?source=rss-2c5a4e892d------2</link>
            <guid isPermaLink="false">https://medium.com/p/be3cd1b0e55c</guid>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Salmen Zouari]]></dc:creator>
            <pubDate>Thu, 21 Jan 2021 11:57:20 GMT</pubDate>
            <atom:updated>2021-01-21T11:57:20.645Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*QHiWGM7KDb9DjXaX.png" /></figure><p>Have you ever encountered a situation where your machine learning model models the training data exceptionally well but fails to perform well on the testing data i.e. was not able to predict test data? This situation can be dealt with regularization in Machine learning.</p><p>Overfitting happens when a model learns the very specific pattern and noise from the training data to such an extent that it negatively impacts our model’s ability to generalize from our training data to new (“unseen”) data. By noise, we mean the irrelevant information or randomness in a dataset.</p><p>Preventing overfitting is very necessary to improve the performance of our machine learning model.</p><p>Following pointers will be covered in this article and eventually help us solve this problem,</p><ul><li>What is Regularization</li><li>How Does Regularization Work</li><li>Regularization Techniques</li></ul><h3>What is Regularization?</h3><p>In general, regularization means to make things regular or acceptable. This is exactly why we use it for applied machine learning. In the context of machine learning, regularization is the process which regularizes or shrinks the coefficients towards zero. In simple words, regularization discourages learning a more complex or flexible model, to prevent overfitting.</p><h3>How Does Regularization Work?</h3><p>The basic idea is to penalize the complex models i.e. adding a complexity term that would give a bigger loss for complex models. To understand it, let’s consider a simple relation for linear regression. Mathematically, it is stated as below:<br> Y≈ W_0+ W_1 X_1+ W_2 X_(2 )+⋯+W_P X_P</p><p>Where Y is the learned relation i.e. the value to be predicted.<br> X_1,X_(2 ),〖…,X〗_P , are the features deciding the value of Y.<br> W_1,W_(2 ),〖…,W〗_P , are the weights attached to the features X_1,X_(2 ),〖…,X〗_P respectively.<br> W_0 represents the bias.</p><p>Now, in order to fit a model that accurately predicts the value of Y, we require a loss function and optimized parameters i.e. bias and weights.</p><p>The loss function generally used for linear regression is called the residual sum of squares (RSS). According to the above stated linear regression relation, it can be given as:<br> RSS= ∑_(j=1)^m (Y_i-W_0-∑_(i=1)^n W_i X_ji )²</p><p>We can also call RSS as the linear regression objective without regularization.</p><p>Now, the model will learn by the means of this loss function. Based on our training data, it will adjust the weights (coefficients). If our dataset is noisy, it will face overfitting problems and estimated coefficients won’t generalize on the unseen data.</p><p>This is where regularization comes into action. It regularizes these learned estimates towards zero by penalizing the magnitude of coefficients.</p><p>But how it assigns a penalty to the coefficients, let’s explore.</p><h3>Regularization Techniques</h3><h4>L1 Regularization</h4><p>A regression model that uses L1 regularization technique is called <em>Lasso Regression</em>.</p><p>Mathematical formula for L1 Regularization.</p><p>Let’s define a model to see how L1 Regularization works. For simplicity, We define a simple linear regression model Y with one independent variable.</p><p>In this model, W represent Weight, b represent Bias.</p><p><em>W</em>=<em>w</em>1,<em>w</em>2…<em>wnX</em>=<em>x</em>1,<em>x</em>2…<em>xn</em></p><p>and the predicted result is <em>Y</em>ˆ</p><p><em>Y</em>ˆ=<em>w</em>1<em>x</em>1+<em>w</em>2<em>x</em>2+…<em>wnxn</em>+<em>b</em></p><p>Following formula calculates the error without Regularization function</p><p><em>Loss</em>=<em>Error</em>(<em>Y</em>,<em>Y</em>ˆ)</p><p>Following formula calculates the error With L1 Regularization function</p><p><em>Loss</em>=<em>Error</em>(<em>Y</em>−<em>Y</em>ˆ)+<em>λ</em>∑1<em>n</em>|<em>wi</em>|</p><p>Note</p><p>Here, If the value of lambda is Zero then above Loss function becomes Ordinary Least Square whereas very large value makes the coefficients (weights) zero hence it under-fits.</p><p>One thing to note is that |<em>w</em>|</p><p>is differentiable when w!=0 as shown below,</p><p>d|<em>w</em>|d<em>w</em>={1−1<em>w</em>&gt;0<em>w</em>&lt;0</p><p>To understand the Note above,</p><p>Let’s substitute the formula in finding new weights using Gradient Descent optimizer.</p><p><em>wnew</em>=<em>w</em>−<em>η</em>∂<em>L</em>1∂<em>w</em></p><p>When we apply the L1 in above formula it becomes,</p><p><em>wnew</em>=<em>w</em>−<em>η</em>.(<em>Error</em>(<em>Y</em>,<em>Y</em>ˆ)+<em>λ</em>d|<em>w</em>|d<em>w</em>)={<em>w</em>−<em>η</em>.(<em>Error</em>(<em>Y</em>,<em>Y</em>ˆ)+<em>λ</em>)<em>w</em>−<em>η</em>.(<em>Error</em>(<em>Y</em>,<em>Y</em>ˆ)−<em>λ</em>)<em>w</em>&gt;0<em>w</em>&lt;0</p><p>From the above formula,</p><ul><li>If w is positive, the regularization parameter <em>λ</em></li></ul><p>&gt; 0 will push w to be less positive, by subtracting <em>λ</em></p><ul><li>from w.</li><li>If w is negative, the regularization parameter <em>λ</em></li></ul><p>&lt; 0 will push w to be less negative, by adding <em>λ</em></p><ul><li>to w. hence this has the effect of pushing w towards 0.</li></ul><p>Simple python implementation</p><pre>def update_weights_with_l1_regularization(features, targets, weights, lr,lambda):<br>     &#39;&#39;&#39;<br>     Features:(200, 3)<br>     Targets: (200, 1)<br>     Weights:(3, 1)<br>     &#39;&#39;&#39;<br>     predictions = predict(features, weights)</pre><pre>     #Extract our features<br>     x1 = features[:,0]<br>     x2 = features[:,1]<br>     x3 = features[:,2]</pre><pre>     # Use matrix cross product (*) to simultaneously<br>     # calculate the derivative for each weight<br>     d_w1 = -x1*(targets - predictions)<br>     d_w2 = -x2*(targets - predictions)<br>     d_w3 = -x3*(targets - predictions)</pre><pre>     # Multiply the mean derivative by the learning rate<br>     # and subtract from our weights (remember gradient points in direction of steepest ASCENT)</pre><pre>     weights[0][0] = (weights[0][0] - lr * np.mean(d_w1) - lambda) if weights[0][0] &gt; 0 else (weights[0][0] - lr * np.mean(d_w1) + lambda)<br>     weights[1][0] = (weights[1][0] - lr * np.mean(d_w2) - lambda) if weights[1][0] &gt; 0 else (weights[1][0] - lr * np.mean(d_w2) + lambda)<br>     weights[2][0] = (weights[2][0] - lr * np.mean(d_w3) - lambda) if weights[2][0] &gt; 0 else (weights[2][0] - lr * np.mean(d_w3) + lambda)</pre><pre>     return weights</pre><p>Use Case</p><p>L1 Regularization (or varient of this concept) is a model of choice when the number of features are high, Since it provides sparse solutions. We can get computational advantage as the features with zero coefficients can simply be ignored.</p><h4>L2 Regularization</h4><p>A regression model that uses L2 regularization technique is called <em>Ridge Regression</em>. Main difference between L1 and L2 regularization is, L2 regularization uses “squared magnitude” of coefficient as penalty term to the loss function.</p><p>Mathematical formula for L2 Regularization.</p><p>Let’s define a model to see how L2 Regularization works. For simplicity, We define a simple linear regression model Y with one independent variable.</p><p>In this model, W represent Weight, b represent Bias.</p><p><em>W</em>=<em>w</em>1,<em>w</em>2…<em>wnX</em>=<em>x</em>1,<em>x</em>2…<em>xn</em></p><p>and the predicted result is <em>Y</em>ˆ</p><p><em>Y</em>ˆ=<em>w</em>1<em>x</em>1+<em>w</em>2<em>x</em>2+…<em>wnxn</em>+<em>b</em></p><p>Following formula calculates the error without Regularization function</p><p><em>Loss</em>=<em>Error</em>(<em>Y</em>,<em>Y</em>ˆ)</p><p>Following formula calculates the error With L2 Regularization function</p><p><em>Loss</em>=<em>Error</em>(<em>Y</em>−<em>Y</em>ˆ)+<em>λ</em>∑1<em>nw</em>2<em>i</em></p><p>Note</p><p>Here, if lambda is zero then you can imagine we get back OLS. However, if lambda is very large then it will add too much weight and it leads to under-fitting.</p><p>To understand the Note above,</p><p>Let’s substitute the formula in finding new weights using Gradient Descent optimizer.</p><p><em>wnew</em>=<em>w</em>−<em>η</em>∂<em>L</em>2∂<em>w</em></p><p>When we apply the L2 in above formula it becomes,</p><p><em>wnew</em>=<em>w</em>−<em>η</em>.(<em>Error</em>(<em>Y</em>,<em>Y</em>ˆ)+<em>λ</em>∂<em>L</em>2∂<em>w</em>)=<em>w</em>−<em>η</em>.(<em>Error</em>(<em>Y</em>,<em>Y</em>ˆ)+2<em>λw</em>)</p><p>Simple python implementation</p><pre>def update_weights_with_l2_regularization(features, targets, weights, lr,lambda):<br>     &#39;&#39;&#39;<br>     Features:(200, 3)<br>     Targets: (200, 1)<br>     Weights:(3, 1)<br>     &#39;&#39;&#39;<br>     predictions = predict(features, weights)</pre><pre>     #Extract our features<br>     x1 = features[:,0]<br>     x2 = features[:,1]<br>     x3 = features[:,2]</pre><pre>     # Use matrix cross product (*) to simultaneously<br>     # calculate the derivative for each weight<br>     d_w1 = -x1*(targets - predictions)<br>     d_w2 = -x2*(targets - predictions)<br>     d_w3 = -x3*(targets - predictions)</pre><pre>     # Multiply the mean derivative by the learning rate<br>     # and subtract from our weights (remember gradient points in direction of steepest ASCENT)</pre><pre>     weights[0][0] = weights[0][0] - lr * np.mean(d_w1) - 2 * lambda * weights[0][0]<br>     weights[1][0] = weights[1][0] - lr * np.mean(d_w2) - 2 * lambda * weights[1][0]<br>     weights[2][0] = weights[2][0] - lr * np.mean(d_w3) - 2 * lambda * weights[2][0]</pre><pre>     return weights</pre><p>Use Case</p><p>L2 regularization can address the multicollinearity problem by constraining the coefficient norm and keeping all the variables. L2 regression can be used to estimate the predictor importance and penalize predictors that are not important. One issue with co-linearity is that the variance of the parameter estimate is huge. In cases where the number of features are greater than the number of observations, the matrix used in the OLS may not be invertible but Ridge Regression enables this matrix to be inverted.</p><h4>Dropout</h4><p>Dropout is a regularization technique for reducing overfitting in neural networks by preventing complex co-adaptations on training data</p><p>Dropout is a technique where randomly selected neurons are ignored during training. They are “dropped-out” randomly. This means that their contribution to the activation of downstream neurons is temporally removed on the forward pass and any weight updates are not applied to the neuron on the backward pass.</p><p>Simply put, It is the process of ignoring some of the neurons in particular forward or backward pass.</p><p>Dropout can be easily implemented by randomly selecting nodes to be dropped-out with a given probability (e.g. .1%) each weight update cycle.</p><p>Most importantly Dropout is only used during the training of a model and is not used when evaluating the model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/621/0*Xo9wSfv6THSCKbE0.PNG" /></figure><pre>import numpy as np<br>A = np.arange(20).reshape((5,4))</pre><pre>print(&quot;Given input: &quot;)<br>print(A)</pre><pre>def dropout(X, drop_probability):<br>    keep_probability = 1 - drop_probability<br>    mask = np.random.uniform(0, 1.0, X.shape) &lt; keep_probability<br>    if keep_probability &gt; 0.0:<br>        scale = (1/keep_probability)<br>    else:<br>        scale = 0.0<br>    return mask * X * scale</pre><pre>print(&quot;\n After Dropout: &quot;)<br>print(dropout(A,0.5))</pre><p>output from above code</p><pre>Given input:<br>[[ 0  1  2  3]<br>[ 4  5  6  7]<br>[ 8  9 10 11]<br>[12 13 14 15]<br>[16 17 18 19]]</pre><pre>After Dropout:<br>[[ 0.  2.  0.  0.]<br>[ 8.  0.  0. 14.]<br>[16. 18.  0. 22.]<br>[24.  0.  0.  0.]<br>[32. 34. 36.  0.]]</pre><h4>Data Augmentation</h4><p>Having more data (dataset / samples) is a best way to get better consistent estimators (ML model). In the real world getting a large volume of useful data for training a model is cumbersome and labelling is an extremely tedious task.</p><p>Either labelling requires more manual annotation, example — For creating a better image classifier we can use Mturk and involve more man power to generate dataset or doing survey in social media and asking people to participate and generate dataset. Above process can yield good dataset however those are difficult to carry and expensive. Having small dataset will lead to the well know Over fitting problem.</p><p>Data Augmentation is one of the interesting regularization technique to resolve the above problem. The concept is very simple, this technique generates new training data from given original dataset. Dataset Augmentation provides a cheap and easy way to increase the amount of your training data.</p><p>This technique can be used for both NLP and CV.</p><p>In CV we can use the techniques like Jitter, PCA and Flipping. Similarly in NLP we can use the techniques like Synonym Replacement,Random Insertion, Random Deletion and Word Embeddings.</p><p>It is worth knowing that Keras’ provided ImageDataGenerator for generating Data Augmentation.</p><p>Sample code for random deletion</p><pre>def random_deletion(words, p):<br>        &quot;&quot;&quot;<br>        Randomly delete words from the sentence with probability p<br>        &quot;&quot;&quot;</pre><pre>        #obviously, if there&#39;s only one word, don&#39;t delete it<br>        if len(words) == 1:<br>                return words</pre><pre>        #randomly delete words with probability p<br>        new_words = []<br>        for word in words:<br>                r = random.uniform(0, 1)<br>                if r &gt; p:<br>                        new_words.append(word)</pre><pre>        #if you end up deleting all words, just return a random word<br>        if len(new_words) == 0:<br>                rand_int = random.randint(0, len(words)-1)<br>                return [words[rand_int]]</pre><pre>        return new_words</pre><p>Furthermore, when comparing two machine learning algorithms train both with either augmented or non-augmented dataset. Otherwise, no subjective decision can be made on which algorithm performed better</p><h4>Early Stopping</h4><p>One of the biggest problem in training neural network is how long to train the model.</p><p>Training too little will lead to underfit in train and test sets. Traning too much will have the overfit in training set and poor result in test sets.</p><p>Here the challenge is to train the network long enough that it is capable of learning the mapping from inputs to outputs, but not training the model so long that it overfits the training data.</p><p>One possible solution to solve this problem is to treat the number of training epochs as a hyperparameter and train the model multiple times with different values, then select the number of epochs that result in the best accuracy on the train or a holdout test dataset, But the problem is it requires multiple models to be trained and discarded.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/343/0*nT4S6egNybwymuzR.png" /></figure><p>Clearly, after ‘t’ epochs, the model starts overfitting. This is clear by the increasing gap between the train and the validation error in the above plot.</p><p>One alternative technique to prevent overfitting is use validation error to decide when to stop. This approach is called Early Stopping.</p><p>While building the model, it is evaluated on the holdout validation dataset after each epoch. If the accuracy of the model on the validation dataset starts to degrade (e.g. loss begins to increase or accuracy begins to decrease), then the training process is stopped. This process is called Early stopping.</p><p>Python implementation for Early stopping,</p><pre>def early_stopping(theta0, (x_train, y_train), (x_valid, y_valid),<br>                   n = 1, p = 100):<br>  &quot;&quot;&quot; The early stopping meta-algorithm for determining the best  amount of time to train.<br>      REF: Algorithm 7.1 in deep learning book.</pre><pre>      Parameters:<br>      n: int; Number of steps between evaluations.<br>      p: int; &quot;patience&quot;, the number of evaluations to observe worsening validataion set.<br>      theta0: Network; initial network.<br>      x_train: iterable; The training input set.<br>      y_train: iterable; The training output set.<br>      x_valid: iterable; The validation input set.<br>      y_valid: iterable; The validation output set.</pre><pre>      Returns:<br>      theta_prime: Network object; The output network.<br>      i_prime: int; The number of iterations for the output network.<br>      v: float; The validation error for the output network.<br>  &quot;&quot;&quot;<br>  # Initialize variables<br>  theta = theta0.clone()       # The active network<br>  i = 0                        # The number of training steps taken<br>  j = 0                        # The number of evaluations steps since last update of theta_prime<br>  v = np.inf                   # The best evaluation error observed thusfar<br>  theta_prime = theta.clone()  # The best network found thusfar<br>  i_prime = i                  # The index of theta_prime</pre><pre>  while j &lt; p:<br>      # Update theta by running the training algorithm for n steps<br>      for _ in range(n):<br>          theta.train(x_train, y_train)</pre><pre>      # Update Values<br>      i += n<br>      v_new = theta.error(x_valid, y_valid)</pre><pre>      # If better validation error, then reset waiting time, save the network, and update the best error value<br>      if v_new &lt; v:<br>          j = 0<br>          theta_prime = theta.clone()<br>          i_prime = i<br>          v = v_new</pre><pre>      # Otherwise, update the waiting time<br>      else:<br>          j += 1</pre><pre>  return theta_prime, i_prime, v</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=be3cd1b0e55c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Machine Learning Optimization Methods “Mechanics, Pros, And Cons”]]></title>
            <link>https://salmenzouari.medium.com/machine-learning-optimization-methods-mechanics-pros-and-cons-81b720194292?source=rss-2c5a4e892d------2</link>
            <guid isPermaLink="false">https://medium.com/p/81b720194292</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[supervised-learning]]></category>
            <dc:creator><![CDATA[Salmen Zouari]]></dc:creator>
            <pubDate>Thu, 14 Jan 2021 02:56:49 GMT</pubDate>
            <atom:updated>2021-01-14T02:56:49.036Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/850/0*7yvB7XvU9jz8nBcS.png" /></figure><p>The principal goal of machine learning is to create a model that performs well and gives accurate predictions in a particular set of cases. In order to achieve that, we need machine learning optimization.</p><p>Machine learning optimization is the process of adjusting the hyperparameters in order to minimize the cost function by using one of the optimization techniques. It is important to minimize the cost function because it describes the discrepancy between the true value of the estimated parameter and what the model has predicted.</p><p>In this article, we will discuss the main types of ML optimization techniques and see the advantages and the disadvantages of each technique.</p><h3><strong>1. Feature Scaling</strong></h3><p>Feature Scaling is a technique to standardize the independent features present in the data in a fixed range. It is performed during the data preprocessing to handle highly varying magnitudes or values or units. If feature scaling is not done, then a machine learning algorithm tends to weigh greater values, higher and consider smaller values as the lower values, regardless of the unit of the values.</p><p><strong>Techniques to perform Feature Scaling</strong><br> Consider the two most important ones:</p><ul><li><strong>Min-Max Normalization: </strong>This technique re-scales a feature or observation value with distribution value between 0 and 1.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/521/0*NDZw3H4ps5CrK6dJ.jpg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*aqmLDPpbjE6eX-OyuF-lXg.png" /><figcaption>Attaining Global minimum before and after scaling</figcaption></figure><ul><li><strong>Standardization: </strong>It is a very effective technique which re-scales a feature value so that it has distribution with 0 mean value and variance equals to 1.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/466/0*EeLIw9VWXRWAmwVZ.jpg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/0*Z3eX9987fVpVBDXd.png" /><figcaption>Before and after using <strong>Standardization</strong></figcaption></figure><h4>Advantages</h4><p><strong>Example:</strong> If an algorithm is not using feature scaling method then it can consider the value 3000 meter to be greater than 5 km but that’s actually not true and in this case, the algorithm will give wrong predictions. So, we use Feature Scaling to bring all values to same magnitudes and thus, tackle this issue.</p><h4>Disadvantages</h4><p>Feature scaling usually helps, but it is not guaranteed to improve performance. If you use distance-based methods like SVM, omitting scaling will basically result in models that are disproportionately influenced by the subset of features on a large scale. It may well be the case that those features are in fact the best ones you have. In that case, scaling will reduce performance.</p><h3>2. Batch normalization</h3><p>Normalisation is a technique to change the values of numeric columns in the dataset to a common scale, without distorting differences in the ranges of values. This technique is generally applied as part of data preparation for machine learning and is necessary if various input features are in a different range of values.</p><p>Using batch normalization during inference can be a bit tricky. This is because we might not always have a batch during inference time. For example, consider running an object detector on a video in real time. A single frame is processed at once, and hence there is no batch.</p><p>This is crucial since we need to compute the mean ^x</p><p>and variance σ2</p><p>of a batch to produce the output of the batch norm layer. In that case, we keep a moving average of the mean and variance during training, and then plug these values for the mean and the variance during inference. This is the approach taken by most Deep Learning libraries that ship batch norm layers out of the box.</p><p>The justification of using a moving average rests on the law of large numbers. The mean and variance of a mini-batch is a very noisy estimate of the true mean and the variance. While the batch estimates are called the batch statistics, the true (unknown to us) values of mean and variance are called the population statistics. The law of large number states, that for a large number of samples, the batch statistics will tend to converge to population statistics and that is why we use a moving average during training. It also helps us even out the noise in the estimates produced owing to the mini batch nature of our optimization algorithm.</p><p>In case, we have the option of using batches at test time, we use the same equations as above, with an exception of a minor change in the equation where we calculate the standard deviation. Instead of the equation</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/303/1*P8P9KYAcJxo_0EtJ7_ysAQ.png" /></figure><p>we use,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/354/1*chHnFplYI4fd5RrdUi1BUg.png" /></figure><p>The reason why we use m−1</p><p>in the denominator instead of m is that since we have already estimated the mean, we only have m−1 independent entities in our minibatch now. Had that not been the case, the mean could have been arbitrarily any number, but we do have a fixed mean which we are using to compute the variance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/389/0*1EkQlrkcVN0IYSdO" /></figure><h4>Advantages</h4><ol><li><strong>Networks train faster</strong> — Each training <em>iteration</em> will actually be slower because of the extra calculations during the forward pass and the additional hyperparameters to train during back propagation. However, it should converge much more quickly, so training should be faster overall.</li><li><strong>Allows higher learning rates</strong> — Gradient descent usually requires small learning rates for the network to converge. And as networks get deeper, their gradients get smaller during back propagation so they require even more iterations. Using batch normalization allows us to use much higher learning rates, which further increases the speed at which networks train.</li><li><strong>Makes weights easier to initialize</strong> — Weight initialization can be difficult, and it’s even more difficult when creating deeper networks. Batch normalization seems to allow us to be much less careful about choosing our initial starting weights.</li><li><strong>Makes more activation functions viable</strong> — Some activation functions do not work well in some situations. Sigmoids lose their gradient pretty quickly, which means they can’t be used in deep networks. And ReLUs often die out during training, where they stop learning completely, so we need to be careful about the range of values fed into them. Because batch normalization regulates the values going into each activation function, non-linearlities that don’t seem to work well in deep networks actually become viable again.</li><li><strong>Simplifies the creation of deeper networks</strong> — Because of the first 4 items listed above, it is easier to build and faster to train deeper neural networks when using batch normalization. And it’s been shown that deeper networks generally produce better results, so that’s great.</li><li><strong>Provides a bit of regularlization</strong> — Batch normalization adds a little noise to your network. In some cases, such as in Inception modules, batch normalization has been shown to work as well as dropout. But in general, consider batch normalization as a bit of extra regularization, possibly allowing you to reduce some of the dropout you might add to a network.</li><li><strong>May give better results overall</strong> — Some tests seem to show batch normalization actually improves the training results. However, it’s really an optimization to help train faster, so you shouldn’t think of it as a way to make your network better. But since it lets you train networks faster, that means you can iterate over more designs more quickly. It also lets you build deeper networks, which are usually better. So when you factor in everything, you’re probably going to end up with better results if you build your networks with batch normalization.</li></ol><h4>Disadvantages</h4><ol><li><strong>Difficult to estimate mean and standard deviation of input during testing</strong></li><li><strong>Cannot use batch size of 1 during training</strong></li><li><strong>Computational overhead during training</strong></li><li><strong>Not good for online learning</strong></li><li><strong>Different calculation between train and test</strong></li><li><strong>Not good for Recurrent Neural Networks and Long Short-Term Memory Networks</strong></li></ol><h3>3. Mini-batch gradient descent</h3><p>Is a variation of the gradient descent algorithm that splits the training datasets into small batches that are used to calculate model error and update model coefficients.</p><p>Let us understand like this,</p><p>suppose I have 1000 records and my batch size = 50, I will choose randomly 50 records, then calculate summation of loss and then send the loss to optimizer to find dE/dw.</p><p><strong>Note: </strong>batches are formed in terms of random selection of datasets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/378/1*iGea2ysMeWNWJtEwj7AySA.png" /></figure><p>We use a batch of a fixed number of training examples which is less than the actual dataset and call it a mini-batch. Doing this helps us achieve the advantages of both the former variants we saw. So, after creating the mini-batches of fixed size, we do the following steps in <strong>one epoch:</strong></p><ol><li>Pick a mini-batch</li><li>Feed it to Neural Network</li><li>Calculate the mean gradient of the mini-batch</li><li>Use the mean gradient we calculated in step 3 to update the weights</li><li>Repeat steps 1–4 for the mini-batches we created</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/617/1*Far_IIrhDIOuB_UQEKymAw.png" /></figure><p>So, when we are using the mini-batch gradient descent we are updating our parameters frequently as well as we can use vectorized implementation for faster computations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/908/1*3L2t1Da4M3ztbB0I1Torhw.png" /><figcaption>Difference between gradient descent types</figcaption></figure><h4><em>Advantages</em>:</h4><ol><li>The model update frequency is higher than Batch gradient descent: In Mini-Batch gradient descent, we are not waiting for entire data, we are just passing 50 records or 200 or 100 or 256, then we are passing for optimization.</li><li>The batching allows both efficiency of not having all training data in memory and algorithms implementations. We are controlling memory consumption as well to store losses for each and every datasets.</li><li>The batches updates provide a computationally more efficient process than Stochastic gradient descent.</li></ol><h4><em>Disadvantages</em>:</h4><ol><li>No guarantee of convergence of a error in a better way.</li><li>Since the 50 sample records we take , are not representing the properties (or variance) of entire datasets. Do, this is the reason that we will not be able to get an convergence i.e., we won’t get absolute global or local minima at any point of a time.</li><li>While using Mini-Batch gradient descent, since we are taking records in batches, so, it might happen that in some batches, we get some error and in dome other batches, we get some other error. So, we will have to control the learning rate by our self , whenever we use Mini-Batch gradient descent. If learning rate is very low, so the convergence rate will also fall. If learning rate is too high, we won’t get an absolute global or local minima. So we need to control the learning rate.</li></ol><p><strong>Note</strong>:If the batch size = total no. of data, then in this case,</p><p>Batch gradient descent = Mini-Batch gradient descent.</p><h3>What is batch size?</h3><p>The batch size defines the number of samples that will be propagated through the network.</p><p>For instance, let’s say you have 1050 training samples and you want to set up a batch_size equal to 100. The algorithm takes the first 100 samples (from 1st to 100th) from the training dataset and trains the network. Next, it takes the second 100 samples (from 101st to 200th) and trains the network again. We can keep doing this procedure until we have propagated all samples through of the network. Problem might happen with the last set of samples. In our example, we’ve used 1050 which is not divisible by 100 without remainder. The simplest solution is just to get the final 50 samples and train the network.</p><p>Advantages of using a batch size &lt; number of all samples:</p><p>It requires less memory. Since you train the network using fewer samples, the overall training procedure requires less memory. That’s especially important if you are not able to fit the whole dataset in your machine’s memory.</p><p>Typically networks train faster with mini-batches. That’s because we update the weights after each propagation. In our example we’ve propagated 11 batches (10 of them had 100 samples and 1 had 50 samples) and after each of them we’ve updated our network’s parameters. If we used all samples during propagation we would make only 1 update for the network’s parameter.</p><p>Disadvantages of using a batch size &lt; number of all samples:</p><p>The smaller the batch the less accurate the estimate of the gradient will be. In the figure below, you can see that the direction of the mini-batch gradient (green color) fluctuates much more in comparison to the direction of the full batch gradient (blue color).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DvXlMkBC2w8gFSX5.png" /></figure><p>Stochastic is just a mini-batch with batch_size equal to 1. In that case, the gradient changes its direction even more often than a mini-batch gradient.</p><h3>4. Gradient descent with momentum</h3><p>Gradient descent with momentum will always work much faster than the algorithm Standard Gradient Descent. The basic idea of Gradient Descent with momentum is to calculate the exponentially weighted average of your gradients and then use that gradient instead to update your weights.It functions faster than the regular algorithm for the gradient descent.</p><p>Stochastic gradient descent has trouble navigating ravines, i.e. areas where the surface curves much more steeply in one dimension than in another , which are common around local optima. In these scenarios, Stochastic gradient descent oscillates across the slopes of the ravine while only making hesitant progress along the bottom towards the local optimum as in “fig1”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Q-A3UNSE_RhpVDra.gif" /><figcaption>fig1</figcaption></figure><p>Momentum is a method that helps accelerate Stochastic gradient descent in the relevant direction and dampens oscillations as can be seen in “fig 2”. It does this by adding a fraction γ</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mbcq_fP9mKxZsSHO.gif" /><figcaption>fig2</figcaption></figure><p>Exponentially weighed averages deal with sequences of numbers. Suppose, we have some sequence S which is noisy. For this example I plotted cosine function and added some Gaussian noise. It looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/581/0*4A-pZVPObIS4bNUv.png" /></figure><p>Out sequence.</p><p>Note, that even though these dots seem very close to each over, none of them share <em>x </em>coordinate. It is a unique number for each point. That’s the number the defines the index of each point in our sequence S.</p><p>What we want to do with this data is, instead of using it, we want some kind of ‘moving’ average which would ‘denoise’ the data and bring it closer to the original function. Exponentially weighed averages can give us a pictures which looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/582/0*GSwefeHuhT_zZa6P.png" /></figure><p>momentum — data from exponentially weighed averages.</p><p>As you can see, that’s a pretty good result. Instead of having data with a lot of noise, we got much smoother line, which is closer to the original function than data we had. Exponentially weighed averages define a new sequence V with the following equation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/60/0*0usdwgcJOPHy-TMR" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/549/0*HFdZoJWcvKiXe1aE.png" /></figure><p>That sequence V is the one plotted yellow above. <em>Beta</em> is another hyper-parameter which takes values from 0 to one. I used <em>beta</em> = 0.9 above. It is a good value and most often used in Stochastic gradient descent with momentum. Intuitively, you can think of <em>beta</em> as follows. We’re approximately averaging over last <em>1 / (1- beta) </em>points of sequence. Let’s see how the choice of <em>beta</em> affects our new sequence V.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/582/0*ezYL28bboWkj9-D1.png" /></figure><p>Exponentially weighed averages for different values of beta.</p><p>As you can see, with smaller numbers of beta, the new sequence turns out to be fluctuating a lot, because we’re averaging over smaller number of examples and therefore are ‘closer’ to the noisy data. With bigger values of beta, like <em>beta=0.98</em>, we get much smother curve, but it’s a little bit shifted to the right, because we average over larger number of example(around 50 for <em>beta=0.98</em>). <em>Beta = 0.9</em> provides a good balance between these two extremes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XaLKA258RxJpoXSR.gif" /><figcaption>We clearly see, that as we increase momentum, we get to the local minimum faster, but we might also overshoot and then it takes longer.</figcaption></figure><h4>Advantages</h4><p><strong>Robust and efficient</strong> —<strong> </strong>The momentum term increases in dimensions whose gradient continues in the same direction, and reduces updates for dimensions whose gradients change directions. As a result, we get faster convergence and reduced oscillation.</p><h4>Disadvantages</h4><ol><li>No rule-of-thumb for selecting mini-batch size</li><li>Hence the number of epochs required will be extremely high, based on the initialization of ‘w’ and ‘b’. Another limitation of gradient descent update rule is that the learning can stop if the points are stuck in the local minimum.</li><li>Momentum-based GD is able to take larger steps even in the regions of the gentle slopes, as the momentum of the history gradients is carried with it every step. But is taking a larger step is always better? How about when the global minimum is about to be reached? Would there be a situation where momentum would cause us to run past our goal? Consider the below example where the momentum-based GD overshoots and moves past the global minimum.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yxMxHB7t5QWObmD6.png" /></figure><p>Although Momentum-based GD is faster than GD, it oscillates in and out of the minima valley. But can this oscillation be reduced? Of course, Nesterov Accelerated GD helps us to reduce the oscillations that happen in momentum based GD.</p><h3>5. RMSProp optimization</h3><p>RMSprop is a gradient based optimization technique used in training neural networks. It was proposed by the father of back-propagation, Geoffrey Hinton. Gradients of very complex functions like neural networks have a tendency to either vanish or explode as the data propagates through the function . RMSprop was developed as a stochastic technique for mini-batch learning.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YmIu605dj9ytR7b1.gif" /></figure><p>RMSprop deals with the above issue by using a moving average of squared gradients to normalize the gradient. This normalization balances the step size (momentum), decreasing the step for large gradients to avoid exploding, and increasing the step for small gradients to avoid vanishing.</p><p>Simply put, RMSprop uses an adaptive learning rate instead of treating the learning rate as a hyperparametre. This means that the learning rate changes over time.</p><p>RMSprop, or Root Mean Square Propogation has an interesting history. It was devised by the legendary Geoffrey Hinton, while suggesting a random idea during a Coursera class.</p><p>RMSProp also tries to dampen the oscillations, but in a different way than momentum. RMS prop also takes away the need to adjust learning rate, and does it automatically. More so, RMSProp choses a different learning rate for each parameter.</p><p>In RMS prop, each update is done according to the equations described below. This update is done separately for each parameter.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*uMVb8RMokVdlosGx.png" /></figure><p>So, let’s break down what is happening here.</p><p>In the first equation, we compute an exponential average of the square of the gradient. <strong>Since we do it separately for each parameter, gradient <em>Gt</em> here corresponds to the projection, or component of the gradient along the direction represented by the parameter we are updating.</strong></p><p>To do that, we multiply the exponential average computed till the last update with a hyperparameter, represented by the greek symbol <em>nu</em>. We then multiply the square of the current gradient with <em>(1 — nu)</em>. We then add them together to get the exponential average till the current time step.</p><p>The reason why we use exponential average is because as we saw, in the momentum example, it helps us weigh the more recent gradient updates more than the less recent ones. In fact, the name “exponential” comes from the fact that the weightage of previous terms falls exponentially (the most recent term is weighted as <em>p</em>, the next one as squared of <em>p</em>, then cube of <em>p</em>, and so on.)</p><p>Notice our diagram denoting pathological curvature, the components of the gradients along <em>w1</em> are much larger than the ones along <em>w2</em>. Since we are squaring and adding them, they don’t cancel out, and the exponential average is large for <em>w2</em> updates.</p><p>Then in the second equation, we decided our step size. We move in the direction of the gradient, but our step size is affected by the exponential average. We chose an initial learning rate <em>eta</em>, and then divide it by the average. In our case, since the average of <em>w1</em> is much much larger than <em>w2</em>, the learning step for <em>w1</em> is much lesser than that of <em>w2</em>. Hence, this will help us avoid bouncing between the ridges, and move towards the minima.</p><p>The third equation is just the update step. The hyperparameter <em>p</em> is generally chosen to be 0.9, but you might have to tune it. The epsilon is equation 2, is to ensure that we do not end up dividing by zero, and is generally chosen to be 1e-10.</p><p>It’s also to be noted that RMSProp implicitly performs simulated annealing. Suppose if we are heading towards the minima, and we want to slow down so as to not to overshoot the minima. RMSProp automatically will decrease the size of the gradient steps towards minima when the steps are too large (Large steps make us prone to overshooting)</p><h4>Advantages</h4><ol><li>RMSProp converge faster than GD or SGD, in many settings. Especially for GANs, RL, and attention-based networks.</li><li>RMSProp might be able to converge to solutions with better quality (e.g. better local minima). This is based on my experience when playing with these algorithms for GANs and LSTM.</li><li>Less tuning compared to GD or SGD.</li></ol><h4>Disadvantages</h4><ol><li>Learning rate is still manual, because the suggested value is not always appropriate for every task.</li><li>Implementation of RMSProp Descent with Employee Attrition</li></ol><h3>6. Adam optimization</h3><p><strong>Adam</strong> or <strong>Adaptive Moment Optimization</strong> algorithms combines the heuristics of both Momentum and RMSProp. Here are the update equations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*PkG7qAh1R9zMUxEz.png" /></figure><p>Here, we compute the exponential average of the gradient as well as the squares of the gradient for each parameters (Eq 1, and Eq 2). To decide our learning step, we multiply our learning rate by average of the gradient (as was the case with momentum) and divide it by the root mean square of the exponential average of square of gradients (as was the case with momentum) in equation 3. Then, we add the update.</p><p>The hyperparameter <em>beta1</em> is generally kept around 0.9 while <em>beta_2</em> is kept at 0.99. Epsilon is chosen to be 1e-10 generally.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*EsGLItTBpMpbpHXv.gif" /></figure><p>Adam implements the exponential moving average of the gradients to scale the learning rate instead of a simple average as in Adagrad.</p><p>Adam is computationally efficient and has very less memory requirement.</p><p><strong>Adam is so far the best optimizer that is known.</strong></p><h4>Advantages</h4><ol><li>Easy to implement</li><li>Quite computationally efficient</li><li>Requires little memory space</li><li>Good for non-stationary objectives</li><li>Works well on problems with noisy or sparse gradients</li><li>Works well with large data sets and large parameters</li><li><strong>Adam realizes the benefits of both AdaGrad and RMSProp.</strong></li></ol><ul><li>Instead of adapting the parameter learning rates based on the average first moment (the mean) as in RMSProp, Adam also makes use of the average of the second moments of the gradients (the uncentered variance).</li><li>Specifically, the algorithm calculates an exponential moving average of the gradient and the squared gradient, and the parameters beta1 and beta2 control the decay rates of these moving averages.</li><li>The initial value of the moving averages and beta1 and beta2 values close to 1.0 (recommended) result in a bias of moment estimates towards zero. This bias is overcome by first calculating the biased estimates before then calculating bias-corrected estimates.</li></ul><h4>Disadvantages</h4><p>There are few disadvantages as the Adam optimizer tends to converge faster, but other algorithms like the Stochastic gradient descent focus on the datapoints and generalize in a better manner. Thus, the performance depends on the type of data being provided and the speed/generalization trade-off.</p><p>When Adam was first introduced, people got very excited about its power. Paper contained some very optimistic charts, showing huge performance gains in terms of speed of training:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/342/0*zVNCc9v75ZvHHFU7.png" /></figure><p>Then, Nadam paper presented diagrams that showed even better results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/662/0*BUjROV7wIAgXtkos.png" /></figure><p>However, after a while people started noticing that despite superior training time, Adam in some areas does not converge to an optimal solution, so for some tasks (such as image classification ) state-of-the-art results are still only achieved by applying SGD with momentum. More than that Wilson et. al [9] showed in their paper ‘The marginal value of adaptive gradient methods in machine learning’ that adaptive methods (such as Adam do not generalize as well as SGD with momentum when tested on a diverse set of deep learning tasks, discouraging people to use popular optimization algorithms. A lot of research has been done since to analyze the poor generalization of Adam trying to get it to close the gap with SGD.</p><p>Nitish Shirish Keskar and Richard Socher in their paper ‘Improving Generalization Performance by Switching from Adam to SGD’ also showed that by switching to SGD during training training they’ve been able to obtain better generalization power than when using Adam alone. They proposed a simple fix which uses a very simple idea. They’ve noticed that in earlier stages of training Adam still outperforms SGD but later the learning saturates. They proposed simple strategy which they called <strong>SWATS </strong>in which they start training deep neural network with Adam but then switch to SGD when certain criteria hits. They managed to achieve results comparable to SGD with momentum.</p><h3>7. Learning rate decay</h3><p>The <strong>learning rate</strong> or <em>step size</em> in machine learning is a hyperparameter which determines to what extent newly acquired information overrides old information. It is the most important hyper-parameter to tune for training deep neural networks. The learning rate is crucial because it controls both the speed of convergence and the ultimate performance of the network. We select learning rate mostly by trial and error, or by virtue of previous experience or some methods like LR finder. A too high learning rate will make the learning jump over minima but a too low learning rate will either take too long to converge or get stuck in undesirable local minima.</p><p>Finding a decent learning rate for a neural network is like fishing. The selection of learning rate is one of those things that makes deep learning look like magic. One of the simplest learning rate strategies is to have a fixed learning rate throughout the training process. During earlier iterations, faster learning rates lead to faster convergence while during later epochs, slower learning rate produces better accuracy. Changing the learning rate over time can overcome this tradeoff.</p><p>Schedules define how the learning rate changes over time and are typically specified for each epoch or iteration (i.e batch) of training. The main benefits of learning rate schedules are it converges faster with higher accuracy. They differ from adaptive methods (such as AdaDelta and Adam) because :</p><ul><li>Schedules change the global learning rate for the optimizer, rather than parameter-wise learning rates.</li><li>Schedules don’t take feedback from the training process and are specified beforehand.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/0*J3ELskkmbo6m-js_.jpg" /></figure><h3>Types of Schedules</h3><p>The theory of stochastic approximation gives us many types of schedules. But, these are not the ones that are usually used in contemporary deep learning models and frameworks. The theoretical basis of why these schedules work well is an active area of research.Here, we will be looking closely at schedules that are prominently used ones. Here, we will look at most common of these schedules:</p><ol><li><strong>Step-wise Decay</strong></li><li><strong>Polynomial Decay</strong></li><li><strong>Exponential Schedule</strong></li><li><strong>Reduce on Loss Plateau Decay</strong></li><li><strong>Cosine Annealing</strong></li><li><strong>Custom Schedules</strong></li></ol><h4>1. Step-wise Decay</h4><p>In step-wise decay, the learning-rate is decayed after a fixed number of steps(intervals) by a fixed factor. This fixed factor is called decay-factor, usually represented by <strong><em>(gamma)</em></strong>.</p><ul><li>After every epochs:</li><li>Learning rate at epoch:</li></ul><p>where, is the learning rate epoch. is the decay-rate. is the step-size.</p><p><strong>Tips</strong></p><ul><li>You would want to decay your LR gradually when you’re training more epochs.</li><li>Converge too fast, to a crappy loss/accuracy, if you decay rapidly</li><li>To decay slower</li><li>Larger</li><li>Larger interval of decay</li></ul><h4>2. Polynomial Decay</h4><p>Stepwise schedules and the discontinuities they introduce may sometime lead to instability in the optimization, so in some cases smoother schedules are preferred. The learning-rate is decayed after every epoch based on a polynomial function. Polynomial Decay provides a smoother decay using a polynomial function and reaches a learning rate of 0 after <strong>max_update</strong> iterations.</p><p>The two important quantities in polynomial decay are:-</p><ol><li><em>max_update</em>: number of iterations to perform before the learning rate is taken to .</li><li><em>power</em>: the degree of the polynomial function</li></ol><p><strong>Tips</strong></p><ul><li>Smaller values of <em>power</em> produce slower decay and large values of learning rate for longer periods.</li><li>For longer training, <em>last_epoch</em> can be increased.</li></ul><h4>3. Exponential Decay</h4><p>Like the polynomial decay given above, exponential decay gives a smoother decay, solving the instability issues in step-wise scheduling. But here, the learning-rate is decayed after every epoch based on an exponential function.</p><p>The important parameters in exponential decay are:</p><ul><li><em>last_epoch</em>: The index of last epoch</li><li>: multiplicative factor of learning rate decay</li></ul><p><strong>Tips</strong></p><ul><li>Larger</li><li>Slower convergence</li><li>Better loss/accuracy</li><li>Smaller</li><li>Faster convergence</li><li>Worse loss/accuracy</li><li>For longer training period, <em>last_epoch</em> can be increased.</li></ul><h4>4. Reduce on Loss Plateau Decay</h4><p>All the above decay methods like step-wise, polynomial, exponential reduce the learning-rate according to a pre-defined rule. It may change after a few steps or with every step, but the change is imminent. Consider a situation where a learning-rate value is performing well, then decaying it prematurely may not be a wise idea. Similarly continuing with a stale learning-rate value waiting for the decay step is also not helpful. All these scheduling methods do not take into consideration the position of the loss function at the moment.</p><p>So, a better idea may be to decrease the learning-rate only when the loss plateaus. This is exactly what we do in ‘Reduce on Loss Plateau Decay’. The decaying action occurs after no improvement in loss value is found. The plateau condition is checked by a fixed value called <strong><em>patience</em></strong>. Patience determines the number of epochs to wait before changing the learning-rate. For example, if patience = 2, then we will ignore the first 2 epochs with no improvement, and will only decrease the LR after the 3rd epoch if the loss still hasn’t improved then.</p><p>The two important quantities in loss plateau decay are:</p><ul><li><em>Patience</em>: number of epochs with no improvements after which learning rate will be reduced.</li><li><em>Factor</em>: multiplier to decrease the learning-rate.</li></ul><p><strong>Tips</strong></p><ul><li>For larger number of epochs increase the value of patience</li><li>Loss or accuracy or any other metric can be used for finding plateau</li></ul><h4>5. Cosine Annealing</h4><p>Cosine Annealing was proposed in SGDR: Stochastic Gradient Descent with Warm Restarts by Ilya Loshchilov &amp; Frank Hutter. We will only be talking about the cosine annealing part here, we can leave out the Warm restart for a later time. In cosine annealing, we will be using the cosine function in the range . This is particularly useful for us as in the early iterations it will give us a relatively large learning rate to quickly approach a local minimum (faster convergence), and towards the end, it gives us many small learning rate iterations (better loss/accuracy).</p><p>Important parameters in cosine annealing are:-</p><ul><li><em>min_lr</em>: the minimum learning rate</li><li><em>max_lr</em>: the maximum learning rate</li><li><em>cycle_length</em>: the number of epochs to run between the maximum and minimum learning rates</li></ul><p><strong>Tips</strong></p><ul><li>Longer cycle length usually works better.</li><li>Cosine Annealing with warm restarts produces better results than vanilla cosine annealing.</li></ul><h4>6. Custom Schedules</h4><p>Along with all these common LR scheduling methods, we can make our own schedules. So, let make a schedule that decays according to the function .</p><pre>class LogAnnealingLR(_LRScheduler):</pre><pre>    def __init__(self, optimizer, T_max, eta_min=0, last_epoch=-1):<br>        self.T_max = T_max<br>        self.eta_min = eta_min<br>        super(LogAnnealingLR, self).__init__(optimizer, last_epoch)</pre><pre>    def get_lr(self):<br>        return [self.eta_min + (base_lr - self.eta_min) *<br>                (1 + math.cos(math.pi * self.last_epoch / self.T_max)) / 2<br>                for base_lr in self.base_lrs]</pre><h3>BONUS</h3><h4>Which optimizer to use?</h4><p>So, which optimizer should you now use? If your input data is sparse, then you likely achieve the best results using one of the adaptive learning-rate methods. An additional benefit is that you won’t need to tune the learning rate but likely achieve the best results with the default value.</p><p>In summary, RMSprop is an extension of Adagrad that deals with its radically diminishing learning rates. It is identical to Adadelta, except that Adadelta uses the RMS of parameter updates in the numinator update rule. Adam, finally, adds bias-correction and momentum to RMSprop. Insofar, RMSprop, Adadelta, and Adam are very similar algorithms that do well in similar circumstances. Kingma et al. show that its bias-correction helps Adam slightly outperform RMSprop towards the end of optimization as gradients become sparser. Insofar, Adam might be the best overall choice.</p><p>Interestingly, many recent papers use vanilla SGD without momentum and a simple learning rate annealing schedule. As has been shown, SGD usually achieves to find a minimum, but it might take significantly longer than with some of the optimizers, is much more reliant on a robust initialization and annealing schedule, and may get stuck in saddle points rather than local minima. Consequently, if you care about fast convergence and train a deep or complex neural network, you should choose one of the adaptive learning rate methods.</p><p>I hope the Optimizers concept is by far clear, its the beauty of mathematics and playing around with equations which researchers spent a lot of time on. For all Optimizers now minibatch is always used. Minibatch Gradient descent solved the problem of performance and had lesser noise, while momentum reduced the noise to bring in smoothening effect. The problem of Adgrad of diminishing learning rate in deeper neural network was solved by RMSProp, and Adam by using both momentum and RMSProp became the best of optimizer right now.</p><p>Thanks for reading and happy modelling!</p><p><a href="https://github.com/salmenz/">My GITHUB</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=81b720194292" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[All You Need To Understanding Activation Function In Neural Networks]]></title>
            <link>https://salmenzouari.medium.com/all-you-need-to-understanding-activation-function-in-neural-networks-41a00717f774?source=rss-2c5a4e892d------2</link>
            <guid isPermaLink="false">https://medium.com/p/41a00717f774</guid>
            <category><![CDATA[activation-functions]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-intelligence]]></category>
            <dc:creator><![CDATA[Salmen Zouari]]></dc:creator>
            <pubDate>Thu, 07 Jan 2021 01:33:50 GMT</pubDate>
            <atom:updated>2021-01-07T01:33:50.245Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bhFifratH9DjKqMBTeQG5A.gif" /></figure><h3>Brief overview of neural networks</h3><p>Before I delve into the details of activation functions, let us quickly go through the concept of neural networks and how they work. A neural network is a very powerful machine learning mechanism which basically mimics how a human brain learns.</p><p>The brain receives the stimulus from the outside world, does the processing on the input, and then generates the output. As the task gets complicated, multiple neurons form a complex network, passing information among themselves.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/0*Y3ixab1tkk7xOXns.png" /></figure><p>An Artificial Neural Network tries to mimic a similar behavior. The network you see below is a neural network made of interconnected neurons. Each neuron is characterized by its weight, bias and activation function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/572/0*za8-0YLdjxuJLRKP.png" /></figure><p>The input is fed to the input layer, the neurons perform a linear transformation on this input using the weights and biases.</p><pre>x = (weight * input) + bias</pre><h3>weights</h3><p>Weights are values that control the strength of the connection between two neurons. That is, inputs are typically multiplied by weights, and that defines how much influence the input will have on the output.</p><h3>Bias</h3><p>Bias terms are additional constants attached to neurons and added to the weighted input before the activation function is applied. Bias terms help models represent patterns that do not necessarily pass through the origin.</p><h3>Weighted input</h3><p>A neuron’s input equals the sum of weighted outputs from all neurons in the previous layer. Each input is multiplied by the weight associated with the synapse connecting the input to the current neuron.</p><p>Post that, an activation function is applied on the above result.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/406/0*_6ybXvdvY_4OOj8O.png" /></figure><p>Finally, the output from the activation function moves to the next hidden layer and the same process is repeated. This forward movement of information is known as the <strong><em>forward propagation</em></strong>.</p><p>What if the output generated is far away from the actual value? Using the output from the forward propagation, error is calculated. Based on this error value, the weights and biases of the neurons are updated. This process is known as <strong><em>back-propagation</em></strong>.</p><h3>Popular types of activation functions and when to use them</h3><h3>1. Binary Step Function</h3><p>The first thing that comes to our mind when we have an activation function would be a threshold based classifier i.e. whether or not the neuron should be activated based on the value from the linear transformation.</p><p>In other words, if the input to the activation function is greater than a threshold, then the neuron is activated, else it is deactivated, i.e. its output is not considered for the next hidden layer. Let us look at it mathematically</p><pre>f(x) = 1, x&gt;=0<br>     = 0, x&lt;0</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/407/0*kLHlFYq4r76dJ40P.png" /></figure><p>This is the simplest activation function, which can be implemented with a single if-else condition in python</p><pre>def binary_step(x):<br>    if x&lt;0:<br>        return 0<br>    else:<br>        return 1</pre><pre>binary_step(5), binary_step(-1)</pre><p><strong>Output:</strong></p><pre>(5,0)</pre><p>The binary step function can be used as an activation function while creating a binary classifier. As you can imagine, this function will not be useful when there are multiple classes in the target variable. That is one of the limitations of binary step function.</p><h3>2. Linear Activation Function</h3><p>A linear activation function takes the form:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/391/0*0CE5k1Xy1ogvAqeb.png" /></figure><p>It takes the inputs, multiplied by the weights for each neuron, and creates an output signal proportional to the input. In one sense, a linear function is better than a step function because it allows multiple outputs, not just yes and no.</p><p>However, a linear activation function has two major problems:</p><p><strong>1. Not possible to use </strong><a href="https://missinglink.ai/guides/neural-network-concepts/backpropagation-neural-networks-process-examples-code-minus-math/"><strong>backpropagation</strong></a> (gradient descent) to train the model — the derivative of the function is a constant, and has no relation to the input, X. So it’s not possible to go back and understand which weights in the input neurons can provide a better prediction.</p><p><a href="https://missinglink.ai/guides/neural-network-concepts/backpropagation-neural-networks-process-examples-code-minus-math/"><strong><em>Go in-depth: See our guide on backpropagation</em></strong></a></p><p><strong>2. All layers of the neural network collapse into one</strong> — with linear activation functions, no matter how many layers in the neural network, the last layer will be a linear function of the first layer (because a linear combination of linear functions is still a linear function). So a linear activation function turns the neural network into just one layer.</p><p>A neural network with a linear activation function is simply a linear regression model. It has limited power and ability to handle complexity varying parameters of input data.</p><h3>3. Sigmoid Activation Function</h3><p>The sigmoid function is an activation function where it scales the values between 0 and 1 by applying a threshold. Below is a sigmoid curve,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/251/0*H50DjbaLG_pF9fbS.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/271/0*VNj0qa4Ip-LkNWEh.png" /></figure><p>The above equation represents a sigmoid function. When we apply the weighted sum in the place of X, the values are scaled in between 0 and 1. The beauty of an exponent is that the value never reaches zero nor exceed 1 in the above equation. The large negative numbers are scaled towards 0 and large positive numbers are scaled towards 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jQtCJ7W-X95BL2a9.jpg" /></figure><p>In the above example, as x goes to minus infinity, y goes to 0 (tends not to fire).<br> As x goes to infinity, y goes to 1 (tends to fire):<br> At x=0, y=1/2.<br> The threshold is set to 0.5. If the value is above 0.5 it is scaled towards 1 and if it is below 0.5 it is scaled towards 0.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/583/0*6UWJq5aAhYhc7vW5.png" /></figure><p>We can also change the sign to implement the opposite of the threshold by the above example. With a large positive input we get a large negative output which tends to not fire and with a large negative input we get a large positive output which tends to fire.</p><p>The beauty of sigmoid function is that the derivative of the function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*QvfCIxRgaPbSDMLn.jpg" /></figure><p>Once this is computed, it is easy to apply gradient descent during back propagation. It makes it smooth to gradually descent towards to minima once this is scaled while we apply the gradient descent. Here is a visual representation,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/728/0*-Fr-EVE67EcL3dGe.gif" /></figure><h3>4. Tanh Activation Function(Hyperbolic Tangent)</h3><p>The Tanh function is an activation function which re scales the values between -1 and 1 by applying a threshold just like a sigmoid function. The advantage i.e the values of a tanh is zero centered which helps the next neuron during propagating.<br> Below is a tanh function</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/0*DNNyRi7DZYFthuxv.png" /></figure><p>When we apply the weighted sum of the inputs in the tanh(x), it re scales the values between -1 and 1. . The large negative numbers are scaled towards -1 and large positive numbers are scaled towards 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/0*y-vaaxw3Y8ZqrgcF.png" /></figure><p>In the above example, as x goes to minus infinity, tanh(x) goes to -1 (tends not to fire).<br> As x goes to infinity, tanh(x) goes to 1 (tends to fire):<br> At x=0, tanh(x)=0.<br> The thresold is set to 0. If the value is above 0 it is scaled towards 1 and if it is below 0 it is scaled towards -1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/642/0*RV0QKQymPDSKmrvx.png" /></figure><p>This is implemented in the computation, just like the sigmoid it will smooth the curve where gradient descent will converge towards the minima based on the learning rate. Here is a visual of how it works,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/0*cGfvjNP9okp2Ul0R.gif" /></figure><h3>5. ReLU Activation Function(Rectified Linear Unit)</h3><p>This is one of the most widely used activation function. The benefits of ReLU is the sparsity, it allows only values which are positive and negative values are not passed which will speed up the process and it will negate or bring down possibility of occurrence of a dead neuron.</p><p><strong>f(x) = (0,max)</strong></p><p>This function will allow only the maximum values to pass during the front propagation as shown in the graph below. The draw backs of ReLU is when the gradient hits zero for the negative values, it does not converge towards the minima which will result in a dead neuron while back propagation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/396/0*EtRVKYddmGTYJ5jd.png" /></figure><h3>Leaky ReLU</h3><p>This can be overcome by Leaky ReLU , which allows a small negative value during the back propagation if we have a dead ReLU problem. This will eventually activate the neuron and bring it down.</p><p><strong>f(x)=1(x&lt;0)(αx)+1(x&gt;=0)(x)</strong> where <strong>α</strong> is a small constant</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/392/0*O-1qswxKbz53bdQA.png" /></figure><p>Some people have got results with this activation function but they are not always consistent. This activation function also has drawbacks, during the front propagation if the learning rate is set very high it will overshoot killing the neuron. This will happen when the learning rate is not set at an optimum level like in the below graph,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/384/0*0oRyXkQZesTIADsz.gif" /></figure><p>High learning rate leading to overshoot during gradient descent.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/384/0*XMX4ed8b8zxModbf.gif" /></figure><p>Low and optimal learning rate leading to a gradual descent towards the minima.</p><h3>6. Softmax Activation Function</h3><p>Softmax function is often described as a combination of multiple sigmoids. We know that sigmoid returns values between 0 and 1, which can be treated as probabilities of a data point belonging to a particular class. Thus sigmoid is widely used for binary classification problems.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gzBoXmZoimBxOee6.gif" /></figure><p>The softmax function can be used for multiclass classification problems. This function returns the probability for a datapoint belonging to each individual class. Here is the mathematical expression of the same-</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/274/0*BC-fpZ1wRHe4qUtO.png" /></figure><p>While building a network for a multiclass problem, the output layer would have as many neurons as the number of classes in the target. For instance if you have three classes, there would be three neurons in the output layer. Suppose you got the output from the neurons as [1.2 , 0.9 , 0.75].</p><p>Applying the softmax function over these values, you will get the following result — [0.42 , 0.31, 0.27]. These represent the probability for the data point belonging to each class. Note that the sum of all the values is 1. Let us code this in python</p><pre>def softmax_function(x):<br>    z = np.exp(x)<br>    z_ = z/z.sum()<br>    return z_</pre><pre>softmax_function([0.8, 1.2, 3.1])</pre><p><strong>Output:</strong></p><pre>array([0.08021815, 0.11967141, 0.80011044])</pre><h3>Choosing the right Activation Function</h3><p>Now that we have seen so many activation functions, we need some logic / heuristics to know which activation function should be used in which situation. Good or bad — there is no rule of thumb.</p><p>However depending upon the properties of the problem we might be able to make a better choice for easy and quicker convergence of the network.</p><ul><li>Sigmoid functions and their combinations generally work better in the case of classifiers</li><li>Sigmoids and tanh functions are sometimes avoided due to the vanishing gradient problem</li><li>ReLU function is a general activation function and is used in most cases these days</li><li>If we encounter a case of dead neurons in our networks the leaky ReLU function is the best choice</li><li>Always keep in mind that ReLU function should only be used in the hidden layers</li><li>As a rule of thumb, you can begin with using ReLU function and then move over to other activation functions in case ReLU doesn’t provide with optimum results</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=41a00717f774" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Learn Recursion in 2 mins]]></title>
            <link>https://salmenzouari.medium.com/learn-recursion-in-2-mins-a40697d081bc?source=rss-2c5a4e892d------2</link>
            <guid isPermaLink="false">https://medium.com/p/a40697d081bc</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[learning]]></category>
            <category><![CDATA[recursion]]></category>
            <dc:creator><![CDATA[Salmen Zouari]]></dc:creator>
            <pubDate>Sun, 26 Apr 2020 22:56:29 GMT</pubDate>
            <atom:updated>2020-04-26T22:56:29.997Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MKZZ0lW3_X1RVOn-QAVSDw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-FuLPjc0VrusOBqIVHW9Vg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O-cBKUWnFITbC-jA4baTcw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7m2G64WxKH25kcgavH9V4g.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a40697d081bc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What Happens When You Type A URL In Your Browser And Press Enter]]></title>
            <link>https://salmenzouari.medium.com/what-happens-when-you-type-a-url-in-your-browser-and-press-enter-fc56f387b5e7?source=rss-2c5a4e892d------2</link>
            <guid isPermaLink="false">https://medium.com/p/fc56f387b5e7</guid>
            <category><![CDATA[surfing]]></category>
            <category><![CDATA[https]]></category>
            <category><![CDATA[browsers]]></category>
            <category><![CDATA[website]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Salmen Zouari]]></dc:creator>
            <pubDate>Wed, 08 Apr 2020 09:35:06 GMT</pubDate>
            <atom:updated>2020-04-08T09:35:06.293Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gOBou4E9siBBL3ykdDnqOA.png" /></figure><p>If you are in any technical profession, I am sure someone at some point has asked you this question. Whether you are an engineer, developer, marketer, or even in sales, it is always good to have a basic understanding of what is going on behind our browsers and how information is transferred to our computers via the internet.</p><p>Here’s the situation: You’ve opened up your laptop, double-clicked on your web browser, typed holbertonschool.com in the address bar and hit the enter key. For us it’s just an enter button let’s see what’s behind.</p><p>First, let’s discuss the web browser.</p><h3>The Web Browser</h3><p>A web browser is a program that most people use to view websites on the Internet. Most modern web browsers like Google Chrome and Mozilla Firefox have many features built into them that hide some of the underlying processes involved in connecting to a webpage in order do improve user experience. We will discuss some of these features in later sections.</p><p>When you type holbertonschool.com in the address bar, you are essentially providing the browser with the URL for the website you want to visit. URL stands for <em>Uniform Resource Locator</em>; it is essentially an address to the file (resources) that the browser needs to display the web page.</p><p>A complete URL looks something like this:</p><pre><a href="http://www.holbertonschool.com/index.html">http://www.holbertonschool.com/index.html</a></pre><ul><li>http:// tells the browser that we want to access a page using the <em>Hyper Text Transfer Protocol</em> (HTTP). This is a protocol that browsers use to interact with web pages. Other protocol have other purposes, for example ftp:// (<em>File Transfer Protocol</em>) is a protocol used to transfer files across the Internet. https:// is another protocol we will discuss later, but in short, it&#39;s the secured version of <a href="http://./">http://.</a></li><li>www is a <em>subdomain</em> of holbertonschool.com; this part refers to a specific location (server) inside the domain where resources are located.</li><li>holbertonschool.com is the domain name; it represents the server where all the data for &quot;holbertonschool.com&quot; resides.</li><li>/index.html is the path to the file that will be displayed by the browser.</li></ul><p>One of the user-friendly features of web browsers is that they don’t require you to type the complete URL of every web page you want to see. These days it is assumed that when you type holbertonschool.com you mean http://www.holbertonscool.com, but underneath the hood, there is some communication with the browser and the website&#39;s server to determine which files are required for the home page. It might be /index.html, /index.php, or some other file that is produced dynamically.</p><p>The communication between computers on a network is built upon many different protocols. A <em>protocol</em> is a set of rules that both parties must follow in order to function. For example, both parties must speak the same language (syntax), include particular information about themselves, and generally act as expected, according to the protocol.</p><p>One of the most relevant protocols the Internet uses is TCP/IP.</p><h3>TCP/IP</h3><p>The TCP/IP reference model is a layered model developed by the Defense Project Research Agency(ARPA or DARPA) of the United States as a part of their research project in 1960. Initially, it was developed to be used by defense only. But later on, it got widely accepted. The main purpose of this model is to connect two remote machines for the exchange of information. These machines can be operating in different networks or have different architecture.</p><p>In the early days, the TCP/IP reference model has four layers, as described below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*sia2XUaUqLj7EcqE.jpg" /></figure><p>These layers are much similar to the layers of the <a href="https://afteracademy.com/blog/what-is-the-osi-model-and-how-it-works">OSI modl</a>. The Application layer in the TCP/IP model has approximately the same functionality as the upper three layers(Application, Presentation, and Session layer) of the OSI model. Also, the Internet layer acts as the Network layer, and the Network Access layer acts as the lower two layers(Physical and Data-Link layer) of the OSI model. TCP/IP network model is named after two main <a href="https://afteracademy.com/blog/what-are-protocols-and-what-are-the-key-elements-of-protocols">protocols</a>(TCP and IP) and is widely used in current internet architecture. But nowadays, we generally use a five-layer TCP/IP model, as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*qrwgnKFamL5RVQfv.jpg" /></figure><p>In the above diagram, the Physical and Data-Link layer acts as the Network Access layer of the previously used TCP/IP model. This TCP/IP model is currently in use. So, in this blog, we’ll learn about the five-layer TCP/IP reference model. We’ll also see the key features of this model and the functionalities of its five layers.</p><blockquote><strong>The key features of the TCP/IP model are as follows:</strong></blockquote><ol><li><strong>Supports flexible architecture:</strong> We can connect two devices with totally different architecture using the TCP/IP model.</li><li><strong>End-node verification:</strong> The end-nodes(source and destination) can be verified, and connection can be made for the safe and successful transmission of data.</li><li><strong>Dynamic Routing: </strong>The TCP/IP model facilitates the dynamic routing of the data packets through the shortest and safest path. Due to dynamic routing, the path taken by the data packet can not be predicted, and thus it improves data security.</li></ol><blockquote><strong>There are also some demerits of using the TCP/IP model, these are as follows:</strong></blockquote><ol><li>Replacing a protocol is not easy.</li><li>The roles and functionalities of each layer are not documented and specified properly, as it is described in the OSI model.</li></ol><blockquote><strong>Following are the five layers of the TCP/IP model:</strong></blockquote><ol><li><strong>Physical Layer</strong></li><li><strong>Data-Link Layer</strong></li><li><strong>Internet Layer</strong></li><li><strong>Transport Layer</strong></li><li><strong>Application Layer</strong></li></ol><p>Now, we will learn about the functionalities of these layers one-by-one in detail.</p><h3>1. Physical Layer</h3><p>The Physical Layer is the lowest layer of the TCP/IP model. It deals with data in the form of bits. This layer mainly handles the host to host communication in the network. It defines the transmission medium and mode of communication between two devices. The medium can be wired or wireless, and the <a href="https://afteracademy.com/blog/what-are-the-data-transmission-modes-in-a-network">mode</a> can be simplex, half-duplex, or full-duplex.</p><p>It also specifies the line configuration(point-to-point or multiport), data rate(number of bits sent each second), and <a href="https://afteracademy.com/blog/what-is-network-topology-and-types-of-network-topology">topology</a> in the network. There are no specific <a href="https://afteracademy.com/blog/what-are-protocols-and-what-are-the-key-elements-of-protocols">protocols</a> that are used in this layer. The functionality of the physical layer varies from network-to-network.</p><h3>2. Data-Link Layer</h3><p>The Data-Link Layer is the second layer of the TCP/IP layer. It deals with data in the form of data frames. It mainly performs the data framing in which, it adds some header information to the data packets for the successful delivery of data packets to correct destinations. For this, it performs physical addressing of the data packets by adding the source and the destination address to it.</p><p>The data-link layer facilitates the delivery of frames within the same network. It also facilitates the flow and error control of the data frames. The flow of the data can be controlled through the data rate. Also, the errors in the data transmission and faulty data frames can be detected and retransmitted using the checksum bits in the header information.</p><h3>3. Internet Layer</h3><p>The Internet layer of the TCP/IP model is approximately the same as the Network layer of the <a href="https://afteracademy.com/blog/what-is-the-osi-model-and-how-it-works">OSI model</a>. It deals with data in the form of datagrams or data packets. This layer mainly performs the logical addressing of the data packets by adding the IP(Internet Protocol) address to it. The IP addressing can be done either by using the Internet Protocol Version 4(IPv4) or Internet Protocol Version 6(IPv6).</p><p>The Internet layer also performs routing of data packets using the IP addresses. The data packets can be sent from one network to another using the <a href="https://afteracademy.com/blog/what-are-routers-hubs-switches-bridges">routers</a> in this layer. This layer also performs the sequencing of the data packets at the receiver’s end. In other words, it defines the various <a href="https://afteracademy.com/blog/what-are-protocols-and-what-are-the-key-elements-of-protocols">protocols</a> for logical transmission of data within the same or different network. The protocols that are used in the Internet layer are IP(Internet Protocol), ICMP(Internet Control Message Protocol), IGMP(Internet Group Management Protocol), ARP(Address Resolution Protocol), RARP(Reverse Address Resolution Protocol), etc.</p><h3>4. Transport Layer</h3><p>The Transport layer is the fourth layer of the TCP/IP model. It deals with data in the form of data segments. It mainly performs segmentation of the data received from the upper layers. It is responsible for transporting data and setting up communication between the application layer and the lower layers. This layer facilitates the end-to-end communication and error-free delivery of the data. It also facilitates flow control by specifying data rates. The transport layer is used for process-to-process communication with the help of the port number of the source and the destination.</p><p>The Transport layer facilitates the congestion control using the following protocols:</p><ol><li><strong>TCP: </strong>TCP stands for Transmission Control Protocol. It is a connection-oriented protocol. It performs sequencing and segmentation of data. It also performs flow and error control in data transmission. There is an acknowledgement feature in TCP for the received data. It is a slow but reliable protocol. It is suitable for important and non-real time data items.</li><li><strong>UDP:</strong> UDP stands for User Datagram Protocol. It is a connection-less protocol. It does not perform flow and error control in data transmission. There is no acknowledgement feature in UDP for the received data. It is a fast but unreliable protocol. It is suitable for real-time data items.</li></ol><h3>5. Application Layer</h3><p>The Application layer in the TCP/IP model is equivalent to the upper three layers(Application, Physical, and Session Layer) of the <a href="https://afteracademy.com/blog/what-is-the-osi-model-and-how-it-works">OSI model</a>. It deals with the communication of the whole data message. The Application layer provides an interface between the network services and the application programs. It mainly provides services to the end-users to work over the network. For Example, file transfer, web browsing, etc. This layer uses all the higher-level <a href="https://afteracademy.com/blog/what-are-protocols-and-what-are-the-key-elements-of-protocols">protocols</a> like HTTP, HTTPS, FTP, NFS, DHCP, FMTP, SNMP, SMTP, Telnet, etc.</p><p>The application layer helps in setting up and managing the network connections. It also checks for the user’s program authentication and authorization for the data. It also performs some complex operations like data translation, encryption and decryption, and data compression. The application layer synchronizes the data at the sender’s and the receiver’s end. In other words, it is the topmost layer and defines the interface for application programs with transport layer services.</p><p>This is all about the TCP/IP model and now we will move to the DNS</p><h3>DNS</h3><p>The Domain Name System (DNS) is the phonebook of the Internet. Humans access information online through domain names, like holbertonschool.com Web browsers interact through Internet Protocol (IP) addresses. DNS translates domain names to <a href="https://www.cloudflare.com/learning/dns/glossary/what-is-my-ip-address/">IP addresses</a> so browsers can load Internet resources.</p><p>Each device connected to the Internet has a unique IP address which other machines use to find the device. DNS servers eliminate the need for humans to memorize IP addresses such as 54.88.73.204 (in IPv4), or more complex newer alphanumeric IP addresses such as 2400:cb00:2048:1::c692:d7a2 (inIPv6).</p><h3>Domain name records</h3><p>Even though decentralized, the information about domain names still needs to be recorded and stored. Domain name records are kept by authoritative DNS servers that are commonly hosted by the domain registrar. In addition to hosting the records, an authoritative DNS server is allowed to create, edit, and delete records for the domains delegated to it. Due to this, most registrars offer their users a way to manage the domain name records without deeper knowledge of the inner workings of DNS servers.</p><p>However, it’s important to understand the basics of DNS records. Each domain can have many different types of records that serve different purposes. In essence, DNS records create a set of instructions that allow Internet users to find to their destination web site.</p><p>Below is a short-list of the most commonly used DNS record types:</p><ul><li><strong>A record</strong> holds the IPv4 address of a domain and is the most important of these records. One domain or sub-domain can have a single IP while one IP can have multiple domains pointing to it.</li><li><strong>AAAA record</strong> is essentially the same as A record but for IPv6 addresses.</li><li><strong>PTR record</strong> finds a domain name in a reverse-lookup when the IP is already known. IP addresses usually have one PTR record each, but multiple PTR records can point to the same domain.</li><li><strong>CNAME record</strong>, or canonical name, forward a domain or sub-domain to another domain without providing an IP address. These can be used as aliases to domains.</li><li><strong>MX record</strong> is the mail exchange record that directs mail to an email server. It indicates how email should be routed to its destination.</li><li><strong>TXT record</strong> lets a domain administrator store text notes in the record. These are commonly used to gauge the trustworthiness and verify ownership of a domain.</li><li><strong>NS record</strong> indicates the authoritative name servers. A domain often has multiple name servers, primary and secondary, to prevent outages in case of failures.</li></ul><p>You can check any existing records using domain name lookup tools such as nslookup or dig.</p><h3>Domain Name Resolution Steps</h3><p>Let’s go back to the point where you entered holbertonschool.com in your browser and pressed enter. In the context of DNS, the first that will happen is the browser will check it&#39;s cache to see if it already knows the IP address of holbertonschool.com. <em>Cache</em> is a memory bank that is easy for the browser to access. In other words, if you&#39;ve visited holbertonschool.com recently, the browser will have the destination IP address in it&#39;s cache and the resolution process will end.</p><p>If you’re using Google Chrome you can view your DNS cache by entering</p><pre>chrome://net-internals/#dns</pre><p>You will probably see some familiar URLs and their corresponding IP addresses listed next to them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/0*WRuh1z5X5wwvytzM.jpg" /></figure><p>Let’s imagine holbertonschool.com is not in your browser&#39;s DNS cache.</p><p>Next, the browser will check if any information about the IP address of holbertonschool.com exists in the operating system. There is a file called /etc/hosts on Linux and MacOS machines (C:\Windows\System32\Drivers\etc\hosts on Windows) that stores local DNS information. These files were used more frequently when there wasn&#39;t distributed DNS servers like there are today, but they are still checked by the browser before they head out to the network.</p><p>Let’s assume that the IP address for holbertonschool.com was not found in the hosts file.</p><p>Next, the browser will make a query to a remote DNS server. A DNS server is a server dedicated to resolving domain names to IP addresses. They contain a database of domain names and their corresponding IP addresses, along with addresses of <em>other</em> DNS servers.</p><p>Most Internet Service Providers (ISPs) have servers dedicated to resolving domain names, so it will start with that one since it’s probably the closest. It will ask that server, “do you know the IP address of holbertonschool.com?&quot;</p><p>If it does, great. The resolution process ends. If not, it will query the next DNS server, known as the Root DNS Server. Root DNS servers know information about Top Level Domain (TLD) servers. .com is an example of a TLD. Others are .org, .edu, .co.uk, .cn, and many more.</p><p>We ask the Root DNS Server, “Do you know the IP address of holbertonschool.com?&quot; It replies, &quot;No, but I know about the .com TLD Server. I will forward your query to it.&quot;.</p><p>Since holbertonschool.com ends in .com the Root DNS Server that the browser connected with will send a query to the .com TLD Server.</p><p>The .com TLD Server holds information about the <em>Name Server</em> of the &quot;second-level&quot; domain, in our case, holbertonschool.</p><p>The query gets forwarded to the holbertonschool.com&#39;s Name Server. Whoever registered the domain holbertonschool.com probably knows their domain&#39;s Name Server. If the site is hosted by GoDaddy for example, the Name Server might be ns1.godaddy.com or ns2.godaddy.com.</p><p>Finally, <em>these</em> are the servers that will (hopefully) know the IP address of holbertonschool.com. If not, an error will be sent back to the browser and you will see something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/756/0*LKlgL3zsjfOkOaPG.png" /></figure><p>Note: ERR_NAME_NOT_RESOLVED.</p><h3>DNS Caching</h3><p>The process of resolving a domain name involves a lot of steps. If the resolving process had to be done completely every time you wanted to view a webpage, your experience on the Internet would be slower. As mentioned before, browsers have a caching mechanism so it doesn’t have to initialize an entire recursive resolution process again and again. Only once in a while for unfamiliar websites.</p><p>Not only do browsers have a cache, but DNS servers have cache, too. Servers keep track of domains requested and then store them in a memory bank for some time in order to make the recursive resolution process shorter.</p><p>When someone registers a domain name, they have the option to configure the DNS records for that domain. One of the configuration settings is called <em>Time to Live</em> (TTL).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/565/0*YiUNd8LslI9y9gMn.jpg" /></figure><p>A domain’s TTL is the amount of time, in seconds, that DNS can exists in the cache.</p><p>Let’s say holbertonschool.com, with a TTL of 10 days, decided to launch a new version of their site tomorrow. It would be wise for them to update their DNS records and set their TTL to 0 so that user&#39;s who have holbertonschool.com in their cache don&#39;t see the &quot;old&quot; site on launch day. Later, they can reset their TTL back to 10 days, if they want. Having a longer TTL improve user experience because re-visitors don&#39;t have to go through the whole resolution stage each time they visit the site.</p><h3>Quick Recap</h3><p>So far we have talked about the browser, URLs, TCP/IP protocols, domain names, and DNS. At this point we have resolved holbertonschool.com to the IP address 54.88.73.204 and we are still waiting for the web page to show up.</p><p>Let’s see what happens when we press enter:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uB5w_90WnHE_NK-9X8WsrA.png" /></figure><p>Note the changes what appear in the browser…</p><ol><li>The full URL went from holbertonschool.com to <a href="https://www.holbertonschool.com/">https://www.holbertonschool.com</a></li><li>There is a green padlock icon next to the URL.</li><li>The title “Holberton School of Software Engineering in San Francisco” appears in the title of the browser’s window</li><li>The Holberton School web page is now being displayed.</li></ol><p>Let’s discuss changes 1 and 2; the green padlock and <em>https</em>.</p><h3>HTTPS, SSL, and TLS</h3><p>I know, I know… More acronyms.</p><p>Remember HTTP, the Hyper Text Transfer Protocol? Well, HTTPS is the <em>secured</em> Hyper Text Transfer Protocol. This protocol works similarly to HTTP (client sends a request for a resource, server responds to request), except that the communication is encrypted so it cannot be read by anyone observing network traffic.</p><p>When thinking about security, it’s important to remember that requests and responses usually include many other routers in their journey from client to server. The nature of underlying IP protocols guides the path from the client to the server, selecting a route that it thinks is most efficient. It’s very likely that somewhere in the route there is an observe you don’t want seeing your messages.</p><p>The HTTPS is a requirement for any decent website that asks users to enter their personal information, such as credit card number, address, phone number, etc. Without HTTPS, that information can be seen by network traffic observers.</p><h3>How does it work?</h3><p>The HTTPS protocol involves another protocol called TLS (<em>Transport Layer Security</em>. TLS is a &quot;new and improved&quot; version of SSL (<em>Secure Sockets Layer</em>). Mozilla Developer Network claims that SSL is now considered obsolete, but it is still used in the HTTPS protocol. The main point is that both SSL and TLS are protocols used for security purposes.</p><p>The main two things the Transport Layer Security protocol provides is <strong>authentication</strong> and <strong>encryption</strong>.</p><p>Authentication: ensuring that the client truly is who it claims to be and the server truly is who it claims to me. Authentication is needed because some deceptive attackers dupe clients by posing as the server they are trying to reach.</p><p>Encryption: using cryptographic algorithms to jumble up the messages during the tranmission between client and server so they cannot be understood by anyone except the two parties.</p><p>SSL and TLS use an asymmetric encryption algorithm, which sets two different keys for each party; one for encryption and one for decryption. You encrypt a message with one key, and then decrypt it with another. These keys, known as <em>public</em> and <em>private</em> keys, are mathematically linked so only messages sent to public key A can only be decrypted by private key A.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/586/1*Pi1kNZMUBpJiKR6yA3teEQ.jpeg" /></figure><h3>The TLS Handshake</h3><p>The TLS handshake is a protocol between a client (web browser) and a server (holbertonschool.com) to establish trust and then negotiate what key should be used to encrypt and decrypt traffic between them. Here is what happens during the TLS handshake:</p><ol><li>Client sends Client Hello message. This packet includes the version of TLS, length of the packet, the ciphers (types of encryption) the client can handle, and a random string of bytes that is used to create a master key.</li><li>Server replies with Server Hello message. This packet includes the cipher the server selected to use, a random string of bytes used to create a master key, and information about the server&#39;s certificate of trust.</li><li>Server sends the Certificate to the client. This include information about the insurer (for example, VeriSign), company name, terms of use, dates of validity, and the server&#39;s public key.</li><li>Server sends Certificate Status to the client. Shows whether or not the certificate has been verified successfully. Server also sends Hello Done, marking the end of the introduction between the two.</li><li>Client generates a master (or “secret”) key using the random string of bytes, encoding it with the server’s public key.</li><li>Client sends <em>it’s</em> public key, along with the master key to the server. This is part of the asymmetric encryption key exchange.</li><li>Server receives this key and generates a <em>symmetric</em> key to be used during the session. Symmetric keys are a lot faster and more efficient than asymmetric keys. It’s less secure, but by this point, client and server have been linked with asymmetric keys so the secure connection has already been established. The symmetric key is also generated on the client-side.</li><li>Client sends change cipher spec to server to announce a change from asymmetric to symmetric encryption, along with Client Finished.</li><li>Server sends change cipher spec and Server Finished message (that is now encrypted with the symmetric key)</li><li>Server sends client a new session ticket and the transmissions will not be encrypted across the network.</li></ol><p>Here is a summarized version of how it works in the context of vising holbertonschool.com:</p><ul><li>Your browser has a public key.</li><li>You make a request to holbertonschool.com.</li><li>When the request hits holberton’s server, it says, “This is a secure website. Before I send you any resources I need to establish authentication and encryption.”</li><li>TLS handshake occurs</li><li>Secure session has been established. Green padlock shows up in the address bar, and https appears at the beginning of the URL.</li></ul><h3>HTTP</h3><p>The Hyper Text Transfer Protocol is an application-layer protocol used for transmitting graphics, audio, video, text, and links; collectively known as “hypermedia”. Web pages can be built to display hypermedia using a language called <em>Hypertext Markup Language</em> (HTML).</p><p>This protocol is built upon the request/response paradigm. When you enter holbertonschool.com in your browser and press enter, you are making an HTTP request to a server. In turn, the server will send an HTTP response back to you.</p><p>HTTP requests and responses have two parts: the <em>header</em> and the <em>body</em>. Headers have information about the request formatted in key, value pairs. Body contains the a segment of, or the entire resource requested.</p><p>Here is what an HTTP request header might look like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/327/0*6xT-MEA8Iz7z7HcQ.png" /></figure><p>And an HTTP response header sent back from the server:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/504/0*kIkExE6VXZDg9M44.png" /></figure><p>The body segment of an HTTP request often contains the resource that the browser displays. If it’s a web page, it will certain contain some HTML.</p><h3>HTML</h3><p>Here is what some HTML code looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/608/0*b9C8BmghgraGP-iv.png" /></figure><p>HTML uses tags and plain text to create the structure of the webpage and define how it will look. Along with HTML, web pages may also be using <em>Cascading Style Sheets</em> (CSS) and <em>JavaScript</em> to add more style and functionality to the webpage.</p><p>The name of the file in the image above is called index.html. index.html is a special name that turns out to be the default html page that is displayed when you go to a website if none is specified. In other words, when you visit holbertonschool.com, there is a good chance that the URL of the page that displays is <a href="http://www.holbertonschool.com/index.html.">http://www.holbertonschool.com/index.html.</a></p><p>For the sake of the article, holbertonschool.com is a bad example, because they&#39;re homepage is not index.html. They must have configured their servers to make their home page display a resource named something else.</p><p>To get a glimpse at the HTML, CSS and JavaScript used to display holbertonschool.com you can right click in your browser and select view page source</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hrAMEApQyX6Ba15kICOIZQ.png" /></figure><p>The image above is just a small part of the entire source code, which is nearly 1500 lines.</p><p>The browser reads the HTML, CSS and JavaScript, sends HTTP requests for additional resources needed such as images, videos, or scripts and then renders the web page:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YEUVI2SKu6cLXhHIShMYiA.png" /></figure><p>But what about personalized, <em>dynamic</em> content? For example, when I sign into your amazon.com account it displays <em>my</em> name and it even remembers what I put in my shopping cart.</p><p>When you sign into Netflix, it remembers your favorite shows and exactly what minute and second of an episode of <em>Stranger Things</em> you were watching.</p><p>This is what we call <em>dynamic content</em>. It’s content that is customized for the client.</p><p>It’s possible to serve dynamic content with JavaScript, but robust applications, such as Amazon and Netflix use other components to process requests and serve content dynamically: <strong>application servers</strong> and <strong>database servers</strong>.</p><h3>Application Servers</h3><p>Application servers are servers dedicated to generating static content for the web server. In other words, they take in some parameters such as &quot;name=&quot;Lee&quot;, day=&quot;Monday&quot;, item=&quot;Laptop&quot;, process the parameters through a program, then return a static document to give to the web server, which in turn sends to the client.</p><p>In this example, the application code might look something like:</p><pre>function say_hello(Name, Day, Item) { return &quot;Hello &lt;name&gt;, it is &lt;day&gt;, would you like to buy a &lt;item&gt;? }</pre><p>Depending on the client, this item would generate some static content like “Hello Lee, it is Monday, would you like to buy a laptop?”</p><p>This is kind of a silly example, but the idea is that the web server (which serves <em>static</em> content) is connected with the application server (which generates static content <em>dynamically</em>).</p><p>An application with millions of users like Netflix needs a place to store all the information about their customers in order to deliver a personalized experience. It needs to know their name, account status, billing address, their viewing history, and a lot more. Where do they keep all this information?</p><p>In a database.</p><h3>Database Servers</h3><p>Database servers are servers dedicated to storing and organizing data. When a user signs in to Netflix, a query will be sent to one of Netflix’s database servers asking <a href="/service/mailto:%22john@doe.com">“john@doe.com</a>” is an actual user, if so, it will check the password they entered against the password in the database and then act accordingly by giving them access or denying them access to their account.</p><p>Imagine all the fields in Netflix’s database. Millions of users, each user with tens or hundreds of fields. That must take up a lot of space. Surely, they cannot fit that all on <em>one</em> computer. And what if it goes down? Will everyone lose access to Netflix?</p><p>This brings up some more concepts about web infrastructure: <strong>redundancy</strong>, <strong>availability</strong>, and <strong>security</strong>.</p><h3>Redundancy</h3><p>Let’s first address the questions, “What if Netflix’s database server goes down… Will everyone lose access to the site?”</p><p>Good web architecture has no <em>single point of failure</em>. Meaning, there is no single thing that will cause everything to break. Netflix has <em>redundant</em> database servers that act as backups in case the current one goes down. They also have redundant web servers, and application servers, and redundancy on basically every level of their architecture.</p><h3>Availability</h3><p>You might imagine that the traffic of visitors going to Netflix varies throughout the day. People don’t tend to watch Netflix at work as much as they do when they get home or on the weekend. An application, like Netflix, that performs the same no matter where you are or what time you are using it, is said to be <em>highly available</em>. High availability is something every web application strives for. They do this in many ways, one of which is using a server known as a <strong>load balancer</strong>.</p><p>A load balancer is well-named. It balances the load of traffic across the servers. If an application has a load balancer, it is implied they have multiple web servers behind it. Having multiple web servers can be a sign of redundancy (good), or they could be web servers that are assigned to serve different content. Either way, the load balancer’s job is to take all incoming requests and send them to a server.</p><p>Here is a simple diagram of a <em>haproxy</em> load balancer in front of two web servers:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/0*wznMue65-jAuwsyd.png" /></figure><p>So when we make a request to holbertonschool.com, the first server the request hits is most likely a load balancer. From there it will decide which server to forward the request to.</p><p>Load balancers determine the server to send the request to using algorithms such as:</p><ul><li>Round Robin: if you have 3 servers (A, B and C), the first request goes to A, second to B, third to C, fourth to A, etc.</li><li>Least Connections: choose the server to the one who has the least amount of connections</li><li>Random: literally random.</li><li>Least latency: choose the server that is fastest.</li></ul><p>There are also weighted versions of these algorithms where the server’s administrator can configure each server with a specific weight so they are more or less likely to be chosen to handle the request.</p><p>Using a load balancer helps maintain the health of the application by not putting the whole load of traffic on only one server.</p><p>Well-designed applications will also have redundant load balancers ready in case the main one goes down. Otherwise that would be a single point of failure.</p><h3>Security</h3><p>We’ve talked about HTTPS/SSL/TLS, which is great for encrypting traffic and providing authentication between client and server, but good web architecture goes a step further and installs <em>firewalls</em>.</p><p>A firewall can he a physical device or a piece of software installed on a server that monitors inbound and outbound traffic. Server administrators can configure a firewall to only accept incoming traffic from certain IP addresses, or certain <em>ports</em>, for example.</p><p>By the way, a port is like a door on the interface of a computer on a network. We already know that each computer on a network has an IP address. They also have the ability to utilize ports. As an analogy, you can think of the IP address as a phone number and the port as an extension. Some ports are designated for certain protocols:</p><ul><li>Port 80: HTTP</li><li>Port 443: HTTPS</li><li>Port 53: DNS</li></ul><p>So let’s say you don’t want anyone requesting DNS information about your web server. You can configure a firewall on that server to deny any inbound traffic coming from port 53.</p><p>Firewalls add extra security by defining what kind of traffic you want coming in and out of your server. Unwanted intruders might make a request to your server and slide into the file system through port 123. If your server’s purpose is to serve web content, it would be a good idea to allow traffic <em>only</em> on ports 80 and 443. That way any incoming requests for other ports will be denied.</p><p>Good web architecture will configure firewalls in front of every server to make it clear what time of traffic they want coming in and going out.</p><p>This is all about that press enter lol. Hope you learned something new today. That’s it for this blog.</p><p>Do share this blog with your friends to spread the knowledge.</p><p>Keep Learning :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fc56f387b5e7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is “Internet  Of Things”(IOT)?Absolute Beginners]]></title>
            <link>https://salmenzouari.medium.com/what-is-internet-of-things-iot-absolute-beginners-5e1cd2817d4c?source=rss-2c5a4e892d------2</link>
            <guid isPermaLink="false">https://medium.com/p/5e1cd2817d4c</guid>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[internet-of-things]]></category>
            <category><![CDATA[learning]]></category>
            <category><![CDATA[iot]]></category>
            <dc:creator><![CDATA[Salmen Zouari]]></dc:creator>
            <pubDate>Sun, 08 Mar 2020 02:37:16 GMT</pubDate>
            <atom:updated>2020-03-08T02:37:16.299Z</atom:updated>
            <content:encoded><![CDATA[<h3>What is “Internet Of Things”(IOT)?Absolute Beginners</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/583/1*oGz2Y5UJfOLBTSfj262nnw.jpeg" /></figure><h3>Definition Of Internet Of Things</h3><p>IoT (Internet of Things) is an advanced automation and analytics system which exploits networking, sensing, big data, and artificial intelligence technology to deliver complete systems for a product or service. These systems allow greater transparency, control, and performance when applied to any industry or system.</p><p>IoT systems have applications across industries through their unique flexibility and ability to be suitable in any environment. They enhance data collection, automation, operations, and much more through smart devices and powerful enabling technology.</p><p>This tutorial aims to provide you with a thorough introduction to IoT. It introduces the key concepts of IoT, necessary in using and deploying IoT systems.</p><h3>Overview:</h3><p>IoT systems allow users to achieve deeper automation, analysis, and integration within a system. They improve the reach of these areas and their accuracy. IoT utilizes existing and emerging technology for sensing, networking, and robotics.</p><p>IoT exploits recent advances in software, falling hardware prices, and modern attitudes towards technology. Its new and advanced elements bring major changes in the delivery of products, goods, and services; and the social, economic, and political impact of those changes.</p><h3>IoT − Key Features</h3><p>The most important features of IoT include artificial intelligence, connectivity, sensors, active engagement, and small device use. A brief review of these features is given below −</p><ul><li><strong>AI</strong> − IoT essentially makes virtually anything “smart”, meaning it enhances every aspect of life with the power of data collection, artificial intelligence algorithms, and networks. This can mean something as simple as enhancing your refrigerator and cabinets to detect when milk and your favorite cereal run low, and to then place an order with your preferred grocer.</li><li><strong>Connectivity</strong> − New enabling technologies for networking, and specifically IoT networking, mean networks are no longer exclusively tied to major providers. Networks can exist on a much smaller and cheaper scale while still being practical. IoT creates these small networks between its system devices.</li><li><strong>Sensors</strong> − IoT loses its distinction without sensors. They act as defining instruments which transform IoT from a standard passive network of devices into an active system capable of real-world integration.</li><li><strong>Active Engagement</strong> − Much of today’s interaction with connected technology happens through passive engagement. IoT introduces a new paradigm for active content, product, or service engagement.</li><li><strong>Small Devices</strong> − Devices, as predicted, have become smaller, cheaper, and more powerful over time. IoT exploits purpose-built small devices to deliver its precision, scalability, and versatility.</li></ul><h3>IoT − Advantages</h3><p>The advantages of IoT span across every area of lifestyle and business. Here is a list of some of the advantages that IoT has to offer −</p><ul><li><strong>Improved Customer Engagement</strong> − Current analytics suffer from blind-spots and significant flaws in accuracy; and as noted, engagement remains passive. IoT completely transforms this to achieve richer and more effective engagement with audiences.</li><li><strong>Technology Optimization</strong> − The same technologies and data which improve the customer experience also improve device use, and aid in more potent improvements to technology. IoT unlocks a world of critical functional and field data.</li><li><strong>Reduced Waste</strong> − IoT makes areas of improvement clear. Current analytics give us superficial insight, but IoT provides real-world information leading to more effective management of resources.</li><li><strong>Enhanced Data Collection</strong> − Modern data collection suffers from its limitations and its design for passive use. IoT breaks it out of those spaces, and places it exactly where humans really want to go to analyze our world. It allows an accurate picture of everything.</li></ul><h3>IoT − Disadvantages</h3><p>Though IoT delivers an impressive set of benefits, it also presents a significant set of challenges. Here is a list of some its major issues −</p><ul><li><strong>Security</strong> − IoT creates an ecosystem of constantly connected devices communicating over networks. The system offers little control despite any security measures. This leaves users exposed to various kinds of attackers.</li><li><strong>Privacy</strong> − The sophistication of IoT provides substantial personal data in extreme detail without the user’s active participation.</li><li><strong>Complexity</strong> − Some find IoT systems complicated in terms of design, deployment, and maintenance given their use of multiple technologies and a large set of new enabling technologies.</li><li><strong>Flexibility</strong> − Many are concerned about the flexibility of an IoT system to integrate easily with another. They worry about finding themselves with several conflicting or locked systems.</li><li><strong>Compliance</strong> − IoT, like any other technology in the realm of business, must comply with regulations. Its complexity makes the issue of compliance seem incredibly challenging when many consider standard software compliance a battle.</li></ul><h3>Internet of Things — Hardware</h3><p>The hardware utilized in IoT systems includes devices for a remote dashboard, devices for control, servers, a routing or bridge device, and sensors. These devices manage key tasks and functions such as system activation, action specifications, security, communication, and detection to support-specific goals and actions.</p><h3>IoT − Sensors</h3><p>The most important hardware in IoT might be its sensors. These devices consist of energy modules, power management modules, RF modules, and sensing modules. RF modules manage communications through their signal processing, WiFi, ZigBee, Bluetooth, radio transceiver, duplexer, and BAW.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*0ch0FtXp3iHsoW1u.jpg" /></figure><p>The sensing module manages sensing through assorted active and passive measurement devices. Here is a list of some of the measurement devices used in IoT −</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/670/1*KkICSCKBQF4CJ7XPM9x7JQ.png" /></figure><h3>Wearable Electronics</h3><p>Wearable electronic devices are small devices worn on the head, neck, arms, torso, and feet.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*VJfotN4RFfiMalYJ.jpg" /></figure><blockquote>Smartwatches not only help us stay connected, but as a part of an IoT system, they allow access needed for improved productivity.</blockquote><p>Current smart wearable devices include −</p><ul><li><strong>Head</strong> − Helmets, glasses</li><li><strong>Neck</strong> − Jewelry, collars</li><li><strong>Arm</strong> − Watches, wristbands, rings</li><li><strong>Torso</strong> − Clothing, backpacks</li><li><strong>Feet</strong> − Socks, shoes</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*E2U7ZnfblAx1wzUK.jpg" /></figure><blockquote>Smart glasses help us enjoy more of the media and services we value, and when part of an IoT system, they allow a new approach to productivity.</blockquote><h3>Standard Devices</h3><p>The desktop, tablet, and cellphone remain integral parts of IoT as the command center and remotes.</p><ul><li>The <strong>desktop</strong> provides the user with the highest level of control over the system and its settings.</li><li>The <strong>tablet</strong> provides access to the key features of the system in a way resembling the desktop, and also acts as a remote.</li><li>The <strong>cellphone</strong> allows some essential settings modification and also provides remote functionality.</li></ul><p>Other key connected devices include standard network devices like <strong>routers</strong> and <strong>switches</strong>.</p><h3>Internet of Things — Software</h3><p>IoT software addresses its key areas of networking and action through platforms, embedded systems, partner systems, and middleware. These individual and master applications are responsible for data collection, device integration, real-time analytics, and application and process extension within the IoT network. They exploit integration with critical business systems (e.g., ordering systems, robotics, scheduling, and more) in the execution of related tasks.</p><h3>Data Collection</h3><p>This software manages sensing, measurements, light data filtering, light data security, and aggregation of data. It uses certain protocols to aid sensors in connecting with real-time, machine-to-machine networks. Then it collects data from multiple devices and distributes it in accordance with settings. It also works in reverse by distributing data over devices. The system eventually transmits all collected data to a central server.</p><h3>Device Integration</h3><p>Software supporting integration binds (dependent relationships) all system devices to create the body of the IoT system. It ensures the necessary cooperation and stable networking between devices. These applications are the defining software technology of the IoT network because without them, it is not an IoT system. They manage the various applications, protocols, and limitations of each device to allow communication.</p><h3>Real-Time Analytics</h3><p>These applications take data or input from various devices and convert it into viable actions or clear patterns for human analysis. They analyze information based on various settings and designs in order to perform automation-related tasks or provide the data required by industry.</p><h3>Application and Process Extension</h3><p>These applications extend the reach of existing systems and software to allow a wider, more effective system. They integrate predefined devices for specific purposes such as allowing certain mobile devices or engineering instruments access. It supports improved productivity and more accurate data collection.</p><h3>Internet of Things — Technology and Protocols</h3><p>IoT primarily exploits standard protocols and networking technologies. However, the major enabling technologies and protocols of IoT are RFID, NFC, low-energy Bluetooth, low-energy wireless, low-energy radio protocols, LTE-A, and WiFi-Direct. These technologies support the specific networking functionality needed in an IoT system in contrast to a standard uniform network of common systems.</p><h3>NFC and RFID</h3><p>RFID (radio-frequency identification) and NFC (near-field communication) provide simple, lowenergy, and versatile options for identity and access tokens, connection bootstrapping, and payments.</p><ul><li>RFID technology employs 2-way radio transmitter-receivers to identify and track tags associated with objects.</li><li>NFC consists of communication protocols for electronic devices, typically a mobile device and a standard device.</li></ul><h3>Low-Energy Bluetooth</h3><p>This technology supports the low-power, long-use need of IoT function while exploiting a standard technology with native support across systems.</p><h3>Low-Energy Wireless</h3><p>This technology replaces the most power hungry aspect of an IoT system. Though sensors and other elements can power down over long periods, communication links (i.e., wireless) must remain in listening mode. Low-energy wireless not only reduces consumption, but also extends the life of the device through less use.</p><h3>Radio Protocols</h3><p>ZigBee, Z-Wave, and Thread are radio protocols for creating low-rate private area networks. These technologies are low-power, but offer high throughput unlike many similar options. This increases the power of small local device networks without the typical costs.</p><h3>LTE-A</h3><p>LTE-A, or LTE Advanced, delivers an important upgrade to LTE technology by increasing not only its coverage, but also reducing its latency and raising its throughput. It gives IoT a tremendous power through expanding its range, with its most significant applications being vehicle, UAV, and similar communication.</p><h3>WiFi-Direct</h3><p>WiFi-Direct eliminates the need for an access point. It allows P2P (peer-to-peer) connections with the speed of WiFi, but with lower latency. WiFi-Direct eliminates an element of a network that often bogs it down, and it does not compromise on speed or throughput.</p><h3>Internet of Things — Security</h3><p>Every connected device creates opportunities for attackers. These vulnerabilities are broad, even for a single small device. The risks posed include data transfer, device access, malfunctioning devices, and always-on/always-connected devices.</p><p>The main challenges in security remain the security limitations associated with producing lowcost devices, and the growing number of devices which creates more opportunities for attacks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*5ln830p1o7EgE8aT.jpg" /></figure><h3>Security Spectrum</h3><p>The definition of a secured device spans from the most simple measures to sophisticated designs. Security should be thought of as a spectrum of vulnerability which changes over time as threats evolve.</p><p>Security must be assessed based on user needs and implementation. Users must recognize the impact of security measures because poorly designed security creates more problems than it solves.</p><p><strong>Example</strong> − A German report revealed hackers compromised the security system of a steel mill. They disrupted the control systems, which prevented a blast furnace from being shut down properly, resulting in massive damage. Therefore, users must understand the impact of an attack before deciding on appropriate protection.</p><h3>Challenges</h3><p>Beyond costs and the ubiquity of devices, other security issues plague IoT −</p><ul><li><strong>Unpredictable Behavior</strong> − The sheer volume of deployed devices and their long list of enabling technologies means their behavior in the field can be unpredictable. A specific system may be well designed and within administration control, but there are no guarantees about how it will interact with others.</li><li><strong>Device Similarity</strong> − IoT devices are fairly uniform. They utilize the same connection technology and components. If one system or device suffers from a vulnerability, many more have the same issue.</li><li><strong>Problematic Deployment</strong> − One of the main goals of IoT remains to place advanced networks and analytics where they previously could not go. Unfortunately, this creates the problem of physically securing the devices in these strange or easily accessed places.</li><li><strong>Long Device Life and Expired Support</strong> − One of the benefits of IoT devices is longevity, however, that long life also means they may outlive their device support. Compare this to traditional systems which typically have support and upgrades long after many have stopped using them. Orphaned devices and abandonware lack the same security hardening of other systems due to the evolution of technology over time.</li><li><strong>No Upgrade Support</strong> − Many IoT devices, like many mobile and small devices, are not designed to allow upgrades or any modifications. Others offer inconvenient upgrades, which many owners ignore, or fail to notice.</li><li><strong>Poor or No Transparency</strong> − Many IoT devices fail to provide transparency with regard to their functionality. Users cannot observe or access their processes, and are left to assume how devices behave. They have no control over unwanted functions or data collection; furthermore, when a manufacturer updates the device, it may bring more unwanted functions.</li><li><strong>No Alerts</strong> − Another goal of IoT remains to provide its incredible functionality without being obtrusive. This introduces the problem of user awareness. Users do not monitor the devices or know when something goes wrong. Security breaches can persist over long periods without detection.</li></ul><h3>Internet of Things — Identity Protection</h3><p>IoT devices collect data about their environment, which includes people. These benefits introduce heavy risk. The data itself does not present the danger, however, its depth does. The highly detailed data collection paints a very clear picture of an individual, giving criminals all the information they need to take advantage of someone.</p><p>People may also not be aware of the level of privacy; for example, entertainment devices may gather A/V data, or “watch” a consumer, and share intimate information. The demand and price for this data exacerbates the issue considering the number and diversity of parties interested in sensitive data.</p><p>Problems specific to IoT technology lead to many of its privacy issues, which primarily stem from the user’s inability to establish and control privacy −</p><h3>Consent</h3><p>The traditional model for “notice and consent” within connected systems generally enforces existing privacy protections. It allows users to interact with privacy mechanisms, and set preferences typically through accepting an agreement or limiting actions. Many IoT devices have no such accommodations. Users not only have no control, but they are also not afforded any transparency regarding device activities.</p><h3>The Right to be Left Alone</h3><p>Users have normal expectations for privacy in certain situations. This comes from the commonly accepted idea of public and private spaces; for example, individuals are not surprised by surveillance cameras in commercial spaces, however, they do not expect them in their personal vehicle. IoT devices challenge these norms people recognize as the “right to be left alone.” Even in public spaces, IoT creeps beyond the limits of expected privacy due to its power.</p><h3>Indistinguishable Data</h3><p>IoT deploys in a wide variety of ways. Much of IoT implementation remains group targeted rather than personal. Even if users give IoT devices consent for each action, not every system can reasonably process every set of preferences; for example, small devices in a complex assembly cannot honor the requests of tens of thousands of users they encounter for mere seconds.</p><h3>Granularity</h3><p>Modern big data poses a substantial threat to privacy, but IoT compounds the issue with its scale and intimacy. It goes not only where passive systems cannot, but it collects data everywhere. This supports creation of highly detailed profiles which facilitate discrimination and expose individuals to physical, financial, and reputation harm.</p><h3>Comfort</h3><p>The growth of IoT normalizes it. Users become comfortable with what they perceive as safe technology. IoT also lacks the transparency that warns users in traditional connected systems; consequently, many act without any consideration for the potential consequences.</p><p>That’s it i hope that it was clear and helpful. What do you think? Tell me in the comments below.</p><p>Here are some of the books that helped me to write this blog you should take a look if you are interested in IOF:</p><p><a href="https://www.amazon.com/IOT-Enabled-Internet-Things-career-ebook/dp/B01GAAV4OY/httpwwwtuto0a-20">https://www.amazon.com/IOT-Enabled-Internet-Things-career-ebook/dp/B01GAAV4OY/httpwwwtuto0a-20</a></p><p><a href="https://www.amazon.com/Learning-Internet-Things-Peter-Waher/dp/1783553537/httpwwwtuto0a-20">https://www.amazon.com/Learning-Internet-Things-Peter-Waher/dp/1783553537/httpwwwtuto0a-20</a></p><p><a href="https://www.amazon.com/Internet-Things-Press-Essential-Knowledge/dp/0262527731/httpwwwtuto0a-20">https://www.amazon.com/Internet-Things-Press-Essential-Knowledge/dp/0262527731/httpwwwtuto0a-20</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5e1cd2817d4c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Machine Learning: For My Grandfather (For Beginners)]]></title>
            <link>https://salmenzouari.medium.com/machine-learning-for-my-grandfather-for-beginners-ab1966d5c6bd?source=rss-2c5a4e892d------2</link>
            <guid isPermaLink="false">https://medium.com/p/ab1966d5c6bd</guid>
            <category><![CDATA[unsupervised-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[supervised-learning]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[inteligencia-artificial]]></category>
            <dc:creator><![CDATA[Salmen Zouari]]></dc:creator>
            <pubDate>Sun, 26 Jan 2020 17:50:33 GMT</pubDate>
            <atom:updated>2020-01-26T17:50:33.214Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*DOlJsNMV7MHhsE_IGAFoQg.jpeg" /></figure><h3>Definition Of The Machine Learning</h3><p>In a way, Machine Learning works in a similar way to human learning. For example, if a child is shown images with specific objects on them, they can learn to identify and differentiate between them. Machine Learning works in the same way: Through data input and certain commands, the computer is enabled to “learn” to identify certain objects (persons, objects, etc.) and to distinguish between them. For this purpose, the software is supplied with data and trained. For instance, the programmer can tell the system that a particular object is a human being (=”human”) and another object is not a human being (=”no human”). The software receives continuous feedback from the programmer. These feedback signals are used by the algorithm to adapt and optimize the model. With each new data set fed into the system, the model is further optimized so that it can clearly distinguish between “humans” and “non-humans” in the end.</p><p>Machine Learning is a sub-area of artificial intelligence, whereby the term refers to the ability of IT systems to independently find solutions to problems by recognizing patterns in databases. In other words: Machine Learning enables IT systems to recognize patterns on the basis of existing algorithms and data sets and to develop adequate solution concepts. Therefore, in Machine Learning, artificial knowledge is generated on the basis of experience.</p><p>In order to enable the software to independently generate solutions, the prior action of people is necessary. For example, the required algorithms and data must be fed into the systems in advance and the respective analysis rules for the recognition of patterns in the data stock must be defined. Once these two steps have been completed, the system can perform the following tasks by Machine Learning:</p><ul><li>Finding, extracting and summarizing relevant data</li><li>Making predictions based on the analysis data</li><li>Calculating probabilities for specific results</li><li>Adapting to certain developments autonomously</li><li>Optimizing processes based on recognized patterns</li></ul><h3>How it works</h3><p>Machine learning uses two types of techniques: <strong>supervised learning</strong>, which trains a model on known input and output data so that it can predict future outputs, and <strong>unsupervised learning</strong>, which finds hidden patterns or intrinsic structures in input data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/649/1*H_AhOSxZorbTxzIKBhQWOA.png" /></figure><p>Figure 1. Machine learning techniques include both unsupervised and supervised learning</p><h3>Supervised Learning</h3><p><a href="https://www.mathworks.com/discovery/supervised-learning.html">Supervised machine learning</a> builds a model that makes predictions based on evidence in the presence of uncertainty. A supervised learning algorithm takes a known set of input data and known responses to the data (output) and trains a model to generate reasonable predictions for the response to new data. Use supervised learning if you have known data for the output you are trying to predict.</p><p>Supervised learning uses classification and regression techniques to develop predictive models.</p><p><strong>Classification techniques</strong> predict discrete responses — for example, whether an email is genuine or spam, or whether a tumor is cancerous or benign. Classification models classify input data into categories. Typical applications include medical imaging, speech recognition, and credit scoring.</p><p>Use classification if your data can be tagged, categorized, or separated into specific groups or classes. For example, applications for hand-writing recognition use classification to recognize letters and numbers. In image processing and computer vision, <a href="https://www.mathworks.com/discovery/pattern-recognition.html">unsupervised pattern recognition</a> techniques are used for object detection and image segmentation.</p><p>Common algorithms for performing classification include <a href="https://www.mathworks.com/help/stats/support-vector-machine-classification.html">support vector machine (SVM)</a>, <a href="https://www.mathworks.com/help/stats/classification-ensembles.html">boosted</a> and <a href="https://www.mathworks.com/help/stats/classification-ensembles.html">bagged</a> <a href="https://www.mathworks.com/help/stats/classification-trees.html">decision trees</a>, <a href="https://www.mathworks.com/help/stats/classification-nearest-neighbors.html"><em>k</em>-nearest neighbor</a>, <a href="https://www.mathworks.com/help/stats/classification-naive-bayes.html">Naïve Bayes</a>, <a href="https://www.mathworks.com/help/stats/classification-discriminant-analysis.html">discriminant analysis</a>, <a href="https://www.mathworks.com/help/stats/generalized-linear-regression-1.html">logistic regression</a>, and <a href="https://www.mathworks.com/help/deeplearning/pattern-recognition-and-classification.html">neural networks</a>.</p><p><strong>Regression techniques</strong> predict continuous responses — for example, changes in temperature or fluctuations in power demand. Typical applications include electricity load forecasting and algorithmic trading.</p><p>Use regression techniques if you are working with a data range or if the nature of your response is a real number, such as temperature or the time until failure for a piece of equipment.</p><p>Common regression algorithms include <a href="https://www.mathworks.com/help/stats/multiple-linear-regression-1.html">linear model</a>, <a href="https://www.mathworks.com/help/stats/nonlinear-models.html">nonlinear model</a>, <a href="https://www.mathworks.com/help/stats/regularization-1.html">regularization</a>, <a href="https://www.mathworks.com/help/stats/stepwise-regression-1.html">stepwise regression</a>, <a href="https://www.mathworks.com/help/stats/classification-ensembles.html">boosted</a> and <a href="https://www.mathworks.com/help/stats/classification-ensembles.html">bagged</a> <a href="https://www.mathworks.com/help/stats/classification-trees.html">decision trees</a>, <a href="https://www.mathworks.com/help/deeplearning/function-approximation-and-nonlinear-regression.html">neural networks</a>, and <a href="https://www.mathworks.com/help/fuzzy/anfis.html">adaptive neuro-fuzzy learning</a>.</p><h3>Unsupervised Learning</h3><p><a href="https://www.mathworks.com/discovery/unsupervised-learning.html">Unsupervised learning</a> finds hidden patterns or intrinsic structures in data. It is used to draw inferences from datasets consisting of input data without labeled responses.</p><p><strong>Clustering</strong> is the most common unsupervised learning technique. It is used for exploratory data analysis to find hidden patterns or groupings in data. Applications for <a href="https://www.mathworks.com/discovery/cluster-analysis.html">cluster analysis</a> include gene sequence analysis, market research, and object recognition.</p><p>For example, if a cell phone company wants optimize the locations where they build cell phone towers, they can use machine learning to estimate the number of clusters of people relying on their towers. A phone can only talk to one tower at a time, so the team uses clustering algorithms to design the best placement of cell towers to optimize signal reception for groups, or clusters, of their customers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/378/1*GbyZXqXs0sHnGBmO3hKX7A.png" /></figure><p>Figure 2. Clustering finds hidden patterns in your data.</p><h3>How Do You Decide Which Machine Learning Algorithm to Use?</h3><p>Choosing the right algorithm can seem overwhelming — there are dozens of supervised and unsupervised machine learning algorithms, and each takes a different approach to learning.</p><p>There is no best method or one size fits all. Finding the right algorithm is partly just trial and error — even highly experienced data scientists can’t tell whether an algorithm will work without trying it out. But algorithm selection also depends on the size and type of data you’re working with, the insights you want to get from the data, and how those insights will be used.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/422/1*v07w6cEgfPbFT3WAX6UOow.png" /></figure><p>Figure 3. Machine learning techniques.</p><h3>Advantages of Machine Learning</h3><p>Machine Learning undoubtedly helps people to work more creatively and efficiently. Basically, you too can delegate quite complex or monotonous work to the computer through Machine Learning — starting with scanning, saving and filing paper documents such as invoices up to organizing and editing images.</p><p>In addition to these rather simple tasks, self-learning machines can also perform complex tasks. These include, for example, the recognition of error patterns. This is a major advantage, especially in areas such as the manufacturing industry: the industry relies on continuous and error-free production. While even experts often cannot be sure where and by which correlation a production error in a plant fleet arises, Machine Learning offers the possibility to identify the error early — this saves downtimes and money.</p><p>Self-learning programs are now also used in the medical field. In the future, after “consuming” huge amounts of data (medical publications, studies, etc.), apps will be able to warn a in case his doctor wants to prescribe a drug that he cannot tolerate. This “knowledge” also means that the app can propose alternative options which for example also take into account the genetic requirements of the respective patient.</p><h3>Machine Learning: The technology leaders</h3><p>In addition to Microsoft, Google, Facebook, IBM and Amazon, Apple also spends enormous financial resources on the use and further development of Machine Learning. IBM’s Watson supercomputer is still the best-known appliance for Machine Learning. Watson is mainly used in the medical and financial sectors. As already mentioned, Facebook uses Machine Learning for image recognition, Microsoft for the speech recognition system Cortana, Apple for Siri. Of course, Machine Learning is also used at Google, both in the area of image services and search engine ranking.</p><p>Cloud providers such as Google, Microsoft, Amazon Webservice and IBM have now created services for Machine Learning. With their help it is also possible for developers who do not have specific Machine Learning knowledge to develop applications. These applications are able to learn from a freely definable set of data. Depending on the provider, these platforms have different names:</p><ul><li>IBM: Watson</li><li>Amazon: Amazon Machine Learning</li><li>Microsoft: Azure ML Studio</li><li>Google: Tensorflow</li></ul><h3>Disadvantages of Machine Learning</h3><p>With all those advantages to its powerfulness and popularity, Machine Learning isn’t perfect. The following factors serve to limit it:</p><h4>1. Data Acquisition</h4><p>Machine Learning requires massive data sets to train on, and these should be inclusive/unbiased, and of good quality. There can also be times where they must wait for new data to be generated.</p><h4>2. Time and Resources</h4><p>ML needs enough time to let the algorithms learn and develop enough to fulfill their purpose with a considerable amount of accuracy and relevancy. It also needs massive resources to function. This can mean additional requirements of computer power for you.</p><h4>3. Interpretation of Results</h4><p>Another major challenge is the ability to accurately interpret results generated by the algorithms. You must also carefully choose the algorithms for your purpose.</p><h4>4. High error-susceptibility</h4><p><a href="https://en.wikipedia.org/wiki/Machine_learning">Machine Learning</a> is autonomous but highly susceptible to errors. Suppose you train an algorithm with data sets small enough to not be inclusive. You end up with biased predictions coming from a biased training set. This leads to irrelevant advertisements being displayed to customers. In the case of ML, such blunders can set off a chain of errors that can go undetected for long periods of time. And when they do get noticed, it takes quite some time to recognize the source of the issue, and even longer to correct it.</p><h3>Summary</h3><p>As a result, we have studied Advantages and Disadvantages of Machine Learning. Also, this blog helps an individual to understand why one needs to choose machine learning. While Machine Learning can be incredibly powerful when used in the right ways and in the right places (where massive training data sets are available), it certainly isn’t for everyone. You may also like to read <a href="https://data-flair.training/blogs/deep-learning-vs-machine-learning/">Deep Learning Vs Machine Learning</a>.</p><p>What do you think? Tell us in the comments below.</p><p>here are some of the ressources that helped me to write this blog you should take if you are interested in Machine Learning:</p><p><a href="https://www.spotlightmetal.com/machine-learning--definition-and-application-examples-a-746226/?cmp=go-aw-art-trf-SLM_DSA-20180820&amp;gclid=CjwKCAiAjrXxBRAPEiwAiM3DQh1gHKP6etFJhiTwosAtwPDEOM2qj1IcLwd-Bvvdp0mSm3xvLC6eqBoC6r4QAvD_BwE">Machine Learning - Definition and application examples</a></p><p><a href="https://www.mathworks.com/discovery/machine-learning.html">https://www.mathworks.com/discovery/machine-learning.html</a></p><p><a href="https://data-flair.training/blogs/advantages-and-disadvantages-of-machine-learning/">https://data-flair.training/blogs/advantages-and-disadvantages-of-machine-learning/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ab1966d5c6bd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Everything is object(Python)]]></title>
            <link>https://salmenzouari.medium.com/everything-is-object-python-3ea6fbf69a99?source=rss-2c5a4e892d------2</link>
            <guid isPermaLink="false">https://medium.com/p/3ea6fbf69a99</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[oop]]></category>
            <dc:creator><![CDATA[Salmen Zouari]]></dc:creator>
            <pubDate>Fri, 17 Jan 2020 20:58:29 GMT</pubDate>
            <atom:updated>2020-01-17T20:58:29.719Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Et0dZhfwrHX_K-XVNYBvvA.png" /></figure><h3>Introduction</h3><p>What makes the Python programming language different from low-level languages such as C? Python is an Object Oriented Programming (OOP) language — what does that mean? It means the Python programming language consists of objects, which allows the user to have their own methods and attributes without having to re-create them each time. Python is built off of a data structure called the PyObject, which is what all the data types inherit from — hence why the language consists of objects.</p><h3>What is an id and type?</h3><p>What are id and types in Python? Ids and Types are objects — remember that Python is made up of objects! An id “returns the identity of an object” and each one is “unique and constant” for the object as long as you use it. For example:</p><pre># Declaring two string objects:&gt;&gt;&gt; obj1 = &quot;Hi&quot;<br>&gt;&gt;&gt; obj2 = &quot;Guillaume&quot;# Getting their ids:&gt;&gt;&gt; id(obj1)<br>139725014564344&gt;&gt;&gt; id(obj2)<br>139725014575280</pre><p>As you can see, obj1 and obj2 each have their own unique ids. Ok, now what happens if I assign two objects to point to the same thing like the below:</p><pre>&gt;&gt;&gt; obj3 = &quot;Guillaume&quot;<br>&gt;&gt;&gt; obj4 = &quot;Guillaume&quot;</pre><p>What would happen if I ask for the id of both? Would they be the same or different?</p><pre>&gt;&gt;&gt; id(obj3)<br>139725014575280&gt;&gt;&gt; id(obj4)<br>139725014575280</pre><p>They are the same, but why? When two objects are referring to the same value, this is known as an alias. However, what happens if the objects are mutable? We’ll talk about that in the next section, but first, what are types?</p><p>Types are objects, again! Type in Python is used to “return the type of an object” and its “return value is a type object and generally the same object as returned by object.__class__. So, if you wanted to find out what type is your variable, you can do this:</p><pre># Declaring an object named obj1:&gt;&gt;&gt; obj1 = &quot;Julien&quot;# Finding its type:&gt;&gt;&gt; type(obj1)<br>&lt;class &#39;str&#39;&gt;</pre><h3>Mutable Objects</h3><p>What are mutable objects? Mutable objects are objects whose values can change — examples of mutable objects are lists, dict, set, byte array.</p><p>You might think that strings are mutable objects, but what happens if you concatenate the string with another string?</p><pre>&gt;&gt;&gt; str1 = &quot;Julien might win at Starcraft&quot;<br>&gt;&gt;&gt; str2 = &quot; or he might lose.&quot;<br>&gt;&gt;&gt; str1 += str2<br>&gt;&gt;&gt; print(str1)<br>Julien might win at Starcraft or he might lose.</pre><p>A third string is created when you concatenate the two strings, but what if the strings are the same? If they are the same, in memory, a pointer will point to the spot. For example, using id:</p><pre># Assigning two objects to the same string<br>&gt;&gt;&gt; a = &quot;b&quot;<br>&gt;&gt;&gt; b = &quot;b&quot;<br>&gt;&gt;&gt; id(a), id(b)<br>(139873424855424, 139873424855424)# Both strings have the same id# Adding third object &#39;c&#39;&gt;&gt;&gt; c = &quot;c&quot;<br>&gt;&gt;&gt; id(c)<br>139873424786912<br>&gt;&gt;&gt; a += c<br>&gt;&gt;&gt; print(a)<br>bc<br>&gt;&gt;&gt; id(a)<br>139873423703824</pre><p>As you can see, a has a new id after the two strings are concatenated.</p><h3>Immutable Objects</h3><p>What about immutable objects? Immutable objects consists of number, string, tuple, frozen set, and bytes. These are objects that can’t be manipulated; for example:</p><pre># Declaring a tuple object:&gt;&gt;&gt; a = (1, )<br>&gt;&gt;&gt; a.append(3)# Getting an error when I try to append a new number to the tupleTraceback (most recent call last):<br>File &quot;&lt;stdin&gt;&quot;, line 1, in &lt;module&gt;<br>AttributeError: &#39;tuple&#39; object has no attribute &#39;append&#39;</pre><p>I can’t add or change the original tuple, but I can re-assign a to a new tuple:</p><pre>&gt;&gt;&gt; a = (2, )<br>&gt;&gt;&gt; print(a)<br>(2,)<br>&gt;&gt;&gt;</pre><p>However, for tuples and frozen sets, even though they are immutable objects, Python handles them the same way as mutable since they may contain mutable objects.</p><h3>Preallocation in Python</h3><p>In Python, upon startup, Python3 keeps an array of integer objects, from -5 to 256. For example, for the int object, marcos called NSMALLPOSINTS and NSMALLNEGINTS are used:</p><pre>#ifndef NSMALLPOSINTS<br>#define NSMALLPOSINTS           257<br>#endif<br>#ifndef NSMALLNEGINTS<br>#define NSMALLNEGINTS           5<br>#endif<br>#if NSMALLNEGINTS + NSMALLPOSINTS &gt; 0<br>/* References to small integers are saved in this array so that they<br>   can be shared.<br>   The integers that are saved are those in the range<br>   -NSMALLNEGINTS (inclusive) to NSMALLPOSINTS (not inclusive).<br>*/<br>static PyIntObject *small_ints[NSMALLNEGINTS + NSMALLPOSINTS];<br>#endif<br>#ifdef COUNT_ALLOCS<br>Py_ssize_t quick_int_allocs;<br>Py_ssize_t quick_neg_int_allocs;<br>#endif</pre><p>What does this mean? This means that when you create an int from the range of -5 and 256, you are actually referencing to the existing object.</p><h3>Assignment vs Referencing</h3><p>What does assignment and referencing mean in Python? In Python, it uses something called “Call by Object Reference”, for example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/250/0*1vOqCmK0JtLVFRRp.png" /></figure><p>If you pass immutable objects as arguments, they are passed by value since they can not be changed. However, if you passed a mutable object argument, you are passing the object as a reference because the objects can be changed. For example, if you pass a list to a function, lists can be changed since they are mutable; “if a new list is created, the old list will not be affected”.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3ea6fbf69a99" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>