<?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[Aorb Tech - Medium]]></title>
        <description><![CDATA[Empowering people, transforming businesses &amp; creating impact through AI, innovation and technology. #AorbTech - Medium]]></description>
        <link>https://medium.com/machine-learning-researcher?source=rss----32a2162bf0c7---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Aorb Tech - Medium</title>
            <link>https://medium.com/machine-learning-researcher?source=rss----32a2162bf0c7---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 02:51:27 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/machine-learning-researcher" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Auto Encoder]]></title>
            <link>https://medium.com/machine-learning-researcher/auto-encoder-d942a29c9807?source=rss----32a2162bf0c7---4</link>
            <guid isPermaLink="false">https://medium.com/p/d942a29c9807</guid>
            <category><![CDATA[encoding-decoding]]></category>
            <category><![CDATA[encoding]]></category>
            <category><![CDATA[autoencoder]]></category>
            <category><![CDATA[decoding]]></category>
            <category><![CDATA[neural-networks]]></category>
            <dc:creator><![CDATA[Amir Ali]]></dc:creator>
            <pubDate>Sun, 26 May 2019 13:25:22 GMT</pubDate>
            <atom:updated>2019-12-08T05:33:31.694Z</atom:updated>
            <content:encoded><![CDATA[<h3>Auto Encoder with Practical Implementation</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*3eCXNRbhDP772E8OxX-tFA.png" /></figure><p>In this Chapter of Deep Learning, we will discuss Auto Encoders. It is an Unsupervised Deep Learning technique and we will discuss both theoretical and Practical Implementation from Scratch.</p><p><strong>This chapter spans 5 parts:</strong></p><ol><li>What is Auto-Encoders?</li><li>Structure of Auto-Encoders.</li><li>How does Auto-Encoders work?</li><li>Different Types of Auto-Encoders.</li><li>Practical Implementation of Auto-Encoders.</li></ol><h3>1. <strong>What is Auto-Encoders?</strong></h3><p>An autoencoder is a neural network that tries to reconstruct its input.</p><p>So if you feed the autoencoder the vector (1,0,0,0) the autoencoder will try to output (1,0,0,0). Of course, I will have to explain why this is useful and how this works.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*JBvQp1GSGYuAN_nCBj4IDw.png" /></figure><p>The trick is the hidden layer, say you have inputs in 4 dimensions as in our example if we use 2 neurons in the hidden layer then our autoencoder will receive 4 features, and “encode” them in 2 features in a way such as it can re-construct the same 4 dim input.</p><p>So we go from (1,0,0,0) to (x,y) and from (x,y) to (1,0,0,0).</p><p>We train the autoencoder with several points of data, maybe thousands of millions and it will find the weights that minimize the reconstruction error. The weights are what we use to transform (1,0,0,0) into (x,y) and (x,y) into (1,0,0,0).</p><p>Imagine our data has a vector for each user and each dimension corresponds to a movie the user likes or not (1 or 0 for each movie), then the internal representation will “compress” the movies each user likes or dislikes to a feature vector where our first dimension can be, for example, if the movie is action or not. In other words, the autoencoder will learn the features hidden in the preferences the user told us.</p><p>Let’s see a quick example:</p><p>The data is the famous MNIST dataset, each MNIST image is a scan of a handwritten digit in a 28x28 image, so our “inputs” are in 28x28 = 784 dimensions. We train an autoencoder using just 25 hidden neurons:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*ySE6FnBcKUXwRNFrPhkprw.png" /></figure><p>On the left some of our original input points, on the right what the autoencoder can reconstruct from the 25 dimensions in the middle layer. It’s not perfect but it is pretty awesome isn’t it?</p><p>So this shows that we can represent each MNIST digit as a vector in 25 dimensions, and this is where we can see the utility of an autoencoder, it is a feature extraction algorithm it helps us find a representation for our data and we can feed that representation to other algorithms, for example, a classifier.</p><p>In some cases, the features generated by the autoencoder represent the data points better than the points themselves, that’s the key!</p><p>Autoencoders can be stacked and trained in a progressive way, we train an autoencoder and then we take the middle layer generated by the AE and use it as input for another AE and so on. This is the first step towards deep learning, the stacked autoencoders will learn how to represent data, the first level will have a basic representation, the second level will combine that representation to create a higher-level representation and so on. Think about images, a first-level autoencoder will learn to detect borders as features, the second level will combine those borders to learn traces and patterns, etc.</p><p><strong>So to summarize:</strong></p><p>- Autoencoders are neural networks trained to reconstruct their original input.</p><p>- An Autoencoder is a form of feature extraction algorithm.</p><p>- Autoencoders can be stacked.</p><p>- The output of an autoencoder is the middle layer, the representation for each data point.</p><p>- We can use the features generated by an AE in any other algorithm, for example for classification.</p><p>An autoencoder has a lot of freedom and that usually means our AE can overfit the data because it has just too many ways to represent it. To constrain this we should use sparse autoencoders where a non-sparsity penalty is added to the cost function. In general, when we talk about autoencoders we are really talking about sparse autoencoders.</p><p>Autoencoders can be magical but they need to be fed some hyper-parameters and finding the optimal values for those hyper-parameters can be a time-consuming operation.</p><h3><strong>2. Structure of Auto-Encoders.</strong></h3><p>The basic structure of Autoencoders contains three layers. The basic purpose of Autoencoders is that when trained, the output should be exactly the same as the input. So if we feed the network a picture of a cat, it will give the exact same picture back. Autoencoders have an input layer, an output layer and one or more hidden layers connecting them, but with the output layer having the same number of nodes as the input layer, and with the purpose of reconstructing its own inputs instead of predicting the target value Y given inputs X. Therefore, autoencoders are unsupervised learning models. An autoencoder learns to compress data from the input layer into a short code present between the input and output layer, and then uncompress that code into something that closely matches the original data. This forces the autoencoder to engage in dimensionality reduction.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/115/1*z4lvl6wjTP6GhuxN2hzw-g.png" /></figure><p>An autoencoder always consists of two parts, the encoder, and the decoder. The first half that converts the information into the narrow region is called the encoding portion and the second half that converts it back into the original information is called the decoding portion.</p><h3><strong>3. How does Auto-Encoders work?</strong></h3><p>We take the input, encode it to identify latent feature representation. Decode the latent feature representation to recreate the input. We calculate the loss by comparing the input and output. To reduce the reconstruction error we backpropagate and update the weights. Weight is updated based on how much they are responsible for the error.</p><p><strong><em>Let’s break it down step by step.</em></strong></p><p>In our example, we have taken the dataset for products bought by customers</p><p><strong>Step 1: </strong>Take the first row from the customer data for all products bought in an array as the input. 1 represents that the customer bought the product. 0 represents that the customer did not buy the product.</p><p><strong>Step 2: </strong>Encode the input into another vector <em>h. h </em>is a lower dimension vector than the input.<strong> </strong>We can use the sigmoid activation function for <strong>h</strong> as it ranges from 0 to 1. W is the weight applied to the input and b is the bias term.</p><p><strong><em>h=f(Wx+b)</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/644/1*Uni3JbAgug0grLFeUX526g.png" /></figure><p><strong>Step 3: </strong>Decode the vector <em>h</em> to recreate the input. The output will be of the same dimension as the input</p><p><strong>Step 4: </strong>Calculate the reconstruction error L. Reconstruction error is the difference between the input and output vector. Our goal is to minimize the reconstruction error so that output is similar to the input vector</p><p><strong>Reconstruction error= input vector — output vector</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/121/1*_Jk4t5DfOgKrgyFwnMVl2g.png" /></figure><p>Loss function or Reconstruction error</p><p><strong>Step 5: </strong>Back propagate the error from the output layer to the input layer to update the weights. Weights are updated based on how much they were responsible for the error.</p><p>The learning rate decides by how much we update the weights.</p><p><strong>Step 6: </strong>Repeat steps 1 through 5 for each of the observations in the dataset. Weights are updated after each observation(<a href="https://medium.com/datadriveninvestor/gradient-descent-5a13f385d403">Stochastic Gradient descent</a>)</p><p><strong>Step 7: </strong>Repeat more epochs. Epoch is when all the rows in the dataset have passed through the neural network.</p><h4><strong>3.1: Let’s Solve with EXAMPLE</strong></h4><p>As we already know that Images have lots and lots of raw information (pixels) and easily identifiable features that can better represent the image. So let’s solve an example to extract useful features that actually represent the image. In the encoding portion, we need to add a convolutional layer(which we already discuss in chapter 3) to autoencoder and then pull identifiable features pattern from image pixels. However, in the latter part called a decoding portion, we also need a deconvolutional layer and then apply unspooling to reconstruct the image. This process is called upsampling.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/628/1*sC8Wtj2ZyjZMQFueufMk1w.png" /></figure><p>Unfortunately, this is basically impossible as we’ve thrown away the information regarding the original location of each pixel from the other squares in the pooling process. And in the decoding portion if we are unspooling a 1x1 region to a 2x2 region (reversing 2x2 pooling), we first have to move the 1x1 region to the right location in the 2x2 box, simply said we first have to store the pixel back to its original location from where it pulled out during the pulling process. So the problem to remember the original location of each pixel is overcome by using switches, which essentially store the original location from the pooling. Basically, each pooled region takes not only the value but the original location it was in before the pool, which is then used in the unspooling. The remaining pixels are filled with 0s.</p><p><strong>3.1.1 Encoding Portion</strong></p><p>Suppose we have an image’s convolutional layer of 4x4 pixel matrix with some simple sort of patterns highlighted with colors in the image given below. Each box represents a pixel and its value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/143/1*ntRQWysWteZZc0_ZDaDC8A.png" /></figure><p>Now we will apply the pulling process on the convolutional layer to convert the image into a compressed form with useful extracted features. We apply the 2x2 matrix with a stride length of 2 on the convolutional layer to compress the image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/133/1*kV0RU4ncZYXNEIEDKXxRCA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/203/1*G106MK9UJVJrSQxDsM2oNg.png" /></figure><p>We take these important and useful high-level feature values representing a specific pattern available in the convolutional layer of the image and compressed the convolutional layer into a 2x2 matrix during the pulling process from the 4x4 matrix to 2x2 matrix.</p><p>Note: The convolutional step is in detail discuss in<strong><em> </em></strong><a href="https://medium.com/machine-learning-researcher/convlutional-neural-network-cnn-2fc4faa7bb63"><strong><em>chapter 3</em></strong></a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/82/1*K_nQj2U-tVWeEOhdgxOrsg.png" /></figure><p>Our feature map, also called filter or kernel is</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/78/1*HCO-pIBWnxALc7tfcFOhTg.png" /></figure><p><strong>3.1.2 Decoding Portion</strong></p><p>In the decoding portion, we will unspool the 2x2 compressed form matrix extracted from the convolutional layer to reconstruct the image. To do this, take the kernel and multiply every single location with the pixel value of the 2x2 compressed matrix that we are deconvolving. Where there are overlaps, we sum the values.</p><p><strong>Step 1:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/231/1*f_ie20rMelvQjh9CMlukgQ.png" /></figure><p>After multiplication;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/115/1*GaYpnuNjyEKTkT21mBQUaw.png" /></figure><p>We use switches represented by number 0 to remember the original location of each pixel</p><p>Our first unpooled matrix;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/168/1*8NlZC2h2YEeW2gwiwIA0qg.png" /></figure><p><strong>Step 2:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/225/1*h-5wMEIGTObqN0nXhE699g.png" /></figure><p>Our second unpooled matrix</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/171/1*LgWIBKy3JInW5HhwrbxFJA.png" /></figure><p><strong>Step 3:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/242/1*efsgfeK7WcfN62oAIc3CuA.png" /></figure><p>Our third unpooled matrix;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/160/1*7e8PDFwj1FoYmpDOzpAdZA.png" /></figure><p><strong>Step 4:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/217/1*yQgmfjN1LqB6Iug-Z5V_Zw.png" /></figure><p>Our forth unpooled matrix</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/149/1*8klsoYdY04yQ_zdQJo-Jhw.png" /></figure><p>As a result of overlaps, we sum all the unpooled matrix to reconstruct the final image;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/612/1*DGeaPs08DhwTjhhah7ubvg.png" /></figure><p>So our final output matrix is</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/202/1*bsn2t8tTvtpBOTxBS950hw.png" /></figure><p>So our final output matrix is exactly the same as the input matrix</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/532/1*GsK2JR_4Mkp4YyMbyVDPqg.png" /></figure><p>So in this way we Encoding and Decoding.</p><h3><strong>4. Different Types of Auto-Encoders?</strong></h3><p>Here we discuss 5 different types of Auto Encoders.</p><h4>4.1 Sparse Autoencoders</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/427/1*lLRsOzq78DOGAjlkS0UetQ.png" /></figure><p>· Sparse autoencoders have hidden nodes greater than input nodes. They can still discover important features from the data.</p><p>· Sparsity constraint is introduced on the hidden layer. This is to prevent output layer copy input data.</p><p>· Sparse autoencoders have a sparsity penalty, Ω(h), a value close to zero but not zero. The sparsity penalty is applied to the hidden layer in addition to the reconstruction error. This prevents overfitting.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/255/1*WpjQpwkHk6FMw4K4dLso7A.png" /></figure><p>· Sparse autoencoders take the highest activation values in the hidden layer and zero out the rest of the hidden nodes. This prevents autoencoders to use all of the hidden nodes at a time and forcing only a reduced number of hidden nodes to be used.</p><p>· As we activate and inactivate hidden nodes for each row in the dataset. Each hidden node extracts a feature from the data</p><h4><strong>4.2 Denoising Autoencoders</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*R05MPVwHnDEJRm6V_dEYpw.png" /></figure><p>· Denoising refers to intentionally adding noise to the raw input before providing it to the network. Denoising can be achieved using stochastic mapping.</p><p>· Denoising autoencoders create a corrupted copy of the input by introducing some noise. This helps to avoid the autoencoders to copy the input to the output without learning features about the data.</p><p>· Corruption of the input can be done randomly by making some of the input as zero. Remaining nodes copy the input to the noised input.</p><p>· Denoising autoencoders must remove the corruption to generate an output that is similar to the input. The output is compared with input and not with noised input. To minimize the loss function we continue until convergence</p><p>· Denoising autoencoders minimize the loss function between the output node and the corrupted input.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/202/1*cbg8vsLYGfBbhTc6yGv4UQ.png" /></figure><p>· Denoising helps the autoencoders to learn the latent representation present in the data. Denoising autoencoders ensure a good representation is one that can be derived robustly from a corrupted input and that will be useful for recovering the corresponding clean input.</p><p>· Denoising is a stochastic autoencoder as we use a stochastic corruption process to set some of the inputs to zero</p><h4><strong>4.3 Contractive Auto Encoders</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/409/1*Lhdfshqc6HxfFGuIhQyaAw.png" /></figure><p>· The contractive autoencoder(CAE) objective is to have a robust learned representation that is less sensitive to the small variation in the data.</p><p>· Robustness of the representation for the data is done by applying a penalty term to the loss function. The penalty term is the <strong>Frobenius norm of the Jacobian</strong> <strong>matrix. </strong>Frobenius norm of the<strong> </strong>Jacobian matrix for<strong> </strong>the hidden layer is calculated with respect to the input. Frobenius norm of the Jacobian matrix is the sum of the square of all elements.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/240/1*lAl_hrpIP3Tz_w-O1kJ44w.png" /></figure><p>Loss function with penalty term — Frobenius norm of the Jacobian matrix</p><p>· A contractive autoencoder is another regularization technique like sparse autoencoders and denoising autoencoders.</p><p>· CAE surpasses results obtained by regularizing autoencoder using weight decay or by denoising. CAE is a better choice than denoising autoencoders to learn useful feature extraction.</p><p>· Penalty term generates mapping which is strongly contracting the data and hence the name contractive autoencoder.</p><h4><strong>4.4 Stacked Auto Encoders</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*-kjH9_RsvMtprV_GmHUoMA.png" /></figure><p>· Stacked Autoencoders is a neural network with multiple layers of sparse autoencoders</p><p>· When we add more hidden layers than just one hidden layer to an autoencoder, it helps to reduce high dimensional data to a smaller code representing important features</p><p>· Each hidden layer is a more compact representation than the last hidden layer</p><p>· We can also denoise the input and then pass the data through the stacked autoencoders called as <strong>stacked denoising autoencoders</strong></p><p>· In Stacked Denoising Autoencoders, input corruption is used only for initial denoising. This helps learn important features present in the data. Once the mapping function f(θ) has been learned. For further layers, we use uncorrupted input from the previous layers.</p><p>· After training a stack of encoders as explained above, we can use the output of the stacked denoising autoencoders as an input to a stand-alone supervised machine learning like support vector machines or multi-class logistics regression.</p><h4><strong>4.5 Deep Auto Encoders</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/454/1*UpWsxOB-3D1nMYgYUEz2NQ.png" /></figure><p>· Deep Autoencoders consists of two identical deep belief networks. One network for encoding and another for decoding</p><p>· Typically deep autoencoders have 4 to 5 layers for encoding and the next 4 to 5 layers for decoding. We use unsupervised layer by layer pre-training</p><p>· Restricted Boltzmann Machine(RBM) is the basic building block of the deep belief network. We will do RBM is a different post.</p><p>· In the above figure, we take an image with 784 pixels. Train using a stack of 4 RBMs, unroll them and then finetune with backpropagation</p><p>· The final encoding layer is compact and fast.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*jYNwmWO1ABx9izX-ZxuyWQ.png" /></figure><p><strong>Note</strong>: If you want this article check out my <a href="https://www.academia.edu/41218152/A_Deep_Level_Understanding_of_Auto_Encoders_with_Practical_Implementation_in_Pytorch"><strong>academia.edu</strong></a> profile.</p><h3><strong>5. Practical Implementation of Auto-Encoders.</strong></h3><h4><strong>Recommender System</strong></h4><p>From Amazon product suggestions to Netflix movie recommendations — good recommender systems are very valuable in today’s World. And specialists who can create them are some of the top-paid Data Scientists on the planet.</p><p>We will work on a dataset that has exactly the same features as the Netflix dataset: plenty of movies, thousands of users, who have rated the movies they watched. The ratings go from 1 to 5, exactly like in the Netflix dataset, which makes the Recommender System more complex to build than if the ratings were simply “Liked” or “Not Liked”.</p><p>Your final Recommender System will be able to predict the ratings of the movies the customers didn’t watch. Accordingly, by ranking the predictions from 5 down to 1, your Deep Learning model will be able to recommend which movies each user should watch.</p><p>Our model will be a powerful Auto Encoder ( previous chapter we apply the RBM model). And you will even be able to apply it to yourself or your friends. The list of movies will be explicit so you will simply need to rate the movies you already watched, input your ratings in the dataset, execute your model and voila! The Recommender System will tell you exactly which movies you would love one night you if are out of ideas of what to watch on Netflix!</p><p>Let’s solve the problem</p><p><strong>Part 1: Data Preprocessing</strong></p><p>In this part, we are doing Data Preprocessing.</p><p><strong><em>1.1 Import the Libraries</em></strong></p><p>In this step, we import three Libraries in Data Preprocessing part. Basically, Library is a tool that you can use to make a specific job. First of all, we import the <strong>numpy</strong> library used for a multidimensional array then import the <strong>pandas </strong>library<strong> </strong>used to import the dataset. Then import <strong>torch</strong> the Pytorch library and import several packages of that. <strong>torch.nn as nn</strong><em> </em>for initializing the neural network. <strong>torch.nn.parallel</strong><em> </em>for parallel computations. <strong>torch.optim as optim</strong><em> </em>for the optimizer. <strong>torch.utils.data</strong><em> </em>for data loading and processing<strong><em>.</em> autograd</strong><em> </em>for implementing automatic differentiation</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/435/1*VjZU8H0JHlW1wYRW1BDWpw.png" /></figure><p><strong><em>1.2 Import the dataset</em></strong></p><p>In the next step, we import the <strong>users</strong>, <strong>ratings</strong>, and <strong>movie</strong> dataset. In our case, our dataset is separated by <strong>double colons</strong>. The dataset does not have any <strong>headers</strong> so we shall pass the headers as none. We then set the <strong>engine</strong> to Python to ensure the dataset is correctly imported.</p><p>We then use the <strong>Latin-1</strong> encoding type since some of the movies have special characters in their titles. The first column of the rating dataset is the user ID, the second column is the movie ID, the third column is the rating and the fourth column is the timestamp.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/484/1*DSC32OHl-jpESVAy2exwXQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*avlhhCyDSVwSuUMJzxE4iQ.png" /></figure><p><strong><em>1.3 Preparing the training set and test set</em></strong></p><p>Let’s now prepare our training set and test set. Our test and training sets are tab-separated; therefore we’ll pass in the <strong>delimiter</strong> argument as \t. As we know very well, <strong>pandas</strong> import the data as a data frame. However, we need to convert it to an array so we can use it in PyTorch tensors. We do that using the <strong>np.array</strong> command from Numpy. We also specify that our array should be integers since we’re dealing with integer data types.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*OnDn2dKw_Gm_rySHt6mFkA.png" /></figure><p><strong><em>1.4 Getting the Number of Users and Movies</em></strong></p><p>In order to build the RBM, we need a matrix with the users’ ratings. This matrix will have the users as the rows and the movies as the columns. The matrix will contain a user’s rating of a specific movie. Zeros will represent observations where a user didn’t rate a specific movie.</p><p>In order to create this matrix, we need to obtain the number of movies and the number of users in our dataset. For no_users we pass in zero since it’s the index of the user ID column. The way we obtain the number of users is by getting the max in the training and test set, and then using the max utility to get the maximum of the two. We then force the obtained number to be an integer by wrapping the entire function inside an int.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*nulwMPTahWWHXLr0WLRgqA.png" /></figure><p><strong><em>1.5 Converting the data into an array with users in lines and movies in columns</em></strong></p><p>Next, we create a function that will create the matrix. The reason for doing this is to set up the dataset in a way that the RBM expects as input. We create a function called convert, which takes in our data as input and converts it into the matrix.</p><p>First, we create an empty list called <strong>new_data</strong><em>. </em>We then create a <strong>for</strong> loop that will go through the dataset, fetch all the movies rated by a specific user, and the ratings by that same user. Notice that we loop up to <strong>no_users + 1</strong> to include the last user ID since the range function doesn’t include the upper bound.</p><p>Since there are movies that the user didn’t rate, we first create a matrix of zeros. We then update the zeros with the user’s ratings. When appending the movie ratings, we use <strong>id_movies — 1</strong><em> </em>because indices in Python start from zero. We, therefore, subtract one to ensure that the first index in Python is included. We append the ratings to <strong>new_data</strong> as a list. This will create a list of lists. Now let’s use our function and convert our training and test data into a matrix.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*pl68MFQzlRPZo_wV7pRb8A.png" /></figure><p><strong><em>1.6 Converting the data into Torch tensors</em></strong></p><p>Since we’re using PyTorch, we need to convert the data into Torch tensors. The way we do this is by using the <strong>FloatTensor</strong><em> </em>utility. This will convert the dataset into PyTorch arrays.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/537/1*WH9pw7rE27IRTOmCs9-QWQ.png" /></figure><p><strong>Part 2: Building our Model</strong></p><p>In this Second Part, we will Build our model which is Auto Encoder.</p><p><strong><em>2.1 Creating the Autoencoder Architecture</em></strong></p><p>Now we need to create a class to define the architecture of the Auto Encoder. Inside the Class, we define two functions in the first function we create the basic architecture of autoencoder fc1 and fc2 basically we encoding and fc3 and fc4 we decoding the values. In the second function, we apply the activation function in our first three layers as you can see below code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*CIe2C_0EO9PEvNoGp11KFA.png" /></figure><p><strong>Part 3: Training the Autoencoder Model</strong></p><p>The first step in training the AE is to define the number of epochs. We then define a loop where all the training set will go through. After each epoch, the weight will be adjusted in order to improve the predictions. Finally, we obtain the visible nodes with the ratings of the movies that were not rated by the users.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*J4xPouIiOxpXyaq1PyekmA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/453/1*K6zEF2PdkJPb1GYKgVsxHA.png" /></figure><p><strong>Part 4: Testing the AE Model</strong></p><p>Next, we test our Model. In this stage, we use the training set data to activate the hidden neurons in order to obtain the output. This is how we get the predicted output of the test set. We then use the absolute mean to compute the test loss.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*02hGsYig9sIiClR9ZhGqcA.png" /></figure><p>If you want dataset and code you also check my <a href="https://github.com/AmirAli5/Deep-Learning"><strong>Github</strong></a> Profile.</p><h3>End Notes</h3><p>If you liked this article, be sure to click ❤ below to recommend it and if you have any questions, <strong>leave a comment</strong> and I will do my best to answer.</p><p>For being more aware of the world of machine learning, <a href="https://amiraliryk1.wixsite.com/portfolio"><strong>follow me</strong></a>. It’s the best way to find out when I write more articles like this.</p><p>You can also follow me on <a href="https://github.com/AmirAli5"><strong>Github</strong></a> for code &amp; dataset follow on <a href="https://uet.academia.edu/AliAmir"><strong>Aacademia.edu</strong></a> for this article, <a href="https://twitter.com/amir_ali_cheema"><strong>Twitter</strong></a><strong> </strong>and<strong> </strong><a href="http://amirali.cheema@outlook.com/"><strong>Email </strong></a>me directly or find me on<strong> </strong><a href="https://www.linkedin.com/in/amiralicheema/"><strong>LinkedIn</strong>.</a> I’d love to hear from you.</p><p>That’s all folks, Have a nice day :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d942a29c9807" width="1" height="1" alt=""><hr><p><a href="https://medium.com/machine-learning-researcher/auto-encoder-d942a29c9807">Auto Encoder</a> was originally published in <a href="https://medium.com/machine-learning-researcher">Aorb Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Boltzmann Machine]]></title>
            <link>https://medium.com/machine-learning-researcher/boltzmann-machine-c2ce76d94da5?source=rss----32a2162bf0c7---4</link>
            <guid isPermaLink="false">https://medium.com/p/c2ce76d94da5</guid>
            <category><![CDATA[rbm]]></category>
            <category><![CDATA[contrastive-divergence]]></category>
            <category><![CDATA[boltzmann-machines]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[recommender-systems]]></category>
            <dc:creator><![CDATA[Amir Ali]]></dc:creator>
            <pubDate>Sun, 26 May 2019 12:55:51 GMT</pubDate>
            <atom:updated>2019-12-08T03:18:12.731Z</atom:updated>
            <content:encoded><![CDATA[<h3>Restricted Boltzmann Machine (RBM) with Practical Implementation</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*8nvvjC77blk5PykrrCugbA.png" /></figure><p>In this Chapter of Deep Learning book, we will discuss the Boltzmann Machine. It is an Unsupervised Deep Learning technique and we will discuss both theoretical and Practical Implementation from Scratch.</p><p><strong>This chapter spans 6 parts:</strong></p><ol><li>What is the Boltzmann Machine?</li><li>An Energy-Based Model.</li><li>Restricted Boltzmann Machine.</li><li>How do Restricted Boltzmann Machine Work?</li><li>Contrastive Divergence.</li><li>Practical Implementation of Restricted Boltzmann Machine.</li></ol><h3>1. What is the Boltzmann Machine?</h3><p><em>Boltzmann </em>Machine was first invented in 1985 by Geoffrey Hinton, a professor at the University of Toronto. He is a leading figure in the deep learning community and is referred to by some as the “<a href="https://en.wikipedia.org/wiki/Geoffrey_Hinton">Godfather of Deep Learning</a>”.</p><p>· <em>Boltzmann </em>Machine<em> is a </em>generative unsupervised model, which involves learning a probability distribution from an original dataset and using it to make inferences about never before seen data.</p><p>· <em>Boltzmann </em>Machine has an input layer (also referred to as the <em>visible layer</em>) and one or several hidden layers (also referred to as the <em>hidden layer</em>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/644/1*YTZo3rydalAJmXuDY4B4ug.png" /></figure><p>· Boltzmann Machine uses neural networks with neurons that are connected not only to other neurons in other layers but also to neurons within the same layer.</p><p>· Everything is connected to everything. Connections are bidirectional, <em>visible </em>neurons connected to each other and <em>hidden </em>neurons also connected to each other</p><p>· <em>Boltzmann Machine doesn’t expect input data, it generates data. </em>Neurons <em>generate information regardless they are hidden or visible.</em></p><p>· <em>For Boltzmann Machine all n</em>eurons are the same, it doesn’t discriminate between <em>hidden </em>and <em>visible n</em>eurons. <em>For Boltzmann Machine whole things are system and its generating </em>state <em>of the system.</em></p><p>The best way to think about it is through an example nuclear power plant.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/644/1*i-DPtO4G3h2oG00EcIGbsw.png" /></figure><p>· Suppose for example we have a nuclear power station and there are certain things we can measure in a nuclear power plant like the temperature of the containment building, how quickly the turbine is spinning, the pressure inside the pump, etc.</p><p>· There are lots of things we are not measuring like the speed of the wind, the moisture of the soil in this specific location, its sunny day or rainy day, etc.</p><p>· All these parameters together form a system, they all work together. All these parameters are binary. So we get a whole bunch of binary numbers that tell us something about the state of the power station.</p><p>· What we would like to do, is we want to notice that when it is going to in an unusual state. A state that is not like a normal state which we had seen before. And we don’t want to use supervised learning for that. Because we don’t want to have any examples of states that cause it to blow up.</p><p>· We would rather be able to detect that when it is going into such a state without even having seen such a state before. And we could do that by building a model of a normal state and noticing that this state is different from the normal states.</p><p>· That what <em>Boltzmann Machine represents.</em></p><p>· The way this system work, we use our training data and feed into the <em>Boltzmann Machine as input to help the system adjust its weights. It resembles our system not any </em>nuclear power station in the world.</p><p>· It learns from the input, what are the possible connections between all these parameters, how do they influence each other and therefore it becomes a machine that represents our system.</p><p>· We can use this <em>Boltzmann Machine to monitor our system</em></p><p>· <em>Boltzmann Machine learns how the system works in its normal states through a good example.</em></p><p>Boltzmann Machine consists of a neural network with an input layer and one or several hidden layers. The neurons in the neural network make stochastic decisions about whether to turn on or off based on the data we feed during training and the cost function the Boltzmann Machine is trying to minimize.</p><p>By doing so, the Boltzmann Machine discovers interesting features about the data, which help model the complex underlying relationships and patterns present in the data.</p><p>This Boltzmann Machine uses neural networks with neurons that are connected not only to other neurons in other layers but also to neurons within the same layer. That makes training an unrestricted Boltzmann machine very inefficient and Boltzmann Machine had very little commercial success.</p><p>Boltzmann Machines are primarily divided into two categories: <strong>Energy-based Models (EBMs) </strong>and <strong>Restricted Boltzmann Machines (RBM)</strong>. When these RBMs are stacked on top of each other, they are known as <strong>Deep Belief Networks (DBN)</strong>.</p><h3>2. An Energy-Based Model.</h3><p>Energy is a term that may not be associated with deep learning in the first place. Rather is energy a quantitative property of physics. E.g. gravitational energy describes the potential energy a body with mass has in relation to another massive objected due to gravity. Yet some deep learning architectures use the idea of energy as a metric for the measurement of the model’s quality.</p><p>One purpose of deep learning models is to encode dependencies between variables. The capturing of dependencies happens through associating of scalar energy to each configuration of the variables, which serves as a measure of compatibility. High energy means bad compatibility. An energy-based model tries always to minimize a predefined energy function. The energy function for the RBMs is defined as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/521/1*R6t2wkgLbr48UM5tS0oBVg.png" /></figure><p>As can be noticed the value of the energy function depends on the configurations of visible/input states, hidden states, weights, and biases. The training of RBM consists of the finding of parameters for given input values so that the energy reaches a minimum.</p><h3>3. Restricted Boltzmann Machine.</h3><p>What makes RBMs different from Boltzmann machines is that visible node isn’t connected to each other, and hidden nodes aren’t connected with each other. Other than that, RBMs are exactly the same as Boltzmann machines.</p><p>As you can see below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/324/1*qP7zFsyjb1sCVpV6IBIqOw.png" /></figure><p>· RBM is the neural network that belongs to the energy-based model</p><p>· It is a probabilistic, unsupervised, generative deep machine learning algorithm.</p><p>· RBM’s objective is to find the joint probability distribution that maximizes the log-likelihood function.</p><p>· RBM is undirected and has only two layers, Input layer, and hidden layer</p><p>· All visible nodes are connected to all the hidden nodes. RBM has two layers, visible layer or input layer and hidden layer so it is also called an a<strong>symmetrical bipartite graph.</strong></p><p>· No intralayer connection exists between the visible nodes. There is also no intralayer connection between the hidden nodes. There are connections only between input and hidden nodes.</p><p>· The original Boltzmann machine had connections between all the nodes. Since RBM restricts the intralayer connection, it is called a Restricted Boltzmann Machine.</p><p>Since RBMs are undirected, they don’t adjust their weights through gradient descent and backpropagation. They adjust their weights through a process called <a href="http://deeplearning.net/tutorial/rbm.html">contrastive divergence</a>. At the start of this process, weights for the visible nodes are randomly generated and used to generate the hidden nodes. These hidden nodes then use the same weights to reconstruct visible nodes. The weights used to reconstruct the visible nodes are the same throughout. However, the generated nodes are not the same because they aren’t connected to each other.</p><h3>4. How do Restricted Boltzmann Machine Work?</h3><p>In an RBM, we have a symmetric bipartite graph where no two units within the same group are connected. Multiple RBMs can also be stacked and can be fine-tuned through the process of gradient descent and back-propagation. Such a network is called a Deep Belief Network. Although RBMs are occasionally used, most people in the deep-learning community have started replacing their use with General Adversarial Networks or Variational Autoencoders.</p><p>RBM is a Stochastic Neural Network which means that each neuron will have some random behavior when activated. There are two other layers of bias units (hidden bias and visible bias) in an RBM. This is what makes RBMs different from autoencoders. The hidden bias RBM produces the activation on the forward pass and the visible bias helps RBM to reconstruct the input during a backward pass. The reconstructed input is always different from the actual input as there are no connections among the visible units and therefore, no way of transferring information among themselves.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/404/1*4JX1ItFmjbNcAlOcokxZJg.png" /></figure><p>The above image shows the first step in training an RBM with multiple inputs. The inputs are multiplied by the weights and then added to the bias. The result is then passed through a sigmoid activation function and the output determines if the hidden state gets activated or not. Weights will be a matrix with the number of input nodes as the number of rows and the number of hidden nodes as the number of columns. The first hidden node will receive the vector multiplication of the inputs multiplied by the first column of weights before the corresponding bias term is added to it.</p><p>And if you are wondering what a sigmoid function is, here is the formula:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/292/1*Z7P-A1phgpbNjjuRHWMqKQ.png" /></figure><p>So the equation that we get in this step would be,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/231/1*IrgrD1wNDpf5_EC-CG9jEg.png" /></figure><p>where <strong>h(1)</strong> and <strong>v(0)</strong> are the corresponding vectors (column matrices) for the hidden and the visible layers with the superscript as the iteration v(0) means the input that we provide to the network) and <strong>a</strong> is the hidden layer bias vector.</p><p>(Note that we are dealing with vectors and matrices here and not one-dimensional values.)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/504/1*qWa1NOZq1JArIlZgdJ4RkQ.png" /></figure><p>Now this image shows the reverse phase or the <strong>reconstruction</strong> phase. It is similar to the first pass but in the opposite direction. The equation comes out to be:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/238/1*zXHLyL3RJNEPrX4ES7o5iA.png" /></figure><p>where <strong>v(1)</strong> and <strong>h(1)</strong> are the corresponding vectors (column matrices) for the visible and the hidden layers with the superscript as the iteration and <strong>b</strong> is the visible layer bias vector.</p><h4>4.1. The learning process</h4><p>Now, the difference <strong>v(0)−v(1)</strong> can be considered as the reconstruction error that we need to reduce in subsequent steps of the training process. So the weights are adjusted in each iteration so as to minimize this error and this is what the learning process essentially is. Now, let us try to understand this process in mathematical terms without going too deep into mathematics. In the forward pass, we are calculating the probability of output <strong>h(1)</strong> given the input <strong>v(0)</strong> and the weights <strong>W</strong> denoted by:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/189/1*Haci88r9yF8w8qt7GSDWzw.png" /></figure><p>And in the backward pass, while reconstructing the input, we are calculating the probability of output <strong>v(1)</strong> given the input <strong>h(1)</strong> and the weights <strong>W</strong> denoted by:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/186/1*r2Q79JsZd7zvi8NWjyApnQ.png" /></figure><p>The weights used in both the forward and the backward pass are the same. Together, these two conditional probabilities lead us to the joint distribution of inputs and the activations:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/104/1*_-p4niZRrhbq1cYOk0BzUQ.png" /></figure><p>Reconstruction is different from regression or classification in that it estimates the probability distribution of the original input instead of associating a continuous/discrete value to an input example. This means it is trying to guess multiple values at the same time. This is known as generative learning as opposed to discriminative learning that happens in a classification problem (mapping input to labels).</p><p>Let us try to see how the algorithm reduces loss or simply put, how it reduces the error at each step. Assume that we have two normal distributions, one from the input data (<strong>denoted by p(x)</strong>) and one from the reconstructed input approximation (<strong>denoted by q(x)</strong>). The difference between these two distributions is our error in the graphical sense and our goal is to minimize it, i.e., bring the graphs as close as possible. This idea is represented by a term called the <a href="https://en.wikipedia.org/wiki/Kullback%E2%80%93Leibler_divergence">Kullback–Leibler divergence</a>.</p><p>KL-divergence measures the non-overlapping areas under the two graphs and the RBM’s optimization algorithm tries to minimize this difference by changing the weights so that the reconstruction closely resembles the input. The graphs on the right-hand side show the integration of the difference in the areas of the curves on the left.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/616/1*u8iwkCv4Imu98GdsyaXbUw.png" /></figure><p>This gives us intuition about our error term. Now, to see how actually this is done for RBMs, we will have to dive into how the loss is being computed. All common training algorithms for RBMs approximate the log-likelihood gradient given some data and perform gradient ascent on these approximations.</p><h3>5: Contrastive Divergence.</h3><p>Boltzmann Machines (and RBMs) are Energy-based models and a joint configuration, <strong>(v,h)</strong> of the visible and hidden units has energy given by:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/505/1*MKdGhd-LI3zya4ZE0DqgbA.png" /></figure><p>Where <strong>vi, hj</strong> are the binary states of visible unit ii and hidden <strong>unit j, ai, bj</strong> are their biases and <strong>wij</strong> is the weight between them.</p><p>The probability that the network assigns to a visible vector,<strong> v</strong>, is given by summing over all possible hidden vectors:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/248/1*j8EbT9y6ZIfHiU00acZSXg.png" /></figure><p><strong>Z</strong> here is the partition function and is given by summing over all possible pairs of visible and hidden vectors:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/205/1*gRh4wadtlgD704xhVAKmvQ.png" /></figure><p>This gives us:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/239/1*gA7AOS00eVINAXOlOBHP0w.png" /></figure><p>The log-likelihood gradient or the derivative of the log probability of a training vector with respect to weight is surprisingly simple:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/380/1*x3cxN6uOwyjzeVAOP15taA.png" /></figure><p>Where the angle brackets are used to denote expectations under the distribution specified by the subscript that follows. This leads to a very simple learning rule for performing stochastic steepest ascent in the log probability of the training data:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/348/1*YAo3a1QN3xrsjzy3xhOEow.png" /></figure><p>where <strong>α</strong> is a learning rate. For more information on what the above equations mean or how they are derived, refer to the <a href="https://www.csrc.ac.cn/upload/file/20170703/1499052743888438.pdf">Guide on training RBM by Geoffrey Hinton</a>. The important thing to note here is that because there are no direct connections between hidden units in an RBM, it is very easy to get an unbiased sample of <strong>⟨vihj⟩data</strong>. Getting an unbiased sample of <strong>⟨vihj⟩model</strong>.</p><p>However, is much more difficult. This is because it would require us to run a Markov chain until the stationary distribution is reached (which means the energy of the distribution is minimized — equilibrium!) to approximate the second term.</p><p>So instead of doing that, we perform <a href="https://en.wikipedia.org/wiki/Gibbs_sampling">Gibbs Sampling</a> from the distribution. It is a Markov Chain Monte Carlo (<strong>MC</strong>) algorithm for obtaining a sequence of observations which are approximated from a specified multivariate probability distribution when direct sampling is difficult (like in our case). The Gibbs chain is initialized with a training example <strong>v(0)</strong> of the training set and yields the sample <strong>v(k)</strong> after <strong>k</strong> steps.</p><p>Each step <strong>t </strong>consists of sampling <strong>h(t)</strong> from <strong>p(h∣v(t))</strong> and sampling <strong>v(t+1)</strong> from <strong>p(v∣h(t))</strong> <strong>subsequently</strong> (the value <strong>k=1</strong> surprisingly works quite well).</p><p>The learning rule now becomes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*fBnCdLH8P4Gwc3Z7NY-37g.png" /></figure><p>The learning works well even though it is only crudely approximating the gradient of the log probability of the training data. The learning rule is much more closely approximating the gradient of another objective function called the <strong>Contrastive Divergence</strong> which is the difference between two Kullback-Liebler divergences.</p><p>When we apply this, we get:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*a6yKbuSbIuzzFAG5_GedYg.png" /></figure><p>Where the second term is obtained after each <strong>k</strong> steps of Gibbs Sampling.</p><p>Here is the pseudo-code for the <strong>CD</strong> algorithm:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/634/1*EXJyM4a4Xo_5_Oo6k8I0GQ.png" /></figure><h4>Example: Recommender System of Movies</h4><p>Let us assume that some people were asked to rate a set of movies on a scale of 1–5 and each movie could be explained in terms of a set of latent factors such as drama, fantasy, action and many more. Restricted Boltzmann Machines are used to analyze and find out these underlying factors.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/532/1*v87Gy7M9tCY5Qc1rGUe6BQ.png" /></figure><p>The analysis of hidden factors is performed in a binary way, i.e, the user only tells if they liked (rating 1) a specific movie or not (rating 0) and it represents the inputs for the input/visible layer. Given the inputs, the RMB then tries to discover latent factors in the data that can explain the movie choices and each hidden neuron represents one of the latent factors.</p><p>Let us consider the following example where a user likes <em>Lord of the Rings and</em> <em>Harry Potter </em>but does not like <em>The Matrix</em>,<em> Fight Club</em> and <em>Titanic</em>. The Hobbit has not been seen yet so it gets a -1 rating. Given these inputs, the Boltzmann Machine may identify three hidden factors <em>Drama</em>, <em>Fantasy </em>and <em>Science Fiction </em>which correspond to the movie genres.</p><p><strong>Using Latent Factors for Prediction</strong></p><p>After the training phase, the goal is to predict a binary rating for the movies that had not been seen yet. Given the training data of a specific user, the network is able to identify the latent factors based on the user’s preference and sample from Bernoulli distribution can be used to find out which of the visible neurons now become active.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/532/1*KXwSv0ElHYofPrNRb7-2Kg.png" /></figure><p>The image shows the new ratings after using the hidden neuron values for the inference. The network identified <em>Fantasy </em>as the preferred movie genre and rated <em>The Hobbit </em>as a movie the user would like.</p><p>The process from <strong>training</strong> to the <strong>prediction</strong> phase goes as follows:</p><ul><li>Train the network on the data of all users</li><li>During inference-time, take the training data of a specific user</li><li>Use this data to obtain the activations of hidden neurons</li><li>Use the hidden neuron values to get the activations of input neurons</li><li>The new values of input neurons show the rating the user would give yet unseen movies</li></ul><p><strong>Note: </strong>If you want this article check out my<strong> </strong><a href="https://www.academia.edu/41217939/A_Briefly_Explanation_of_Restricted_Boltzmann_Machine_with_Practical_Implementation_in_Pytorch"><strong>academia.edu</strong></a><strong> </strong>profile.</p><h3>6.Practical Implementation of Restricted Boltzmann Machine.</h3><h4>Recommender System</h4><p>From Amazon product suggestions to Netflix movie recommendations — good recommender systems are very valuable in today’s World. And specialists who can create them are some of the top-paid Data Scientists on the planet.</p><p>We will work on a dataset that has exactly the same features as the Netflix dataset: plenty of movies, thousands of users, who have rated the movies they watched. The ratings go from 1 to 5, exactly like in the Netflix dataset, which makes the Recommender System more complex to build than if the ratings were simply “Liked” or “Not Liked”.</p><p>Your final Recommender System will be able to predict the ratings of the movies the customers didn’t watch. Accordingly, by ranking the predictions from 5 down to 1, your Deep Learning model will be able to recommend which movies each user should watch.</p><p>Our model will be Deep Belief Networks, complex Boltzmann Machines. And you will even be able to apply it to yourself or your friends. The list of movies will be explicit so you will simply need to rate the movies you already watched, input your ratings in the dataset, execute your model and voila! The Recommender System will tell you exactly which movies you would love one night you if are out of ideas of what to watch on Netflix!</p><p>Let’s solve the problem</p><p><strong>Part 1: Data Preprocessing</strong></p><p>In this part, we are doing Data Preprocessing.</p><p><strong><em>1.1 Import the Libraries</em></strong></p><p>In this step, we import three Libraries in Data Preprocessing part. Basically, Library is a tool that you can use to make a specific job. First of all, we import the <strong>numpy</strong> library used for a multidimensional array then import the <strong>pandas </strong>library<strong> </strong>used to import the dataset. Then import <strong>torch</strong> the Pytorch library and import several packages of that. <strong>torch.nn as nn</strong><em> </em>for initializing the neural network. <strong>torch.nn.parallel</strong><em> </em>for parallel computations. <strong>torch.optim as optim</strong><em> </em>for the optimizer. <strong>torch.utils.data</strong><em> </em>for data loading and processing<strong><em>.</em> autograd</strong><em> </em>for implementing automatic differentiation</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/435/1*WTlQsd4HcDA6gP9bcj9DLA.png" /></figure><p><strong><em>1.2 Import the dataset</em></strong></p><p>In the next step, we import the <strong>users</strong>, <strong>ratings</strong>, and <strong>movie</strong> dataset. In our case, our dataset is separated by <strong>double colons</strong>. The dataset does not have any <strong>headers</strong> so we shall pass the headers as none. We then set the <strong>engine</strong> to Python to ensure the dataset is correctly imported.</p><p>We then use the <strong>Latin-1</strong> encoding type since some of the movies have special characters in their titles. The first column of the rating dataset is the user ID, the second column is the movie ID, the third column is the rating and the fourth column is the timestamp.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/484/1*DSC32OHl-jpESVAy2exwXQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*avlhhCyDSVwSuUMJzxE4iQ.png" /></figure><p><strong><em>1.3 Preparing the training set and test set</em></strong></p><p>Let’s now prepare our training set and test set. Our test and training sets are tab-separated; therefore we’ll pass in the <strong>delimiter</strong> argument as \t. As we know very well, <strong>pandas</strong> import the data as a data frame. However, we need to convert it to an array so we can use it in PyTorch tensors. We do that using the <strong>np.array</strong> command from Numpy. We also specify that our array should be integers since we’re dealing with integer data types.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*OnDn2dKw_Gm_rySHt6mFkA.png" /></figure><p><strong><em>1.4 Getting the Number of Users and Movies</em></strong></p><p>In order to build the RBM, we need a matrix with the users’ ratings. This matrix will have the users as the rows and the movies as the columns. The matrix will contain a user’s rating of a specific movie. Zeros will represent observations where a user didn’t rate a specific movie.</p><p>In order to create this matrix, we need to obtain the number of movies and the number of users in our dataset. For no_users we pass in zero since it’s the index of the user ID column. The way we obtain the number of users is by getting the max in the training and test set, and then using the max utility to get the maximum of the two. We then force the obtained number to be an integer by wrapping the entire function inside an int.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*nulwMPTahWWHXLr0WLRgqA.png" /></figure><p><strong><em>1.5 Converting the data into an array with users in lines and movies in columns</em></strong></p><p>Next, we create a function that will create the matrix. The reason for doing this is to set up the dataset in a way that the RBM expects as input. We create a function called, which takes in our data as input and converts it into the matrix.</p><p>First, we create an empty list called <strong>new_data</strong><em>. </em>We then create a loop that will go through the dataset, fetch all the movies rated by a specific user, and the ratings by that same user. Notice that we loop up to <strong>no_users + 1</strong> include the last user ID since the range function doesn’t include the upper bound.</p><p>Since there are movies that the user didn’t rate, we first create a matrix of zeros. We then update the zeros with the user’s ratings. When appending the movie ratings, we use <strong>id_movies — 1</strong><em> it </em>because indices in Python start from zero. We, therefore, subtract one to ensure that the first index in Python is included. We append the ratings <strong>new_data</strong> as a list. This will create a list of lists. Now let’s use our function and convert our training and test data into a matrix.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*pl68MFQzlRPZo_wV7pRb8A.png" /></figure><p><strong><em>1.6 Converting the data into Torch tensors</em></strong></p><p>Since we’re using PyTorch, we need to convert the data into Torch tensors. The way we do this is by using the <strong>FloatTensor</strong><em> </em>utility. This will convert the dataset into PyTorch arrays.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/537/1*WH9pw7rE27IRTOmCs9-QWQ.png" /></figure><p><strong><em>1.7 Converting the Rating into Binary rating 1 (Liked) or 0 (Not Liked)</em></strong></p><p>Next, we convert these ratings into binary ratings since we want to make a binary classification. We, therefore, convert the ratings to zeros and ones. Remember that we already have zero ratings in the dataset representing where a user didn’t rate the movie. We replace that with <strong>-1</strong> to represent movies that a user never rated. We then convert the ratings that were rated 1 and 2 to <strong>0</strong> and movies that were rated 3, 4 and, 5 to <strong>1</strong>. We do this for both the test set and the training set.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*049FW2p5H9Q5S4oJwZddeQ.png" /></figure><p><strong>Part 2: Building our Model</strong></p><p>In this Second Part, we will Build our Restricted Boltzmann Machine (RBM).</p><p><strong><em>2.1 Creating the RBM Architecture</em></strong></p><p>Now we need to create a class to define the architecture of the RBM. Inside the <strong>init</strong> the function we specify two parameters; the first variable is the number of visible nodes <strong>nv</strong>, and the second parameter is the number of hidden nodes <strong>nh</strong>.</p><p>Next, we initialize the weight and bias. We do this randomly using a normal distribution and using <strong>randn</strong> from the <strong>torch</strong>. The weight is of size <strong>nh</strong> and <strong>nv</strong>. We then define two types of biases. <strong>a</strong> is the probability of the hidden nodes given the visible nodes, and b is the probability of the visible nodes given the hidden nodes. In declaring them we input 1 as the first parameter, which represents the batch size.</p><p>The next step is to create a function <strong>sample_h</strong><em> </em>which will sample the hidden nodes. It takes x as an argument, which represents the visible neurons.</p><p>Next, we compute the probability of <strong>h</strong> given <strong>v</strong> where h and v represent the hidden and visible nodes respectively. This represents the sigmoid activation function and is computed as the product of the vector of the weights and <strong>x</strong> plus the bias <strong>a</strong>. The product is done using the <strong>mm</strong> utility from Torch. Since we’re doing binary classification, we also return <strong>Bernoulli</strong> samples of the hidden neurons.</p><p>Next, we create a function <strong>sample_v</strong> that will sample the visible nodes. The function is similar to the <strong>sample_h</strong> function.</p><p>The next function we create is the <strong>training</strong> function. It takes the following parameter; the input vector containing the movie ratings, the visible nodes obtained after <strong>k</strong> samplings, the vector of probabilities, and the probabilities of the hidden nodes after <strong>k</strong> samplings.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*siJKapf658PHltj6FclBfA.png" /></figure><p>Now we set the number of visible nodes to the length of the training set and the number of hidden nodes to 100. The number of visible nodes corresponds to the number of features in our training set. The number of hidden nodes determines the number of features that we’d like our RBM to detect. We also set a batch size of 100 and then call the class <strong>RBM</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/318/1*0FQhNuRuj8SA1WR9UG__VA.png" /></figure><p><strong>Part 3: Training the RBM Model</strong></p><p>The first step in training the RBM is to define the number of epochs. We then define a loop where all the training set will go through. After each epoch, the weight will be adjusted in order to improve the predictions. Finally, we obtain the visible nodes with the ratings of the movies that were not rated by the users.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*-DXDMYRaxoql13pMcjgtNQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/349/1*eVlyvkWDoTPJr94wHQLW_Q.png" /></figure><p><strong>Part 4: Testing the RBM Model</strong></p><p>Next, we test our RBM. In this stage, we use the training set data to activate the hidden neurons in order to obtain the output. This is how we get the predicted output of the test set. We then use the absolute mean to compute the test loss.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*ccv9Gg_bA1A5toS4LNcryQ.png" /></figure><p>If you want dataset and code you also check my <a href="https://github.com/AmirAli5/Deep-Learning"><strong>Github</strong></a> Profile.</p><h3>End Notes</h3><p>If you liked this article, be sure to click ❤ below to recommend it and if you have any questions, <strong>leave a comment</strong> and I will do my best to answer.</p><p>For being more aware of the world of machine learning, <a href="https://amiraliryk1.wixsite.com/portfolio"><strong>follow me</strong></a>. It’s the best way to find out when I write more articles like this.</p><p>You can also follow me on <a href="https://github.com/AmirAli5"><strong>Github</strong></a> for code &amp; dataset follow on <a href="https://uet.academia.edu/AliAmir"><strong>Aacademia.edu</strong></a> for this article, <a href="https://twitter.com/amir_ali_cheema"><strong>Twitter</strong></a><strong> </strong>and<strong> </strong><a href="http://amirali.cheema@outlook.com/"><strong>Email </strong></a>me directly or find me on<strong> </strong><a href="https://www.linkedin.com/in/amiralicheema/"><strong>LinkedIn</strong>.</a> I’d love to hear from you.</p><p>That’s all folks, Have a nice day :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c2ce76d94da5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/machine-learning-researcher/boltzmann-machine-c2ce76d94da5">Boltzmann Machine</a> was originally published in <a href="https://medium.com/machine-learning-researcher">Aorb Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Self Organizing Map(SOM)]]></title>
            <link>https://medium.com/machine-learning-researcher/self-organizing-map-som-c296561e2117?source=rss----32a2162bf0c7---4</link>
            <guid isPermaLink="false">https://medium.com/p/c296561e2117</guid>
            <category><![CDATA[k-means-clustering]]></category>
            <category><![CDATA[self-organizing-map]]></category>
            <category><![CDATA[kohonen-network]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Amir Ali]]></dc:creator>
            <pubDate>Sun, 26 May 2019 12:08:12 GMT</pubDate>
            <atom:updated>2019-12-07T19:22:45.955Z</atom:updated>
            <content:encoded><![CDATA[<h3>Self Organizing Map(SOM) with Practical Implementation</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*1gooOZOUKnXKzuae9mPZWg.png" /></figure><p>In this Chapter of Deep Learning, we will discuss Self Organizing Maps (SOM). It is an Unsupervised Deep Learning technique and we will discuss both theoretical and Practical Implementation from Scratch.</p><p><strong>This chapter spans 5 parts:</strong></p><ol><li>What is Self Organizing Maps?</li><li>K-Mean Clustering Technique.</li><li>SOMs Network Architecture.</li><li>How Self Organizing Maps work.</li><li>Practical Implementation of SOMs.</li></ol><h3>1: What is Self Organization Maps?</h3><p>The Self Organizing Map is one of the most popular neural models. It belongs to the category of the competitive learning network. The SOM is based on unsupervised learning, which means that is no human intervention is needed during the training and those little needs to be known about characterized by the input data. We could, for example, use the SOM for clustering membership of the input data. The SOM can be used to detect features inherent to the problem and thus has also been called SOFM the Self Origination Feature Map.</p><p>The Self Organized Map was developed by professor kohenen which is used in many applications.</p><p>the purpose of SOM is that it’s providing a data visualization technique that helps to understand high dimensional data by reducing the dimension of data to map. SOM also represents the clustering concept by grouping similar data together.</p><p>Therefore it can be said that Self Organizing Map reduces data dimension and displays similarly among data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*0PdY0c_2FFZ1-BY-_j0yRA.png" /></figure><h3>2. K-Mean Clustering Technique.</h3><h4>2.1: What is k-Mean?</h4><p>K-Means clustering aims to partition n observation into k clusters in which each observation belongs to the cluster with the nearest mean, serving as a prototype of the cluster.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/235/1*8-fVkj9l8AnQUfIqSOlMnw.png" /></figure><h4>2.2: How k-Mean Cluster work?</h4><p>The k-Means clustering algorithm attempt to split a given anonymous data set(a set of containing information as to class identity into a fixed number (k) of the cluster.</p><p>Initially, k number of the so-called centroid is chosen. A centroid is a data point (imaginary or real) at the center of the cluster.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/367/1*er4Y8d_W60WrbAMXvsSLcg.png" /></figure><p><strong>Dataset Description:</strong></p><p>This dataset has three attributes first is an item which is our target to make a cluster of similar items second and the third attribute is the informatics value of that item.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/573/1*XXf9WqsO2sXUA_StoPYHkA.png" /></figure><p>Now In the first step take any random row to let’s suppose I take row 1 and row 3.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/568/1*h186kOX-CuLk9vqWJ-Q56Q.png" /></figure><p>Now take these above centroid values to compare with observing the value of the respected row of our data by using the Euclidean Distance formula.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/539/1*yTGAAIZxuNSIUhKyAt_qrA.png" /></figure><p>Now let’s solve one by one</p><p><strong>Row 1 (A)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/211/1*eVI6MLxjOcJhBPndVTwnlA.png" /></figure><p><strong>Row 2 (B)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/197/1*ehI2Ne6OifOSS4bfLVDJ4g.png" /></figure><p><strong>Row 3 (C )</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/215/1*BwJ5g9kTpD4D893RAkMUDQ.png" /></figure><p><strong>Row 4 (D)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/211/1*6gnxz8c0dEGUaad1yhyqXA.png" /></figure><p><strong>Row 5 (E)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/199/1*ZjyrjsvHOr3FPXpd6_xN-w.png" /></figure><p><strong>Now</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/585/1*jeb8YgtZ6npRMEDhMHofsA.png" /></figure><p>Let’s say A and B are belong the Cluster 1 and C, D and E.</p><p>As we show in below table</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/1*vOWMShUGFWJeebfdQByFCQ.png" /></figure><p>Now calculate the centroid of cluster 1 and 2 respectively and again calculate the closest mean until calculate when our centroid is repeated previous one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/566/1*PiRZnfoiJHogqTl3p2HSeg.png" /></figure><p>Now find the Centroid of respected Cluster 1 and Cluster 2</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/225/1*d7wR-5mIhstAk_f849tu_A.png" /></figure><p><strong>New Centroid</strong></p><p>X1 = (1, 0.5)</p><p>X2 = (1.7,3.7)</p><p><strong>Previous Centroid</strong></p><p>X1 = (1, 1)</p><p>X2 = (0, 2)</p><p>If New Centroid Value is equal to previous Centroid Value then our cluster is final otherwise if not equal then repeat the step until new Centroid value is equal to previous Centroid value.</p><p>So in our case new centroid value is not equal to previous centroid.</p><p>Now recalculate cluster having the closest mean.</p><p>So</p><p>X1 = (1, 0.5)</p><p>X2 = (1.7,3.7)</p><p>Similarly procedure as we calculate above</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/595/1*0aP5NKPzB4EREUyFxoJrXA.png" /></figure><p>So based on based one, A B and C belongs to cluster 1 &amp; D and E from cluster 2.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/1*93cX0dBjwf5W2k77gQilCw.png" /></figure><p>So mean of Cluster I and 2</p><p>X1( Cluster 1 ) = ( 0.7 , 1)</p><p>X1( Cluster 2 ) = ( 2.5 , 4.5)</p><p><strong>New Centroid</strong></p><p>X1 = ( 0.7 , 1)</p><p>X2 = ( 2.5 , 4.5)</p><p><strong>Previous Centroid</strong></p><p>X1 = (1, 0.5)</p><p>X2 = (1.7,3.7)</p><p>If New Centoid Value is equal to previous Centroid Value then our cluster is final otherwise if not equal then repeat the step until new Centroid value is equal to previous Centroid value .</p><p>So in our case new centroid value is not equal to previous centroid.</p><p>Now recalculate cluster having a closest mean similar step</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/579/1*HlSOcgZhz0pqVzcVCBCbsQ.png" /></figure><p>So based on closest distance, A B and C belongs to cluster 1 &amp; D and E from cluster 2.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/575/1*SVav4FKNDJ7rdJD2DocNsQ.png" /></figure><p>So mean of Cluster I and 2</p><p>X1( Cluster 1 ) = ( 0.7 , 1)</p><p>X1( Cluster 2 ) = ( 2.5 , 4.5)</p><p><strong>New Centroid</strong></p><p>X1 = (1, 0.5)</p><p>X2 = (1.7,3.7)</p><p><strong>Previous Centroid</strong></p><p>X1 = (1, 0.5)</p><p>X2 = (1.7,3.7)</p><p>So here we have New Centroid values is Equal to previous value and Hence our cluster are final. A, B and C are belong to cluster 1 and D and E are belong to Cluster 2.</p><p>As shown in fig:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*zjh6FUTW02gLpYPNHHa_pQ.png" /></figure><h3>3. Self Organization Maps Network Architecture?</h3><p>For the purposes, we’ll be discussing a two-dimensional SOM. The network is created from a 2D lattice of ‘nodes’, each of which is fully connected to the input layer. The below Figure shows a very small Kohonen network of 4 X 4 nodes connected to the input layer (shown in green) representing a two-dimensional vector.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/192/1*KqqSQXGUWGvxsM5I91hu0g.png" /><figcaption><strong>A simple Kohonen network</strong></figcaption></figure><p>Each node has a specific topological position (an x, y coordinate in the lattice) and contains a vector of weights of the same dimension as the input vectors. That is to say, if the training data consists of vectors, <em>V</em>, of <em>n</em> dimensions:</p><p>V1, V2, V3…Vn</p><p>Then each node will contain a corresponding weight vector <em>W, </em>of <em>n </em>dimensions:</p><p>W1, W2, W3…Wn</p><p>The lines connecting the nodes in the above Figure are only there to represent adjacency and do not signify a connection as normally indicated when discussing a neural network. There are no lateral connections between nodes within the lattice.</p><h3>4. How Self Organization Maps work?</h3><h4>4.1: Learning Algorithm Overview</h4><p>A SOM does not need a target output to be specified unlike many other types of network. Instead, where the node weights match the input vector, that area of the lattice is selectively optimized to more closely resemble the data for the class the input vector is a member of. From an initial distribution of random weights, and over many iterations, the SOM eventually settles into a map of stable zones. Each zone is effectively a feature classifier, so you can think of the graphical output as a type of feature map of the input space.</p><p><strong>Training occurs in several steps and over many iterations:</strong></p><p>1. Each node’s weights are initialized.</p><p>2. A vector is chosen at random from the set of training data and presented to the lattice.</p><p>3. Every node is examined to calculate which ones weights are most like the input vector. The winning node is commonly known as the Best Matching Unit (BMU).</p><p>4. The radius of the neighborhood of the BMU is now calculated. This is a value that starts large, typically set to the ‘radius’ of the lattice, but diminishes each time-step. Any nodes found within this radius are deemed to be inside the BMU’s neighborhood.</p><p>5. Each neighboring node’s (the nodes found in step 4) weights are adjusted to make them more like the input vector. The closer a node is to the BMU; the more its weights get altered.</p><p>6. Repeat step 2 for N iterations.</p><h4>4.2: Learning Algorithm in Details.</h4><p>Now it’s time for us to learn how SOMs learn. Are you ready? Let’s begin. Right here we have a very basic self-organizing map.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/346/1*fORW9kNLagNAd1KPmn1CVA.png" /></figure><p>Our input vectors amount to three features, and we have nine output nodes.</p><p>That being said, it might confuse you to see how this example shows three input nodes producing nine output nodes. Don’t get puzzled by that. The three input nodes represent three columns (dimensions) in the dataset, but each of these columns can contain thousands of rows. The output nodes in a SOM are always two-dimensional.</p><p>Now what we’ll do is turn this SOM into an input set that would be more familiar to you from when we discussed the supervised machine learning methods (artificial, convolutional, and recurrent neural networks) in earlier chapters.</p><p>Consider the Structure of Self Organizing which has 3 visible input nodes and 9 outputs that are connected directly to input as shown below fig.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/453/1*1M8siT_wCkgB4QZ00dDXEQ.png" /></figure><p>Our input nodes values are:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/146/1*kvshcxjLcwpK5coVn31f2g.png" /></figure><p>Now let’s take a look at each step in detail.</p><p><strong>Step 1: Initializing the Weights</strong></p><p>Now, let’s take the topmost output node and focus on its connections with the input nodes. As you can see, there is a weight assigned to each of these connections.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/470/1*ZJcLgjMfo-Xa0oXqR50A8g.png" /></figure><p>Again, the word “weight” here carries a whole other meaning than it did with artificial and convolutional neural networks. For instance, with artificial neural networks we multiplied the input node’s value by the weight and, finally, applied an activation function. With SOMs, on the other hand, there is no activation function.</p><p>Weights are not separate from the nodes here. In a SOM, the weights belong to the output node itself. Instead of being the result of adding up the weights, the output node in a SOM contains the weights as its coordinates. Carrying these weights, it sneakily tries to find its way into the input space.</p><p>In this example, we have a 3D dataset, and each of the input nodes represents an x-coordinate. The SOM would compress these into a single output node that carries three weights. If we happen to deal with a 20-dimensional dataset, the output node, in this case, would carry 20 weight coordinates.</p><p>Each of these output nodes does not exactly become parts of the input space, but try to integrate into it nevertheless, developing imaginary places for themselves.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/476/1*heKQQSOKrMi5ZlfDT6FweA.png" /></figure><p>We have randomly initialized the values of the weights (close to 0 but not 0).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/525/1*FOPE8kt6MMmLonLGKbGbkg.png" /></figure><p><strong>Step 2: Calculating the Best Matching Unit</strong></p><p>The next step is to go through our dataset. For each of the rows in our dataset, we’ll try to find the node closest to it.</p><p>Say we take row number 1, and we extract its value for each of the three columns we have. We’ll then want to find which of our output nodes is closest to that row.</p><p>To determine the best matching unit, one method is to iterate through all the nodes and calculate the Euclidean distance between each node’s weight vector and the current input vector. The node with a weight vector closest to the input vector is tagged as the BMU.</p><p><strong>The Euclidean distance is given as:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/356/1*YWdBq03dGCge2rtLKf-vuw.png" /></figure><p>Where X is the current input vector and W is the node’s weight vector.</p><p>Let’s calculate the Best Match Unit using the Distance formula.</p><p>For 1st Nodes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/478/1*CIfJE7pWpS_hbAEVI4gT1w.png" /></figure><p>For 2nd Nodes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/546/1*ubSxRpy4Y9TBvzNDI7u9BQ.png" /></figure><p>For 3rd Nodes:</p><p>Similarly, way we calculate all remaining Nodes the same way as you can see below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/533/1*VPd-OFYMdfMz-EgId3akWA.png" /></figure><p>Similarly, way we calculate all remaining Nodes the same way as you can see below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/525/1*tLhX8HkK26KiKmmcadeI2Q.png" /></figure><p>Since we have calculated all the values of respected Nodes. Now it’s time to calculate the Best Match Unit.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/530/1*yI2oCkwkoXXety81zG_yCQ.png" /></figure><p>As we can see, node number 3 is the closest with a distance of 0.4. We will call this node our BMU (best-matching unit).</p><p><strong>What happens next?</strong></p><p>To understand this next part, we’ll need to use a larger SOM.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/254/1*dfuNXNEctnGhJ-xy8TihwA.png" /></figure><p>Supposedly you now understand what the difference is between weights in the SOM context as opposed to the one we were used to when dealing with supervised machine learning.</p><p>The red circle in the figure above represents this map’s BMU. Now, the new SOM will have to update its weights so that it is even closer to our dataset’s first row. The reason we need this is that our input nodes cannot be updated, whereas we have control over our output nodes.</p><p>In simple terms, our SOM is drawing closer to the data point by stretching the BMU towards it. The end goal is to have our map as aligned with the dataset as we see in the image on the far right</p><p><strong>Step 3: Calculating the size of the neighborhood around the BMU</strong></p><p>This is where things start to get more interesting! Each iteration, after the BMU has been determined, the next step is to calculate which of the other nodes are within the BMU’s neighborhood. All these nodes will have their weight vectors altered in the next step. So how do we do that? Well, it’s not too difficult… first, you calculate what the radius of the neighborhood should be and then it’s a simple application of good ol’ Pythagoras to determine if each node is within the radial distance or not.</p><p>The figure shows an example of the size of a typical neighborhood close to the commencement of training.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/215/1*Gep4eigbq9sKXpXBk3516A.png" /></figure><p>You can see that the neighborhood shown above is centered around the BMU (red-point) and encompasses most of the other nodes and circle show radius.</p><p>The size of the neighborhood around the BMU is decreasing with an exponential decay function. It shrinks on each iteration until reaching just the BMU</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/436/1*ZJ382ByaRRP1-31cxb1kVw.png" /></figure><p>Where t = 0, 1, 2, 3….</p><p>Figure below shows how the neighborhood decreases over time after each iteration</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/349/1*jJbbLejw1e4IDOUI-Jb0SQ.png" /></figure><p>Over time the neighborhood will shrink to the size of just one node… the BMU.</p><p>Now we know the radius, it’s a simple matter to iterate through all the nodes in the lattice to determine if they lay within the radius or not. If a node is found to be within the neighborhood then its weight vector is adjusted as follows in Step 4.</p><p><strong>How to set the radius value in the self-organizing map?</strong></p><p>It depends on the range and scale of your input data. If you are mean-zero standardizing your feature values, then try σ=4. If you are normalizing feature values to a range of [0, 1] then you can still try σ=4, but a value of σ=1 might be better. Remember, you have to decrease the learning rate α and the size of the neighborhood function with increasing iterations, as none of the metrics stay constant throughout the iterations in SOM.</p><p>It also depends on how large your SOM is. If it’s a 10 by 10, then use for example σ=5. Otherwise, if it’s a 100 by 100 map, use σ=50.</p><p>In unsupervised classification, σ is sometimes based on the Euclidean distance between the centroids of the first and second closest clusters.</p><p><strong>Step 4: Adjusting the Weights</strong></p><p>Every node within the BMU’s neighborhood (including the BMU) has its weight vector adjusted according to the following equation:</p><p>New Weights = Old Weights + Learning Rate (Input Vector — Old Weights)</p><p>W(t+1) = W(t) + L(t) ( V(t) — W(t) )</p><p>Where t represents the time-step and L is a small variable called the learning rate, which decreases with time. What this equation is sayiWhatnewly adjusted weight for the node is equal to the old weight (W), plus a fraction of the difference (L) between the old weight and the input vector (V).</p><p>So according to our example are Node 4 is Best Match Unit (as you can see in step 2) corresponding their weights:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/530/1*hGGVOUGKYrM4aVdR-jK_dg.png" /></figure><p>Learning rate = 0.5</p><p>So update that weight according to the above equation</p><p>For W3,1</p><p>New Weights = Old Weights + Learning Rate (Input Vector1 — Old Weights)</p><p>New Weights = 0.39 + 0.5 (0.7–0.39)</p><p>New Weights = 0.545</p><p>For W3,2</p><p>New Weights = Old Weights + Learning Rate (Input Vector2 — Old Weights)</p><p>New Weights = 0.42 + 0.5 (0.6–0.42)</p><p>New Weights = 0.51</p><p>For W3,3</p><p>New Weights = Old Weights + Learning Rate (Input Vector3 — Old Weights)</p><p>New Weights = 0.45 + 0.5 (0.9–0.45)</p><p>New Weights = 0.675</p><p><strong>Updated weights:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*uEet0tAV_ZWm7MzpIkTXsw.png" /></figure><p>So in this way we update the weights.</p><p>The decay of the learning rate is calculated each iteration using the following equation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/192/1*fpz6XLr5tDY_UESaIttBMQ.png" /></figure><p>As training goes on, the neighborhood gradually shrinks. At the end of the training, the neighborhoods have shrunk to zero sizes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/285/1*Mg9BN8C6Adgd9y6I5rAbMw.png" /></figure><p>The influence rate shows the amount of influence a node’s distance from the BMU has on its learning. In the simplest form influence rate is equal to 1 for all the nodes close to the BMU and zero for others, but a Gaussian function is common too. Finally, from a random distribution of weights and through many iterations, SOM can arrive at a map of stable zones. In the end, interpretation of data is to be done by a human but SOM is a great technique to present the invisible patterns in the data.</p><p><strong>Note: </strong>If you want this article check out my<strong> </strong><a href="https://www.academia.edu/41216265/An_Intuitive_Guide_of_Self_Organizing_Maps_with_Practical_Implementation_in_Minisom"><strong>academia.edu</strong></a><strong> </strong>profile.</p><h3>5. Practical Implementation of SOMs?</h3><h4>Fraud Detection</h4><p>According to a recent report published by Markets &amp; Markets, the Fraud Detection and Prevention Market is going to be worth USD 33.19 Billion by 2021. This is a huge industry and the demand for advanced Deep Learning skills is only going to grow. That’s why we have included this case study in this chapter.</p><p>The business challenge here is about detecting fraud in credit card applications. We will be creating a Deep Learning model for a bank and given a dataset that contains information on customers applying for an advanced credit card.</p><p>This is the data that customers provided when filling the application form. Our task is to detect potential fraud within these applications. That means that by the end of the challenge, we will come up with an explicit list of customers who potentially cheated on their applications.</p><p><strong>Dataset</strong></p><p><strong>Data Set Information: </strong>This file concerns credit card applications. All attribute names and values have been changed to meaningless symbols to protect the confidentiality of the data. <br> This dataset is interesting because there is a good mix of attributes — continuous, nominal with small numbers of values, and nominal with larger numbers of values. There are also a few missing values.</p><p><strong>Attribute Information:</strong> There are 6 numerical and 8 categorical attributes. The labels have been changed for the convenience of the statistical algorithms. For example, attribute 4 originally had 3 labels p,g, gg and these have been changed to labels 1,2,3. <br> A1: 0,1 CATEGORICAL (formerly: a,b) <br> A2: continuous. <br> A3: continuous. <br> A4: 1,2,3 CATEGORICAL (formerly: p,g,gg) <br> A5: 1, 2,3,4,5,6,7,8,9,10,11,12,13,14 CATEGORICAL (formerly: ff,d,i,k,j,aa,m,c,w, e, q, r,cc, x) <br> A6: 1, 2,3, 4,5,6,7,8,9 CATEGORICAL (formerly: ff,dd,j,bb,v,n,o,h,z) <br> A7: continuous. <br> A8: 1, 0 CATEGORICAL (formerly: t, f) <br> A9: 1, 0 CATEGORICAL (formerly: t, f) <br> A10: continuous. <br> A11: 1, 0 CATEGORICAL (formerly t, f) <br> A12: 1, 2, 3 CATEGORICAL (formerly: s, g, p) <br> A13: continuous. <br> A14: continuous. <br> A15: 1,2 class attribute (formerly: +,-)</p><p><strong>Dataset sample:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*MFGnDI4TIZ5abp3q6hE6DQ.png" /></figure><p>Let’s solve the problem</p><p><strong>Part 1: Data Preprocessing</strong></p><p><strong><em>1.1 Import the Libraries</em></strong></p><p>In this step, we import three Libraries in Data Preprocessing part. A library is a tool that you can use to make a specific job. First of all, we import the <strong>numpy</strong> library used for multidimensional array then import the <strong>pandas </strong>library<strong> </strong>used to import the dataset and in last we import <strong>matplotlib </strong>library used for plotting the graph.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/381/1*9qJqMRr-8PHP5X-a01JlZQ.png" /></figure><p><strong><em>1.2 Import the dataset</em></strong></p><p>In this step, we import the dataset to do that we use the <strong>pandas</strong> library. After import our dataset we define our dependent and independent variable. Our independent variables are 1 to 12 attributes as you can see in the sample dataset which we call ‘<strong>X’</strong> and dependent is our last attribute which we call ‘<strong>y</strong>’ here.</p><p><strong>Note:</strong> we will build the SOMs model which is unsupervised deep learning so we are working with independent variables.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*iY5oj3TEkGNgycyW9Qug3Q.png" /></figure><p><strong><em>1.3 Feature Scaling</em></strong></p><p>Feature Scaling is the most important part of data preprocessing. If we see our dataset then some attribute contains information in Numeric value some value very high and some are very low if we see the age and estimated salary. This will cause some issues in our machinery model to solve that problem we set all values on the same scale there are two methods to solve that problem first one is Normalize and Second is Standard Scaler.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*wuCX1bjSh6YXcu8tuA5wyw.png" /></figure><p>Here we use Normalize import from Sklearn Library.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/549/1*ZLytX3ZO5CxLZRaxPVyl_A.png" /></figure><p><strong>Part 2: Building &amp; Train our Model</strong></p><p>In this part, we model our Self Organizing Maps model.</p><p><strong><em>2.1 Import the Model</em></strong></p><p>In this step, we import our SOM models which are made by other developers. Link: <a href="https://test.pypi.org/project/MiniSom/1.0/">https://test.pypi.org/project/MiniSom/1.0/</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/336/1*6bpgmogNjGvDuSe6ayVCog.png" /></figure><p><strong><em>2.2 Initialize our SOM model</em></strong></p><p>In this step, we initialize our SOM model and we pass several parameters here. The first two are the dimension of our SOM map here <strong>x= 10 &amp; y= 10</strong> mean we take 10 by 10 grid. The third parameter is <strong>input length</strong> we have 15 different attributes in our data set columns so input_lenght=15 here. The fourth parameter is <strong>sigma</strong> is the radius of a different neighborhood in the grid so we will keep 1.0 here which is the default value for SOMs. And last past parameters are <strong>learning rate</strong> which is hyperparameter the size of how much weight is updated during each iteration so higher is learning rate the faster is conversion and we keep the default value which is 0.5 here.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*GoJ5vp9sI3z6_gNmjtzALQ.png" /></figure><p><strong><em>2.3 Initialize the weights</em></strong></p><p>In this step, we randomly initialize our weights from by using our SOM models and we pass only one parameter here which our data(X).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/331/1*A6QIfPAdcNzeM3GpyFb4hQ.png" /></figure><p><strong><em>2.4 Train the Model</em></strong></p><p>In this step we train our model here we pass two arguments here first is our data and the second is the number of iteration here we choose 100.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/558/1*BfcaROoiWOAeJx_cM6Iicg.png" /></figure><p><strong>Part 3: Visualizing the result</strong></p><p>In this step, we build a map of the Self Organizing Map. Firstly we import the library pylab which is used for the visualization of our result and we import different packages here. Bone is making a window then in the third line of code, we take a mean of all wining nodes. Then make of color bar which value is between 0 &amp; 1. In Marker, we take a circle of red color which means the customer didn’t get approval and square of green color which gets which customer gets approval. Then we make a for loop (i here correspond to index vector and x corresponds to customers) and inside for loop we take a wining node of each customer and this wining node is replaced by color marker on it and w[0] (x coordinate) and w[1] (y coordinate) are two coordinate ) and then make a color of and take dependent variable which is 0 or 1 mean approval customer or didn’t get approval and take a marker value of ( o for red and s for green ) and replace it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*qa0snhRBmKIt4MJk_CvRKg.png" /></figure><p>Here is our Self Organizing map red circle mean customer didn’t get approval and green square mean customer get approval. And if we look at our outlier then the white color area is high potential fraud which we detect here. And in the next part, we catch this cheater as you can see this both red and green.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/530/1*ENX-685z37Vg-g5bcNGPww.png" /></figure><p><strong>Part 4: Catch the Potential Fraud</strong></p><p>In this part, we catch the potential fraud of customer from the self-organizing map which we visualize in above</p><p><strong><em>4.1 Mapping the wining node</em></strong></p><p>In this step, we map all the wining nodes of customers from the Self Organizing Map.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/317/1*6_fqSqKtXZp0xrdz9QVqEw.png" /></figure><p><strong><em>4.2 Catch the cheater</em></strong></p><p>In this step we catch the fraud to do that we take only those customer who potential cheat if we see in our SOM then clearly see that mapping [(7, 8), (3, 1) and (5, 1)] are potential cheat and use concatenate to concatenate of these three mapping values to put them in same one list.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*mMSeOWhZQHLJ0yzu125Oxg.png" /></figure><p><strong><em>4.3 Rescale the value</em></strong></p><p>In this step, we convert our scale value into the original scale to do that we use the inverse function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/503/1*GAd_mNQSIVKfF6tQseZ3fg.png" /></figure><p><strong><em>4.4 Final results</em></strong></p><p>Then simply call frauds and you get the whole list of those customers who potential cheat the bank.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/93/1*aRA6XtA47xcF9Y04zFwA-Q.png" /></figure><p>If you want dataset and code you also check my <a href="https://github.com/AmirAli5/Deep-Learning"><strong>Github</strong></a> Profile.</p><h3>End Notes</h3><p>If you liked this article, be sure to click ❤ below to recommend it and if you have any questions, <strong>leave a comment</strong> and I will do my best to answer.</p><p>For being more aware of the world of machine learning, <a href="https://amiraliryk1.wixsite.com/portfolio"><strong>follow me</strong></a>. It’s the best way to find out when I write more articles like this.</p><p>You can also follow me on <a href="https://github.com/AmirAli5"><strong>Github</strong></a> for code &amp; dataset follow on <a href="https://uet.academia.edu/AliAmir"><strong>Aacademia.edu</strong></a> for this article, <a href="https://twitter.com/amir_ali_cheema"><strong>Twitter</strong></a><strong> </strong>and<strong> </strong><a href="http://amirali.cheema@outlook.com/"><strong>Email </strong></a>me directly or find me on<strong> </strong><a href="https://www.linkedin.com/in/amiralicheema/"><strong>LinkedIn</strong>.</a> I’d love to hear from you.</p><p>That’s all folks, Have a nice day :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c296561e2117" width="1" height="1" alt=""><hr><p><a href="https://medium.com/machine-learning-researcher/self-organizing-map-som-c296561e2117">Self Organizing Map(SOM)</a> was originally published in <a href="https://medium.com/machine-learning-researcher">Aorb Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Recurrent Neural Network (RNN)]]></title>
            <link>https://medium.com/machine-learning-researcher/recurrent-neural-network-rnn-e6f69db16eba?source=rss----32a2162bf0c7---4</link>
            <guid isPermaLink="false">https://medium.com/p/e6f69db16eba</guid>
            <category><![CDATA[backpropagation]]></category>
            <category><![CDATA[recurrent-neural-network]]></category>
            <category><![CDATA[exploding-gradient]]></category>
            <category><![CDATA[vanishing-gradient]]></category>
            <category><![CDATA[long-short-term-memory]]></category>
            <dc:creator><![CDATA[Amir Ali]]></dc:creator>
            <pubDate>Thu, 23 May 2019 06:27:47 GMT</pubDate>
            <atom:updated>2019-12-07T16:54:43.756Z</atom:updated>
            <content:encoded><![CDATA[<h3>Recurrent Neural Network &amp; LSTM with Practical Implementation</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*f8BynDnbyZ3HBFcZqm-tmg.png" /></figure><p>In this Fourth Chapter of Deep Learning, we will discuss the Recurrent Neural Network and LSTM. It is a Supervised Deep Learning technique and we will discuss both theoretical and Practical Implementation from Scratch.</p><p><strong>This chapter spans 7 parts:</strong></p><ol><li>What is the Recurrent Neural Network?</li><li>Understand a Recurrent Neural Network in Detail.</li><li>Forward Propagation in Recurrent Neural Network.</li><li>Backpropagation is an RNN (BPTT).</li><li>Vanishing and Exploding Gradient Problem.</li><li>Long Short Term Memory (LSTM).</li><li>Practical Implementation of Recurrent Neural Network &amp; LSTM.</li></ol><h3>1. What is the Recurrent Neural Network?</h3><p>Let’s say the task is to predict the next word in a sentence. Let’s try accomplishing it using an MLP. So what happens in an MLP. In the simplest form, we have an input layer, a hidden layer, and an output layer. The input layer receives the input, the hidden layer activations are applied and then we finally receive the output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/149/1*FRHimf-ZhB6Yv7zc96qpgQ.png" /></figure><p>Let’s have a deeper network, where multiple hidden layers are present. So here, the input layer receives the input, the first hidden layer activations are applied and then these activations are sent to the next hidden layer, and successive activations through the layers to produce the output. Each hidden layer is characterized by its owights and biases.</p><p>Since each hidden layer has its owights and activations, they behave independently. Now the objective is to identify the relationship between successive inputs. Can we supply the inputs to hidden layers? Yes, we can!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/150/1*oAtBtUKsSBwHQSWQo_Zn6Q.png" /></figure><p>Here, the weights and bias of these hidden layers are different. And hence each of these layers behaves independently and cannot be combined too combine these hidden layers toe shall have the same weights and bias for these hidden layers.</p><p>We can now combine these layers tohat the weights and bias of all the hidden layers are the same. All these hidden layers can be rolled in together in a single recurrent layer.</p><p>So it’s like supplying the input to the hidden layer. At all the time steps weights of the recurrent neuron would be the same since it’s a single neuron now. So a recurrent neuron stores the state of a previous input and combines with the current input thereby preserving some relationship of the current input with the previous input.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/708/1*lW2-A9AeJYikokluUXV3NA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/706/1*e4BmeILjDspkxem01ZzDLQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/693/1*bwsItCrci52Xv4L5E8ebaA.png" /></figure><h3>2. Understand a Recurrent Neural Network in Details.</h3><p>Let’s take a simple task at first. Let’s take a character level RNN where we have the word “Hello”. So we provide the first 4 letters i.e. h,e,l,l and ask the network to predict the last letter i.e.’ o’. So here the vocabulary of the task is just 4 letters {h,e,l,o}. In real case scenarios involving natural language processing, the vocabularies include the words in the entire Wikipedia database or all the words in a language. Here for simplicity, we have taken a very small set of vocabulary.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/200/1*G2SRcJV39TUqSKoqgwfuRA.png" /></figure><p>Let’s see how the above structure be used to predict the fifth letter in the word “hello”. In the above structure, the blue RNN block applies something called a recurrence formula to the input vector and also its previous state. In this case, the letter “h” has nothing preceding it, let’s take the letter “e”. So at the time the letter “e” is supplied to the network, a recurrence formula is applied to the letter “e” and the previous state which is the letter “h”. These are known as various time steps of the input. So if at time t, the input is “e”, at time t-1, the input was “h”. The recurrence formula is applied to e and h both. and we get a new state.</p><p><strong>The formula for calculating current state:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/183/1*MAy2urszAbVkwcxraX3mLw.png" /></figure><p>Where:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/204/1*dDdiluQ1J4GZENGghXxguw.png" /></figure><p>We now have a state of the previous input instead of the input itself, because the input neuron would have applied the transformations on our previous input. So each successive input is called a time step.</p><p>In this case, we have four inputs to be given to the network, during a recurrence formula, the same function and the same weights are applied to the network at each time step.</p><p>Let’s take a look at how we can calculate these states in Excel and get the output.</p><p><strong>The formula for applying Activation function (tanh):</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/361/1*h1v9MB2r-vwsbPCW3ghZig.png" /></figure><p>Where:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/293/1*_fVnTo7yP6ecE6DN0AJBUQ.png" /></figure><p>Taking the simplest form of a recurrent neural network, let’s say that the activation function is tanh, the weight at the recurrent neuron is Whh and the weight at the input neuron is Wxh.</p><p>The Recurrent neuron, in this case, is just taking the considering the immediately previous stater sequences, the equation can involve multiple such states. Once the final state is calculated we can go on to produce the output</p><p>Now, once the current state is calculated we can calculate the output state as</p><p><strong>The formula for calculating output:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/149/1*JPZmaGQvfS9HIsYalNZStg.png" /></figure><p>Where:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/292/1*TS9Xq5SGzVaPtHh_NM-dMw.png" /></figure><p><strong>Let me summarize the steps in a recurrent neuron</strong></p><ol><li>A single time step of the input is supplied to the network i.e. xt is supplied to the network</li><li>We then calculate its current state using a combination of the current input and the previous state i.e. we calculate ht</li><li>The current ht becomes ht-1 for the next time step</li><li>We can go as many time steps as the problem demands and combine the information from all the previous states</li><li>Once all the time steps are completed the final current state is used to calculate the output yt</li><li>The output is then compared to the actual output and the error is generated</li><li>The error is then backpropagated to the network to update the weights(we shall go into the details of backpropagation in further sections) and the network is trained</li></ol><h3>3. Forward Propagation in a Recurrent Neuron.</h3><p>Let’s take a look at the inputs first –</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/263/1*3-Z5chGdXPMdXRPBRime3A.png" /></figure><p>The inputs are one-hot encoded. Our entire vocabulary is {h,e,l,o} and hence we can easily one-hot encode the inputs.</p><p>Now the input neuron would transform the input to the hidden state using the weight wxh. We have randomly initialized the weights as a 3*4 matrix –</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/275/1*MkjzVdhwFymqaTchg-5gQQ.png" /></figure><p><strong>Step 1:</strong></p><p>Now for the letter “h”, for the hidden state, we would need Wxh*Xt. By matrix multiplication, we get it as –</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*9G5GUaReugJbB45daY7X-g.png" /></figure><p><strong>Step 2:</strong></p><p>Now moving to the recurrent neuron, we have <strong>Whh</strong> as the weight which is a 1*1 matrix as 0.42703 and the bias which is also a 1*1 matrix as 0.56700</p><p>For the letter “h”, the previous state is [0,0,0] since there is no letter prior to it.</p><p>So beforelate -&gt; (whh*ht-1+bias)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/613/1*7CX3gBtlXVCpj59iiPyISQ.png" /></figure><p><strong>Step 3:</strong></p><p>Now we can get the current state as –</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*7-qbHV6pllIhtoGZUVPYXw.png" /></figure><p>Since for h, there is no previous hidden state we apply the tanh function to this output and get the current state –</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/614/1*fmd6Cd_I-MD08tgh7gb8rg.png" /></figure><p><strong>Step 4:</strong></p><p>Now we go on to the next state. “e” is now supplied to the network. The processed output of ht, now becomes ht-1, while the one-hot encoded e, is xt. Let’s now calculate the current state ht.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*7-qbHV6pllIhtoGZUVPYXw.png" /></figure><p>Whh*ht-1 +bias will be –</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/633/1*5PSE9C5vCuUY9O8IERPnGQ.png" /></figure><p>Wxh*xt will be –</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/616/1*R6cqhDSqCS7riY-E3nhxDQ.png" /></figure><p><strong>Step 5:</strong></p><p>Now calculating ht for the letter “e”,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/632/1*nLFqIQYJ5QlewOZ891lR9g.png" /></figure><p>Now, this would become ht-1 for the next state and the recurrent neuron would use this along with the new character to predict the next one.</p><p><strong>Step 6:</strong></p><p>At each state, the recurrent neural network would produce the output as well. Let’s calculate yt for the letter e.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/162/1*CO3uiNL80SRctKwMV487DQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/639/1*GsHoIkLLsGAxmrrbSQmVEA.png" /></figure><p><strong>Step 7:</strong></p><p>The probability for a particular letter from the vocabulary can be calculated by applying the softmax function. so we shall have softmax(yt)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/608/1*Gu5HNb4ocHsluRIe4RiQmg.png" /></figure><p>If we convert these probabilities to understand the prediction, we see that the model says that the letter after “e” should be h, since the highest probability is for the letter “h”. Does this mean we have done something wrong? No, so here we have hardly trained the network. We have just shown it two letters. So it pretty much hasn’t learned anything yet.</p><p>Now the next BIG question that faces us is how does Backpropagation work in case of a Recurrent Neural Network. How are the weights updated while there is a feedback loop?</p><h3>4. Backpropagation is an RNN (BPTT).</h3><p>To imagine how weights would be updated in case of a recurrent neural network, might be a bit of a challenge. So to understand and visualize the backpropagation, let’s unroll the network at all the time steps. In an RNN we may or may not have outputs at each time step.</p><p>In the case of forwarding propagation, the inputs enter and move forward at each time step. In case of backward propagation, in this case, we are figuratively going back in time to change</p><p>the weights, hence we call it the Backpropagation through time(BPTT).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/632/1*Tn9BWchhdMntFuuxBgpiAg.png" /></figure><p>In case of an RNN, if yt is the predicted value ȳt is the actual value, the error is calculated as a cross-entropy loss –</p><p>Et(ȳt,yt) = — ȳt log(yt)</p><p>E(ȳ,y) = — ∑ ȳt log(yt)</p><p>We typically treat the full sequence (word) as one training example, so the total error is just the sum of the errors at each time step (character). The weights as we can see are the same at each time step. Let’s summarize the steps for backpropagation</p><ol><li>The cross-entropy error is first computed using the current output and the actual output</li><li>Remember that the network is unrolled for all the time steps</li><li>For the unrolled network, the gradient is calculated for each time step with respect to the weight concerninghat the weight is the same for all the time steps the gradients can be combined together for all time stepshts are then updated for both recurrent neuron and the dense layers</li></ol><p>The unrolled network looks much like a regular neural network. And the backpropagation algorithm is similar to a regular neural network, just that we combine the gradients of the error for all time steps. Now, what do you think might happen, if there are 100s of time steps. This would basically take really long tworkverge since after unrolling the network becomes really huge.</p><p>In case you dosh to deep dive into the math of backpropagation, all you need to understand is that backpropagation through time works similarly as it does in a regular neural network once you unroll the recurrent neuron in your network. However, I shall be coming up with a detailed article on Recurrent Neural networks with scratch with would have the detailed mathematics of the backpropagation algorithm in a recurrent neural network.</p><h3>5. Vanishing and Exploding Gradient Problem.</h3><p>Recurrent Neural Networks use a <strong>backpropagation algorithm</strong> for training, <strong>but</strong> it is <strong>applied</strong> for every <strong>timestamp.</strong> It is commonly known as <strong>Back-propagation Through Time (BTT) which we already discussed above.</strong></p><p>There are <strong>some issues</strong> with Back-propagation such as:</p><ul><li><strong>Vanishing Gradient</strong></li><li><strong>Exploding Gradient</strong></li></ul><p>Let us consider each of these to understand what is going on</p><h4>5.1: Vanishing Gradient</h4><p>When making use of back-propagation the goal is to calculate the error which is actually found out by findie difference between the actual output and the model output and raising that to a power of 2.</p><p>Consider the following diagram:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*AEfbEBzYS0znMQyPfmvBDQ.png" /></figure><p>With the error calculated, the changes in the error with respect to the change iconcerninge calculated. But with each learning rate, this has to be multiplied with the same.</p><p>So, the product of the learning rate with the change leads to the value which is the actual change in the weight. This change in weight is added to the old set of weights for every training iteration as shown in the figure. The issue here is when the change in weight is multiplied, the value is very less. Consider you are predicting a sentence say, “I am going to Rahim Yar Khan” and you want to predict “I am going to Rahim Yar Khan, the language spoken there is _____”</p><p>A lot of iterations will cause the new weights to be extremely negligible and this leads to the weights not being updated.</p><h4>5.2. Exploding Gradient</h4><p>The working of the exploding gradient is similar but the weights here change drastically instead of negligible change. Notice the small change in the diagram below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*Cs5gl6oIs50Sx0Rj8JR63Q.png" /></figure><p>We need to overcome both of these and it is a bit of a challenge at first. Consider the following chart</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/714/1*B-rdCTy0HPGrMY8-gD_Pew.png" /></figure><h3>6. Long Short Term Memory (LSTM).</h3><p>Long Short-Term Memory networks are usually just called “LSTMs”.</p><p>They are a special kind of Recurrent Neural Networks that are capable of learning long-term dependencies.</p><p><strong>What are long-term dependencies?</strong></p><p>Many times only recent data is needed in a model to perform operations. But there might be a requirement from data which was obtained in the past.</p><p>Let’s look at the following example:</p><p>Consider a language model trying to predict the next word based on the previous ones. If we are trying to predict the last word in the sentence say “The clouds are in the sky”.</p><p>The context here was pretty simple and the last word ends up being sky all the time. In such cases, the gap between the past information and the current requirement can be bridged really easily by using Recurreal Networks.</p><p>So, problems like Vanishing and Exploding Gradients do not exist and this makes LSTM networks handle long-term dependencies easily.</p><p>LSTM has a chain-like neural network layer. In a standard recurrent neural network, the repeating module consists of one single function as shown in the below figure:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/395/1*HlUWL6XIYyaGPedB_QWMiw.png" /></figure><p>As shown above, there is a tanh function present in the layer. This function is a squashing function. So, what squashingion?</p><p>It is a function that is basically used in the range of nd to manipulate the values based on the inputs.</p><p>Now, let us consider the structure of an LSTM network:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/507/1*sqfkjtuTkx9Ri_-e0fhyJA.png" /></figure><p>As denoted from the image, each of the functions in the layers has its own structures when it comes to networks. The cell state is the horizontal line in the figure and it acts like a conveyer belt carrying certain data linearly across the data channel.</p><p>Let us consider a step-by-step approach to understand LSTM networks better.</p><p><strong>Step 1:</strong></p><p>The first step in the LSTM is to identify that information which is not required and will be thrown away from the cell state. This decision is made by a sigmoid layer called a forget gate layer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/240/1*yC7lBGEQMnJKypeVdG023A.png" /></figure><p>The highlighted layer in the above is the sigmoid layer which is previously mentioned.</p><p>The calculation is done by considering the new input and the previous timestamp which eventually leads to the output of a number between 0 and 1 for each number in that cell state. As a typical binary, 1 represents to keep the cell state while 0 represents to trash it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/312/1*8o1YKQyUOgDZy_0WiZlp8w.png" /></figure><p>Consider gender classification, it is really important to consider the latest and correct gender when the network is being used.</p><p><strong>Step 2:</strong></p><p>The next step is to decide, what new information we’re going to store in the cell state. This whole process comprises of following steps:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/349/1*ekN4PVtmKuxU0VYLpB0yJQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*Wb_agNLjKM_LcJb3jJg_WA.png" /></figure><p>A sigmoid layer called the “input gate layer” decides which values will be updated.</p><p>The tanh layer creates a vector of new candidate values that could be added to the state.</p><p>The input from the previous timestamp and the new input are passed through a sigmoid function which gives the value i(t). This value is then multiplied by c(t) and then added to the cell state.</p><p>In the next step, these two are combined to update the state.</p><p><strong>Step 3:</strong></p><p>Now, we will update the old cell state Ct−1, into the new cell state Ct.</p><p>First, we multiply the old state (Ct−1) by f(t), forgetting the things we decided to leave behind earlier.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/340/1*IDcjN2qud075XzhqfUtTjA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/342/1*IDwbF_eh52u9dRUZwTQOXg.png" /></figure><p>We add i_t* c˜_t. This is the new candidate values, scaled by how much we decided to update each state value.</p><p>In the second step, we decided to do make use of the data which is only required at that stage.</p><p>In the third step, we actually implement it.</p><p>In the languagemple which was previously discussed, there is where the old gender would be dropped and the new gender would be considered.</p><p><strong>Step 4:</strong></p><p>We will run a sigmoid layer which decides what parts of the cell state we’re going to output.<strong> </strong>Then, we put the cell state through tanh (push the values to be between −1 and 1).<strong> </strong>Later, we multiply it by the output of the sigmoid gate, so that we only output the parts we decided to.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/1*quETXJadeK3VBbxal5U-ow.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/413/1*Ng36X18LX_tg1yVRUmlt6Q.png" /></figure><p>The calculation in this step is pretty much straightforward which eventually leads to the output. However, the output consists of only the outputs there were decided to be carried forwarded in the previous steps and not all the outputs at once.</p><p><strong>Summing up all the 4 steps:</strong></p><p>1. In the first step, we found out what was needed to be dropped.</p><p>2. The second step consisted of what new inputs are added to the network.</p><p>3. The third step was to combine the previously obtained inputs to generate the new cell states.</p><p>4. Lastly, we arrived at the output as per requirement.</p><p>Let’s consider an interesting use-case.</p><h4>Use Case: Long Short-Term Memory Networks</h4><p>The use case we will be <strong>considering</strong> is to <strong>predict</strong> the <strong>next word</strong> in a sample short story.</p><p>We can start by <strong>feeding</strong> an <strong>LSTM</strong> Network with <strong>correct sequences</strong> from the text of 3 <strong>symbols</strong> as <strong>inputs</strong> and 1 labeled symbol.</p><p>Eventually, the neural network will <strong>learn</strong> to <strong>predict</strong> the next symbol <strong>correctly!</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/467/1*-lMrUqsPo8ap1erKY-gxSw.png" /></figure><p><strong>Dataset:</strong></p><p>The LSTM is trained using a <strong>sample short story</strong> which consists of <strong>112 unique symbols. Comma</strong> and <strong>period</strong> are also <strong>considered</strong> as <strong>unique symbols</strong> in this <strong>case.</strong></p><p><em>“Long ago, the mice had a general council to consider what measures they could take to outwit their common enemy, the cat. some said this, and some said that but at last a young mouse got up and said he had a proposal to make, which he thought would meet the case . You will all agree, said he that our chief danger consists in the sly and treacherous manner in whicslyly and treacherouslyf we could receive some signal of her approach, we could easily escape from her. I venture, therefore, to propose that a small bell be procured, and attached by a ribbon around the neck of the cat. By this means we should always know when she was about, and could easily retire while she was in the neighborhood. This proposal met with general applause until an old mouse got up and said that it is all very well, but who is to bell the cat? The mice looked at one another and nobody spoke. Then the old mouse said it is easy to propose impossible remedies.”</em></p><p><strong>Training:</strong></p><p>We already know that <strong>LSTMs</strong> can only <strong>understand real numbers.</strong> So, the first <strong>requirement</strong> is to <strong>convert</strong> the unique symbols into <strong>unique integer</strong> values based on the <strong>frequency</strong> of <strong>occurrence.</strong></p><p>Doing this will create a <strong>customized dictionary</strong> that we can <strong>make use</strong> later on to <strong>map</strong> the values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/422/1*s15I85jdNvZ964AexJcr6Q.png" /></figure><p>In the above figure, <strong>certain symbols</strong> are mapped to be <strong>integers</strong> as shown.</p><p>The network will create a <strong>112-element vector</strong> consisting of the <strong>probability</strong> of <strong>occurrence</strong> of each of these unique integer values.</p><p><strong>Note</strong>: If you want this article check out my <a href="https://www.academia.edu/41209114/A_Deep_Level_Understanding_of_Recurrent_Neural_Network_and_LSTM_with_Practical_Implementation_in_Keras_and_Tensorflow"><strong>academia.edu</strong></a> profile.</p><h3>7. Practical Implementation of Recurrent Neural Network and LSTM.</h3><h4>Stock Price Prediction</h4><p>In this part, we will create one of the most powerful Deep Learning models. We will even go as far as saying that we will create the Deep Learning model closest to “Artificial Intelligence”. Why is that? Because this model will have long-term memory, just like us, humans.</p><p>The branch of Deep Learning which facilitates this is Recurrent Neural Networks. Classic RNNs have a short memory and were neither popular nor powerful for this exact reason. But a recent major improvement in Recurrent Neural Networks gave rise to the popularity of LSTMs (Long Short Term Memory RNNs) which has completely changed the playing field. In this part, we will learn how to implement this ultra-powerful model, and we will take the challenge to use it to predict the real Google stock price. A similar challenge has already been faced by researchers at Stanford University and we will aim to do at least as good as them.</p><p><strong>Dataset sample:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/385/1*D4tiCwPQOQbxanQpQLT0Sw.png" /></figure><p>Let’s solve the problem</p><p><strong>Part 1: Data Preprocessing</strong></p><p><strong><em>1.1 Import the Libraries:</em></strong></p><p>In this step, we import three Libraries in Data Preprocessing part. Basically, Library is a tool that you can ua specific job. First of all, we import the <strong>numpy</strong> library used for multidimensional array then import the <strong>pandas </strong>library<strong> </strong>used to import the dataset and in last we import <strong>matplotlib </strong>library used for plotting the graph.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/381/1*GY73oS0F_Nn_x3RSqg3cnA.png" /></figure><p><strong><em>1.2 Import the dataset</em></strong></p><p>In this step, we import the dataset to do that we use the <strong>pandas</strong> library. After import, our dataset and we take only one attribute of Google stock price prediction which is open Google stock price which we want to predict.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*95f64D9jf71pCu6-k0xGbg.png" /></figure><p><strong><em>1.3 Feature Scaling</em></strong></p><p>Feature Scaling is the most important part of data preprocessing. If we see our dataset then some attribute contains information in Numeric value some value very high and some are very low if we see the age and estimated salary. This will cause some issues in our machinery model to solve that problem we set all values on the same scale there are two methods to solve that problem first one is Normalize and Second is Standard Scaler.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*wuCX1bjSh6YXcu8tuA5wyw.png" /></figure><p>Here we use Normalize Scalar because in Google Stock Price Prediction we build the LSTM model which has several sigmoid functions (which is 0 or 1) that are why we choose Normalize Scalar here.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/551/1*MUzWnUVKzskquUMKj0CvPw.png" /></figure><p><strong><em>1.4 Getting the Input and Output</em></strong></p><p>In this step, we create our input and output from training data. Here X_train is our input which is <strong>t</strong> and Y_train is our output which is <strong>t+1</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/381/1*JuurKMMgiW59Ddw2rT7FpA.png" /></figure><p><strong><em>1.5 Reshaping</em></strong></p><p>In this step, we reshape our input. Why I Reshape here Because our input shape have 2 dimension one dimension corresponds to observation and second correspond to feature which has only one feature here and we convert our input into three-dimension last 1 corresponds to a timestamp because our input is t and output is t+1. So t+1-t= 1 that’s why 1 here. So here 1257 is observation, 1 is time step, 1 is feature scaling.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/518/1*u6S_F65EIyjn1wDVnqBlIg.png" /></figure><p><strong>Part 2: Building our Model</strong></p><p>In this part, we model our Recurrent Neural Network model.</p><p><strong><em>2.1 Import the Libraries</em></strong></p><p>In this step, we import the Library which will build our RNN model. We import <strong>Keras</strong> Library which will build a deep neural network based on Tensorflow because we use Tensorflow backhand. Here we import the three modules from Keras. The first one is <strong>Sequential </strong>used for initializing our RNN model and second is <strong>Dense </strong>used for adding different layers of RNN and third is <strong>LSTM</strong> which we use in the RNN model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/533/1*OQN_uKEjSl3TAbl54Enrbw.png" /></figure><p><strong><em>2.2 Initialize our RNN model</em></strong></p><p>In this step, we initialize our Recurrent Neural Network model to do that we use sequential modules.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/1*Ol4eDeoZG0Uvq9QxdkklhA.png" /></figure><p><strong><em>2.3 Adding the input layer and LSTM layer</em></strong></p><p>In this step, we add the LSTM layer and the input. Here we pass several parameters pass here first is <strong>unit=4</strong> which corresponds to number ofry unit I choose 4 here second is <strong>activation = sigmoid</strong> which is activation function I choose both tanh &amp; sigmoid but I choose sigmoid activation here and the third parameter is <strong>input shape</strong> and in input shape I pass 2 arguments here 1 for timestep and 1 for feature.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*iqrxSoIh_5TU0EborhPV1w.png" /></figure><p><strong><em>2.4 Adding the output layer</em></strong></p><p>In this step, we add the output layer to do we use Dense class here. Here in output, we pass only one argument here which is<strong> unit </strong>corresponds to the number of neurons in the output layer that corresponds to the dimension of outcome since the outcome is stock price t+1 so the outcome has 1 dimension there we need put here units=1 stock price t+1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/380/1*i0CoaOgILtdIihHZ8DgocQ.png" /></figure><p><strong><em>2.5 Compiling the RNN</em></strong></p><p>In this step, we compile the RNN to do that we use the compile method and add several parameters the first parameter is <strong>optimizer = Adam</strong> here use the optimal number of weights. So for choosing the optimal number of weights, there are various algorithms of Stochastic Gradient Descent but very efficient one which is Adam<strong> </strong>so that’s why we use Adam optimizer here. The second parameter is loss this corresponds to loss function here we use the <strong>mean_squared_error </strong>because the dataset is regression value so that why we loss function means square error here. It’s basically the sum of the squared distance between youd stock price and the real stock price.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*3M_w3WUNkiU3pk4gxHehaA.png" /></figure><p><strong><em>2.6 Fitting the RNN to the Training set</em></strong></p><p>In this step we fit the training data our model X_train, y_train is our training data. Here a <strong>batch size</strong> is basically a number of observations after which you wanseveralts here we take batch size 32. And the final parameter is <strong>epoch </strong>is basically when whole the training set passed through the RNN here we choose the 200 number of the epoch.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*jwtxpU5skhUpnT10-hlz7Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*CUpeFgQtHpIRcA-cwdupDA.png" /></figure><p><strong>Part 3: Making the Prediction and Visualize the Result.</strong></p><p>In this step, we make a prediction of our test set of Google Stock Price and then visualize the result.</p><p><strong><em>3.1 Import the test set dataset of Google Stock Price</em></strong></p><p>In this step, we import our test set dataset of Google stock price.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*4zM_nf-SAphISnY8_mHosQ.png" /></figure><p><strong><em>3.2 Getting the Predicted Stock Price of 2017</em></strong></p><p>First, we need input as we have already done in part 1</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/321/1*JzUm8X8CxpFuhrmbZSGEKg.png" /></figure><p>Then Scale our value as we have already done in part 1</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/348/1*1BNmD5Ix7SwE_glxOwE5-g.png" /></figure><p>Then Reshape as we have already done in part 1</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/476/1*eTh12kG9caiIv8E0UY0JwA.png" /></figure><p>Now predicted our test set result uses the regressor model which we already train in part 2.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/579/1*-oaOn-0IM8VFMy-CNpBvAA.png" /></figure><p>The predicted result is scale value now we convert these values into original values using the inverse method.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*Mvqj_zQ2UQ5Upvtf6a-agg.png" /></figure><p><strong><em>3.3 Visualize the Result</em></strong></p><p>In this step, we compare our predicted results with real stock prices. As you can see below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*fbW18i05w9eQ3IE8Ab9t6w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*9cdLbidDfrqETJxE_Qp8_w.png" /></figure><p>If you want dataset and code you also check my <a href="https://github.com/AmirAli5/Deep-Learning"><strong>Github</strong></a> Profile.</p><h3>End Notes</h3><p>If you liked this article, be sure to click ❤ below to recommend it and if you have any questions, <strong>leave a comment</strong> and I will do my best to answer.</p><p>For being more aware of the world of machine learning, <a href="https://amiraliryk1.wixsite.com/portfolio"><strong>follow me</strong></a>. It’s the best way to find out when I write more articles like this.</p><p>You can also follow me on <a href="https://github.com/AmirAli5"><strong>Github</strong></a> for code &amp; dataset follow on <a href="https://uet.academia.edu/AliAmir"><strong>Aacademia.edu</strong></a> for this article, <a href="https://twitter.com/amir_ali_cheema"><strong>Twitter</strong></a><strong> </strong>and<strong> </strong><a href="http://amirali.cheema@outlook.com/"><strong>Email </strong></a>me directly or find me on<strong> </strong><a href="https://www.linkedin.com/in/amiralicheema/"><strong>LinkedIn</strong>.</a> I’d love to hear from you.</p><p>That’s all folks, Have a nice day :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e6f69db16eba" width="1" height="1" alt=""><hr><p><a href="https://medium.com/machine-learning-researcher/recurrent-neural-network-rnn-e6f69db16eba">Recurrent Neural Network (RNN)</a> was originally published in <a href="https://medium.com/machine-learning-researcher">Aorb Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Convlutional Neural Network(CNN)]]></title>
            <link>https://medium.com/machine-learning-researcher/convlutional-neural-network-cnn-2fc4faa7bb63?source=rss----32a2162bf0c7---4</link>
            <guid isPermaLink="false">https://medium.com/p/2fc4faa7bb63</guid>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[image-processing]]></category>
            <category><![CDATA[image-recognition]]></category>
            <category><![CDATA[convolutional-neural-net]]></category>
            <dc:creator><![CDATA[Amir Ali]]></dc:creator>
            <pubDate>Wed, 22 May 2019 05:46:28 GMT</pubDate>
            <atom:updated>2019-12-07T03:37:08.033Z</atom:updated>
            <content:encoded><![CDATA[<h3>Convolutional Neural Network(CNN) with Practical Implementation</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*_zO929D0Sz7VQJoL4uRDeA.png" /></figure><p>In this Third Chapter of Deep Learning book, we will discuss the Convolutional Neural Network. It is a Supervised Deep Learning technique and we will discuss both theoretical and Practical Implementation from Scratch.</p><p><strong>This chapter spans 4 parts:</strong></p><ol><li>What is Convolutional Neural Network?</li><li>Structure of Convolutional Neural Network.</li><li>How Convolutional Neural Network works?</li><li>Practical Implementation of Convolutional Neural Network.</li></ol><h3>1. What are Convolutional Neural Networks?</h3><h4>1.1: Introduction</h4><p>Convolutional neural networks. Sounds like a weird combination of biology and math with a little CS sprinkled in, but these networks have been some of the most influential innovations in the field of computer vision. 2012 was the first year that neural nets grew to prominence as Alex Krizhevsky used them to win that year’s ImageNet competition (basically, the annual Olympics of computer vision), dropping the classification error record from 26% to 15%, an astounding improvement at the time. Ever since then, a host of companies have been using deep learning at the core of their services. Facebook uses neural nets for their automatic tagging algorithms, Google for their photo search, Amazon for their product recommendations, Pinterest for their home feed personalization, and Instagram for their search infrastructure.</p><h4>1.2: The Problem Space</h4><p>Image classification is the task of taking an input image and outputting a class (a cat, dog, etc) or a probability of classes that best describes the image. For humans, this task of recognition is one of the first skills we learn from the moment we are born and is one that comes naturally and effortlessly as adults. Without even thinking twice, we’re able to quickly and seamlessly identify the environment we are in as well as the objects that surround us. When we see an image or just when we look at the world around us, most of the time we can immediately characterize the scene and give each object a label, all without even consciously noticing. These skills of being able to quickly recognize patterns, generalize from prior knowledge, and adapt to different image environments are ones that we do not share with our fellow machines.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/615/1*yP7Dr8h2zsqItn00Fpw23w.png" /></figure><h4>1.3: Input and Output</h4><p>When a computer sees an image (takes an image as input), it will see an array of pixel values. Depending on the resolution and size of the image, it will see a 32 x 32 x 3 array of numbers (The 3 refers to RGB values). Just to drive home the point, let’s say we have a color image in JPG form and its size is 480 x 480. The representative array will be 480 x 480 x 3. Each of these numbers is given a value from 0 to 255 which describes the pixel intensity at that point. These numbers, while meaningless to us when we perform image classification, are the only inputs available to the computer. The idea is that you give the computer this array of numbers and it will output numbers that describe the probability of the image being a certain class (.80 for a cat, .15 for a dog, .05 for a bird, etc).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*_2VW10xgiZsjD1zslSGR-w.png" /></figure><h4>1.4: What we want to computer Do.</h4><p>Now that we know the problem as well as the inputs and outputs, let’s think about how to approach this. What we want the computer to do is to be able to differentiate between all the images it’s given and figure out the unique features that make a dog a dog or that make a cat a cat. This is the process that goes on in our minds subconsciously as well. When we look at a picture of a dog, we can classify it as such if the picture has identifiable features such as paws or 4 legs. Similarly, the computer can perform image classification by looking for low-level features such as edges and curves and then building up to more abstract concepts through a series of convolutional layers. This is a general overview of what CNN does. Let’s get into the specifics.</p><h4>1.5: Biological Connection.</h4><p>But first, a little background. When you first heard of the term convolutional neural networks, you may have thought of something related to neuroscience or biology, and you would be right. Sort of. CNNs do take a biological inspiration from the visual cortex. The visual cortex has small regions of cells that are sensitive to specific regions of the visual field. This idea was expanded upon by a fascinating experiment by Hubel and Wiesel in 1962 where they showed that some individual neuronal cells in the brain responded (or fired) only in the presence of edges of a certain orientation. For example, some neurons fired when exposed to vertical edges and some when shown horizontal or diagonal edges. Hubel and Wiesel found out that all of these neurons were organized in a columnar architecture and that together, they were able to produce visual perception. This idea of specialized components inside of a system having specific tasks (the neuronal cells in the visual cortex looking for specific characteristics) is one that machines use as well and is the basis behind CNNs.</p><h3>2. Structure of Convolutional Neural Network.</h3><p>A more detailed overview of what CNNs do would be that you take the image, pass it through a series of convolutional, nonlinear, pooling (downsampling), and fully connected layers, and get an output. As we said earlier, the output can be a single class or a probability of classes that best describes the image. Now, the hard part understands what each of these layers does. So let’s get into the most important one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/329/1*XFLitGL4Q54PjXqx2pFztg.png" /></figure><h4>2.1: Convolutional</h4><p>ConvNets derive their name from the “Convolution Operation”. The Convolution in case of ConvNet is to extract features from the input images. Convolution preserves the spatial relationships between pixels by learning image features using Small Square of input data. As we discussed above, every image can be considered as a matrix of the pixel value. Consider a 5*5 image whose pixel values are only 0 &amp; 1 (note that for a grayscale image, pixel values range from 0 to 255, where pixel values are only 0 &amp; 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*PcJg9NP-H9C9A6vUDWAbqg.png" /></figure><p>Similarly, Feature Detector Detect the Every single part of the input image and then result from the show in Feature map which base on the match of feature Detector of the input image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*g6OUIapsfPttD1eUzDgGBg.png" /></figure><p>CNN terminology, the 3×3 matrix is called a ‘filter’ or ‘kernel’ or ‘feature detector’ and the matrix formed by sliding the filter over the image and computing the dot product is called the ‘Convolved Feature’ or ‘Activation Map’ or the ‘Feature Map’. It is important to note that filters act as feature detectors from the original input image.</p><p><strong>Depth:</strong></p><p>Depth corresponds to the number of filters we use for the convolution operation. In the network shown in Figure below, we are performing the convolution of the original boat image using three distinct filters, thus producing three different feature maps as shown. You can think of these three feature maps as stacked 2d matrices, so, the ‘depth’ of the feature map would be three. The more numbers of filters the more accurate result.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/474/1*Swl_X8TPR-Eryk-atXPLqg.png" /></figure><p><strong>Stride:</strong></p><p>Stride is the number of pixels by which we slide our filter matrix over the input matrix. When the stride is 1 then we move the filters one pixel at a time. When the stride is 2, then the filters jump 2 pixels at a time as we slide them around. Having a larger stride will produce smaller feature maps.</p><p><strong>Zero-Padding:</strong></p><p>Sometimes, it is convenient to pad the input matrix with zeros around the border, so that we can apply the filter to bordering elements of our input image matrix. A nice feature of zero paddings is that it allows us to control the size of the feature maps. Adding zero-padding is also called <em>wide convolution</em><strong>,</strong> and not using zero-padding would be a<em> narrow convolution</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/443/1*4oxIRZfPlq2S7C8mxhO7cw.png" /></figure><p>Input = output</p><p>That’s the benefits of padding</p><p>Padding &gt;&gt;&gt; valid &gt;&gt;&gt; no padding</p><p>Padding &gt;&gt;&gt; same &gt;&gt;&gt; padding to make output size same as input size.</p><h4>2.1a: ReLu Layer</h4><p>An additional operation called ReLU has been used after every Convolution operation. ReLU stands for the Rectified Linear Unit and is a non-linear operation. Its output is given by:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/570/1*CihszfNPolBhzUgjBUUx1Q.png" /></figure><p>ReLU is an element-wise operation (applied per pixel) and replaces all negative pixel values in the feature map by zero. The purpose of ReLU is to introduce non-linearity in our ConvNet since most of the real-world data we would want our ConvNet to learn would be non-linear (Convolution is a linear operation — element-wise matrix multiplication and addition, so we account for non-linearity by introducing a non-linear function like ReLU).</p><p>As shown below image we apply the Relu operation and he replaces all the negative numbers by 0.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*hw4MvdJhQeFiibIqhrKu-g.png" /></figure><h4>2.2: Max Pooling</h4><p>Spatial Pooling (also called subsampling or downsampling) reduces the dimensionality of each feature map but retains the most important information. Spatial Pooling can be of different types: Max, Average, Sum, etc.</p><p>In the case of Max Pooling, we define a spatial neighborhood (for example, a 2×2 window) and take the largest element from the rectified feature map within that window. Instead of taking the largest element we could also take the average (Average Pooling) or sum of all elements in that window. In practice, Max Pooling has been shown to work better.</p><p>Below shows an example of Max Pooling operation on a Rectified Feature map (obtained after convolution + ReLU operation) by using a 2×2 window.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/603/1*XVDBlU_vUvOiiN7kU1D6Dw.png" /></figure><h4>2.3: Flattening</h4><p>Flattening is the process of converting al the resultant 2-dimensional arrays into a single long continuous linear vector.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*oJSpK_KcHUTIZxniOQ_vOQ.png" /></figure><p>The process of building a CNN involves four major steps</p><ol><li>Convolution</li><li>Pooling</li><li>Flattening</li><li>Full Connection</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*dhkXm1iLCin_z113GPmM8A.png" /></figure><p>So Flattening is become the input of Artificial Neural Network which is used for the backpropagation Method.</p><h4>2.4: Full Connection</h4><p>The Fully Connected layer is a traditional Multi-Layer Perceptron that uses a softmax activation function in the output layer (other classifiers like SVM can also be used, but will stick to softmax in this post). The term “Fully Connected” implies that every neuron in the previous layer is connected to every neuron on the next layer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/459/1*G9-eByAaBLfm2_nmJllRkA.png" /></figure><p>The output from the convolutional and pooling layers represent high-level features of the input image. The purpose of the Fully Connected layer is to use these features for classifying the input image into various classes based on the training dataset. For example, the image classification task we set out to perform has four possible outputs as shown in <strong>Figure</strong> below (note that Figure 14 does not show connections between the nodes in the fully connected layer)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/446/1*U-299RSgUwcTxCLvXjsCpg.png" /></figure><p>Apart from classification, adding a fully-connected layer is also a (usually) cheap way of learning non-linear combinations of these features. Most of the features from convolutional and pooling layers may be good for the classification task, but combinations of those features might be even better. The sum of output probabilities from the Fully Connected Layer is 1. This is ensured by using the Softmax as the activation function in the output layer of the Fully Connected Layer. The Softmax function takes a vector of arbitrary real-valued scores and squashes it to a vector of values between zero and one that sums to one.</p><h4>2.5: Putting it all together Training using Backpropagation</h4><p>As discussed above the convolution + Pooling layers act as Features extractor from the input image while a fully connected layer acts as the classifier.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*-Bo5d1RCDWu9MeHluC5hfw.png" /></figure><p>Note that in <strong>Figure </strong>below, since the input image is a boat, the target probability is 1 for Boat class and 0 for the other three classes, i.e.</p><p>Input Image = Boat</p><p>Target Vector = [0, 0, 1, 0]</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/1*7917Eybhw-WSmc9jzoIzew.png" /></figure><p><strong>The overall training process of the Convolution Network may be summarized as below:</strong></p><p><strong>Step1:</strong> We initialize all filters and parameters/weights with random values.</p><p><strong>Step2: </strong>The network takes a training image as input, goes through the forward propagation step (convolution, ReLU, and pooling operations along with forwarding propagation in the Fully Connected layer) and finds the output probabilities for each class.</p><p>Let’s say the output probabilities for the boat image above are [0.2, 0.4, 0.1, 0.3]</p><p>Since weights are randomly assigned for the first training example, output probabilities are also random.</p><p><strong>Step3:</strong> Calculate the total error at the output layer (summation over all 4 classes)</p><p>Total Error = ∑ ½ (target probability — output probability) ²</p><p><strong>Step4:</strong> Use Backpropagation to calculate the <em>gradients</em> of the error concerning all weights in the network and use <em>gradient descent</em> to update all filter values/weights and parameter values to minimize the output error.</p><p>The weights are adjusted in proportion to their contribution to the total error.</p><p>When the same image is input again, output probabilities might now be [0.1, 0.1, 0.7, 0.1], which is closer to the target vector [0, 0, 1, 0].</p><p>This means that the network has <em>learn</em>ed to classify this particular image correctly by adjusting its weights/filters such that the output error is reduced.</p><p>Parameters like the number of filters, filter sizes, the architecture of the network, etc. have all been fixed before Step 1 and do not change during the training process — only the values of the filter matrix and connection weights get updated.</p><p><strong>Step5:</strong> Repeat steps 2–4 with all images in the training set.</p><h3>3: How Convolutional Neural Network Works?</h3><p><strong>Approach</strong></p><ul><li>Build a small convolutional neural network as defined in the architecture below.</li><li>Select images to train the convolutional neural network.</li><li>Extraction of feature filters/feature maps.</li><li>Implementation of the convolutional layer.</li><li>Apply the ReLu Activation function on the convolutional layer to convert all negative values to zero.</li><li>Then apply max pooling on convolutional layers.</li><li>Make a fully connected layer</li><li>Then input an image into CNN to predict the image content</li><li>Backpropagation to calculate the error rate</li></ul><p><strong>Selection of Image</strong></p><p>Let’s take an image of the alphabet “X” and “O”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/626/1*_RwuCMmfKr5zGWY2S3D0sg.png" /></figure><p><strong>Train the Convolutional Neural Network For Image X</strong></p><p><strong>Feature Filters extraction from image X</strong></p><p>In convolutional networks, you look at an image through a smaller window and move that window to the right and down. That way you can find features in that window, for example, a horizontal line or a vertical line or a curve, etc… What exactly a convolutional neural network considers an important feature is defined while learning.</p><p>Wherever you find those features, you report that in the feature maps. A certain combination of features in a certain area can signal a larger, more complex feature exists there.</p><p>For example, your first feature map could look for curves. The next feature map could look at a combination of curves that build circles.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/524/1*GcmvCXwWroLOElD8SbUvaA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/506/1*2_WfdxnLtkctJN0X10WPmA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/538/1*1LuvGKC5rMJEV_mBLUzNEw.png" /></figure><h4>3.1 Convolutional Layers</h4><p><strong>3.1.1 Convolutional Layer 1 (Image X with filter 1)</strong></p><p>In CNN convolutional layer, the 3×3 matrix called the ‘<strong>feature filter’</strong> or ‘kernel’ or ‘feature detector’ sliding over the image and the matrix formed will be the <strong>convolutional layer</strong>. It is important to note that filters act as feature detectors from the original input image. Image X matching with filter # 1 with a <strong>stride</strong> of 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/550/1*d5jso5gIAXOePQftQ8BpaQ.png" /></figure><p>The pixel values of the highlighted matrix will be multiplied with their corresponding pixel values of the filter and then takes the average.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/335/1*ov1Z2tvruJf01iKItWpxHg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/352/1*jCW3EDDr2IstCxUVXOSfVw.png" /></figure><p>Here you will see how the filter shifts on pixels with a stride of 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/582/1*lcFZqij1OGA5erh7JSNjfA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/425/1*AKNRxan9IeaAo6wjQzZEdQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/527/1*9gIaUNx79F3E9-wjX9zA9A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/239/1*GpkkfibDm0tR0bYp8eoYfg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/354/1*gYOYnsQmm9JREeWXRbHLKg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/517/1*t7WgQz2ErR_IpNdTxKyc-A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/372/1*xf4v5I6hpnKCIb6jEogPng.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/1*7sVPyeT6H9mIDlye4y1UKw.png" /></figure><p>similarly so on</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/462/1*SRI5bbKdENp_d63gqXvj7w.png" /></figure><p>= 0.77</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/468/1*Yd6zCQBQMM7w5Mjkr1A4Sg.png" /></figure><p><strong>3.1.2 Convolutional Layer 2 (Image X with filter 2)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/1*1nwSZr-6THdGgeVzJEnQHg.png" /></figure><p>After repeating the same steps (As we did for filter 1) of the convolutional layer on image “X” with filter 2, we get</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/478/1*1HSAWtGwtycVFsBBUOJrGg.png" /></figure><p><strong>3.1.3 Convolutional Layer 3 (Image X with filter 3)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/291/1*a7deqt4MY6nZdBJ1J21Weg.png" /></figure><p>After repeating the same steps of the convolutional layer on image “X” with filter 3, we get</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/365/1*8rtlV1tXzVOBR8xMGGkAxg.png" /></figure><h4>3.2 RELU Layer:</h4><p>Apply ReLu Activation Function on Convolutional layers:</p><p>Convert all negative values to zero</p><p><strong>3.2.1 Relu layer For Convolutional Layer 1:</strong></p><p>Apply ReLu activation Function on Convolutional Layer 1 to convert all the negative values to zero</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/356/1*VGttrEMNRR3RpKfU0li1dw.png" /></figure><p><strong>3.2.2 Relu layer Convolutional Layer 2:</strong></p><p>Apply ReLu activation Function on Convolutional Layer 2 to convert all the negative values to zero</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/353/1*WUIiuloB8JVMvXFSnXHWpg.png" /></figure><p><strong>3.2.2 Relu layer Convolutional Layer 3:</strong></p><p>Apply ReLu activation Function on Convolutional Layer 3 to convert all the negative values to zero</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/334/1*Oz7TSBWSGY2urd7ztWXJew.png" /></figure><h4>3.3 Max Pooling:</h4><p>After applying the Convolutional &amp; Relu layer respectively Now we apply the Max pooling for convolutional layers 1, 2 &amp; 3 and extract maximum feature from the image.</p><p><strong>3.3.1 Max pooling For Convolutional Layer 1</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/1*72IgyA0l97WWYjvMkNQubg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/645/1*Jynb4GJzIxmfEgvnjpj3yA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/633/1*y8oaeKo1l4XBTejaUuJ52A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/584/1*40UE5jAdXDINBzJS-7T_ig.png" /></figure><p>similarly so on</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/628/1*AXcEh7_GwUkLf9xd-cn4Gg.png" /></figure><p><strong>3.3.2 Max pooling For Convolutional Layer 2</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/354/1*ecO26CcYGCtHyb0Nhocc7Q.png" /></figure><p>Repeat the same steps of max pooling for convolutional layer 2, we get</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/228/1*L6XPGfdUa0D3RrfMjnhmgQ.png" /></figure><p><strong>3.3.3 Max pooling For Convolutional Layer 3</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/353/1*t8x-DUIlEjf6rnVcjAY9kQ.png" /></figure><p>Repeat the same steps of max pooling for convolutional layer 3, we get</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/203/1*MoqMzlau9ZcvZI1qkmiZjA.png" /></figure><h4>3.4 Further Max Pooling:</h4><p>Further Max Pooling for use in fully connected layer</p><h4>3.4.1 Further Max pooling for convolutional layer 1</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/443/1*uLTlmZgepd6E8PbTvn-Cag.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/458/1*-KRmAMDG5TE_DYFV2K4zhA.png" /></figure><p><strong>3.4.2 Further Max pooling for convolutional layer 2</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/542/1*_OwhuHD_c4uBfw7K0CqAmA.png" /></figure><p><strong>3.4.3 Further Max pooling for convolutional layer 3</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/562/1*rZNs8QAQT-s1_gLdzqZnag.png" /></figure><h4>3.5 Flattening:</h4><p>In this step, we converting all the resultant 2-dimensional arrays into a single long continuous linear vector.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/452/1*4jQdnOnc8Ev4PX8Ba2lVCw.png" /></figure><p>Now, these single long continuous linear vectors are input nodes of our full connection layer.</p><h4>3.6 Fully Connected Layer ( for X ):</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/169/1*2FKuPrSuUfplelqj7vL9JQ.png" /></figure><p>White cells are votes depends on how strongly a value can predict “X”</p><p>These are the input node so after that we doing backpropagation. For backpropagation, you can see <a href="https://medium.com/machine-learning-researcher/artificial-neural-network-ann-4481fa33d85a"><strong>chapter 2</strong></a> which we explain backpropagation in details (we not going backpropagation here because we already have done in chapter 2)</p><p><strong>Train the Convolutional Neural Network For Image ‘O’</strong></p><p><strong>Feature Filters extraction from image ‘O’</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/318/1*9eViGZTb6_mZvngaBoKTvw.png" /></figure><p>After repeating the procedure of training the convolutional neural network the same as we had done for training image X, we get</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/311/1*2kcE4N8l9qbThMBnbvgDNA.png" /></figure><p>White cells are votes depends on how strongly a value can predict “O”</p><p><strong>Prediction Example</strong></p><p>We feed an image into the convolutional neural network and we don’t know whether it is X or O.</p><p>Now we get new input and we don’t know what it is and want to decide the way this works is the input goes through all of our convolutional our rectified linear unit and pooling layer and at the end we get,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/274/1*oc9eh1EZsWUX86EhX8r6jg.png" /></figure><p><strong>Now calculate predictions for X</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/302/1*ciIsnzn4BhtGI9lF9drHgw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/231/1*CBcAwhuAvHf4TGxui3G4Wg.png" /></figure><p>So our CNN predicts the input image as X with a prediction rate of 91 percent</p><p><strong>Now calculate a prediction for O Image</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/297/1*U8afsDGahbBkqPGZZjR5Lw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/239/1*pasReoPU3VakNrTGU4k9uA.png" /></figure><p>So our CNN predicts the input image as O with a prediction rate of 51 percent</p><p>As</p><p>Prediction rate for X &gt; Prediction rate of O</p><p>91 &gt; 51</p><p>So,</p><p>The image we input for prediction into our convolutional neural network is X</p><p><strong>Note</strong>: If you want this article check out my <a href="https://www.academia.edu/41197398/A_Briefly_Explanation_of_Convolutional_Neural_Network_with_Practical_Implementation_in_Keras_and_Tensorflow"><strong>academia.edu</strong></a> profile.</p><h3>5: Practical Implementation of Convolutional Neural Network.</h3><h4>Image Recognition (Cat &amp; Dog dataset)</h4><p>In this part, we will create a Convolutional Neural Network that can detect various objects in images. We will implement this Deep Learning model to recognize a cat or a dog in a set of pictures. However, this model can be reused to detect anything else and we will show you how to do it — by simply changing the pictures in the input folder.</p><p>For example, you will be able to train the same model on a set of brain images, to detect if they contain a tumor or not. But if you want to keep it fitted to cats and dogs, then you will be able to take a picture of your cat or your dog, and your model will predict which pet you have.</p><p><strong>Dataset sample:</strong></p><p>The dataset contains 10000 images of cats and dogs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/623/1*SD7Nh-cppIVk1UJXIRxAbQ.png" /></figure><p><strong>Part 1: Building the CNN model</strong></p><p><strong><em>1.1 Import the Libraries:</em></strong></p><p>In this step, we import Keras library and packages for building the Convolutional Neural Network model. First, we import <strong>the Sequential</strong> module which is used for initializing our model. Second is <strong>Convolutiona2D</strong> is the package that we’ll use for the first step of making the CNN that is the convolution step in which we add convolutional layers So here we are working with images which are only 2 dimensions there we use convolution2D( incase of video we use 3D). Then the next package is <strong>MaxPooling2D</strong> that’s a package that we’ll use to proceed to step to the pooling step that will add our pooling layers. The next package is <strong>Flatten </strong>this is the package that we will use in step 3 flattening in which we convert all the pooled feature maps that we created through convolution and max-pooling into the large feature vector that is then becoming the input of our fully connected layers. And then finally the last package which <strong>Dense</strong> package this is the package we use to add the fully connected layer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/545/1*sQm2XKM4T4a-ZqqlOdfRnw.png" /></figure><p><strong><em>1.2 Initialize our model:</em></strong></p><p>In this step, we initialize our Convolutional Neural Network model to do that we use sequential modules.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/573/1*ypV-EzPAEuFV1TlDUTwDIw.png" /></figure><p><strong><em>1.3 Convolution Step:</em></strong></p><p>In this step, we add a convolution step and this is the first step of CNN. Here in Convolution2D, we pass several arguments in this module. First arguments which we pass here <strong>feature detector </strong>(32, 3, 3) that’s mean we create 32 feature detectors of three by three dimensions and therefore our convolutional layers composed of 32 feature maps. Next arguments are <strong>input shape </strong>that’s the shape of input image on which we are going to apply feature detectors through the convolution operation in this arguments we convert all images into same formats here 64 and 64 are dimension and 3 is number of channels because we are working with colored images that’s why we use 3 number channels correspond to RGB ( incase of black &amp; white image we use 1 number of channel). And the last argument which we pass here is <strong>relu </strong>activation function the relu function is used to replace the negate pixel value by 0(As we understand in mathematical part of CNN intuition)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*oefR7GwZbqb3TxTYo5xhWw.png" /></figure><p><strong><em>1.4 Pooling Step:</em></strong></p><p>In this step, we add the pooling layer of our CNN model pooling layer is reducing the size of the feature map( the size of the feature map is divided by 2 when we apply the pooling layer). Here we passed only one argument which is <strong>pool size </strong>and define 2 by 2 dimension because we don’t want to lose any information about the image there we take the minimum size of the pool.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/553/1*4Wpe7QZYwe86BKl-Pf-3-A.png" /></figure><p><strong><em>1.5 Add a second convolution layer and pooling layer:</em></strong></p><p>In this step, we add a second convolution layer and pooling layer to make a mode more efficient and produce some good accuracy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*38p2ua-G0CoUd81tqPX0eg.png" /></figure><p><strong><em>1.6 Flatten Step:</em></strong></p><p>In this step, we convert Max pooling 2D into a single long continuous linear vector to make an input node of fully connected layers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/304/1*9Q3-UBFA0GDV_YnCbwWTTQ.png" /></figure><p><strong><em>1.7 Full Connection layer:</em></strong></p><p>In this step, we use the Dense model to add a different layer. The parameter which we pass here first is ouptu_dim=6 which defines hidden layer=128 and last arguments Third is activation= relu here in hidden layer we use relu activation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*WsRVzt5YlyAtccH9ejs_VQ.png" /></figure><p>After adding a Hidden layer we add an output layer in full connection layer out_dim= 1 which means one output node here we use the sigmoid function because our target attribute has a binary class which is cat or dog that’s why we use sigmoid activation function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*3t6hK-5lZSusZrZDwOfCFg.png" /></figure><p><strong><em>1.8 Compiling the CNN</em></strong></p><p>In this step we compile the CNN to do that we use the compile method and add several parameters the first parameter is <strong>optimizer = Adam</strong> here use the optimal number of weights. So for choosing the optimal number of weights, there are various algorithms of Stochastic Gradient Descent but very efficient one which is Adam<strong> </strong>so that’s why we use Adam optimizer here. The second parameter is loss this corresponds to loss function here we use <strong>binary_crossentropy</strong> because if we see target attribute our dataset which contains the binary value that’s why we choose the binary cross-entropy. The final parameter is <strong>metrics</strong> its list of metrics to be evaluated by the model and here we choose the accuracy metrics.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*Hreh4GmHAL3yfFNsWiToGQ.png" /></figure><p><strong>Part 2: Image Preprocessing</strong></p><p><strong><em>2.1 Import the library</em></strong></p><p>First import a class that will allow us to use this image data Generator function. This class called Image Data Generator and we import this class from Keras image preprocessing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*BjoonKQCVOtNvhhlpuSmYw.png" /></figure><p><strong><em>2.2: Image Augmentation</em></strong></p><p><strong><em>2.2.1: Train_datagen</em></strong></p><p>This step is like a data preprocessing which we did chapter 2 ANN but Now we are working with an image that’s why we doing Image Augmentation. Here we pass several arguments first is <strong>rescale </strong>is like a feature scaling which doing in data preprocessing here our image 0 to 255-pixel value and we rescale into 0 &amp; 1. Then next is <strong>Shear_range</strong>( Shear angle in the counter-clockwise direction in degrees) that to apply random transactions and we will keep this 0.2. <strong>zoom_range </strong>that will apply some random zoom and we keep 0.2 value. And then last is <strong>horizontal_flip</strong> Randomly flip inputs horizontally</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/429/1*BGh1CXZZ3_5e_-ctd_xA7g.png" /></figure><p><strong><em>2.2.2: Test_datagen</em></strong></p><p>Same as a train but here only rescale our images.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/582/1*Qh900lVeaK6HAmmdKY3mtg.png" /></figure><p><strong><em>2.3 Training set &amp; Test set</em></strong></p><p>In this step, we import the images that we want to train. Remember our dataset contains 1000 images 8000 for train and 2000 for test and here first we import our images from the working directory that we want to train. Then target size here 64 by 64 that’s expected CNN which we defined earlier in Building the CNN part. Then batch size that the size of batch in which some random sample of our image will be included and that contains the number of images that will go through the CNN after which the weight will be updated. And finally, the class mode that the parameter indicating if your class is dependent variable is binary or has more than two categories and therefore since two-class here cat &amp; dog that’s why class mode is binary here that we use here.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*-NvDugEF6ipzUXdZZs2_rg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*O9HlLnZO9_wQ4K4ZZYrnPQ.png" /></figure><p><strong><em>2.4 Fit the CNN model</em></strong></p><p>First arguments which we pass here is <strong>train set</strong> which contains 8000 images belongs to 2 class second is <strong>stepper epoch</strong> that is the number of the image we in our training set because remember all the observation of the training set pass through CNN during each epoch since we have 8000 images that’s why 8000 here. Then the number of <strong>epoch</strong> you want to choose to train our CNN here we take only 1 because our purpose is just to understand we suggest to take more than 50 for good accuracy. And then <strong>validation data </strong>that correspond to the test set on which we want to evaluate the performance of our CNN. And last are validation steps that correspond to the number of the image in our test set and that is 2000.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*-qydd6EpDulvbwwBcxilpw.png" /></figure><p>Here we go we obtain 80% for the training set and 81% for the test set.</p><p><strong>Part 3: Making a new prediction</strong></p><p><strong><em>3.1 Import the library</em></strong></p><p>In this step, we import libraries the first library which we import here is numpy used for multidimensional array and the second is image package from Keras used for import the image from the working directory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/447/1*siJveVvI82Colk2-lezYLw.png" /></figure><p><strong><em>3.2 Import the Image</em></strong></p><p>In this step, we import our single image we don’t know either is cat image or dog image (like in mathematical part when we train images 0 and X and then make a prediction X). Here we pass two arguments first is image load and second is target size. Here we set target size 64 by 64 as expected our CNN model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*wT4jbS60rDXf-q0owcIB8Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/190/1*Tzat_rQBCUCB5OM_uA8-lA.png" /></figure><p><strong><em>3.3 Set the Dimension of image</em></strong></p><p>In this step, we set the dimension of our image 2D (64, 64) into the 3D array(64, 64, 3) exactly as input shape that’s the architecture of input shape.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*NVZ0IAZ1axMHDhwK8KtNSw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/217/1*QJtNvjZTFtu2dUuEDGqAiA.png" /></figure><p><strong><em>3.4 Set the Dimension of image</em></strong></p><p>We are working with the single image we directly make a prediction then will raise an error which expected convolution 2d input_1 to have 4 dimensions to do that we modify the test image into 4 dimensions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/579/1*0M2vkGzdAZzCSkwuSCzTSw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/248/1*W7DuIFIuDbPzGPetM4bp-A.png" /></figure><p><strong><em>3.5 Make a prediction</em></strong></p><p>In this step, we predict a single image</p><p>So here we go cat corresponds to 0 and dog corresponds to 1 so our image is a dog. Perfect so that’s mean the prediction of our CNN model for the first image of cat &amp; dog is correct because the image contains the dog</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/468/1*qsDl3YfGFVE0QTifdcPOtQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/476/1*GGe41AZKP7zpZq1texKLHQ.png" /></figure><p>So here we go cat corresponds to 0 and dog corresponds to 1 so our image is a dog. Perfect so that’s mean the prediction of our CNN model for the first image of cat &amp; dog is correct because the image contains the dog</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/214/1*CeoU8vbHumxodA5o-yEpHA.png" /></figure><p>If you want dataset and code you also check my <a href="https://github.com/AmirAli5/Deep-Learning"><strong>Github</strong></a> Profile.</p><h3>End Notes</h3><p>If you liked this article, be sure to click ❤ below to recommend it and if you have any questions, <strong>leave a comment</strong> and I will do my best to answer.</p><p>For being more aware of the world of machine learning, <a href="https://amiraliryk1.wixsite.com/portfolio"><strong>follow me</strong></a>. It’s the best way to find out when I write more articles like this.</p><p>You can also follow me on <a href="https://github.com/AmirAli5"><strong>Github</strong></a> for code &amp; dataset follow on <a href="https://uet.academia.edu/AliAmir"><strong>Aacademia.edu</strong></a> for this article, <a href="https://twitter.com/amir_ali_cheema"><strong>Twitter</strong></a><strong> </strong>and<strong> </strong><a href="http://amirali.cheema@outlook.com/"><strong>Email </strong></a>me directly or find me on<strong> </strong><a href="https://www.linkedin.com/in/amiralicheema/"><strong>LinkedIn</strong>.</a> I’d love to hear from you.</p><p>That’s all folks, Have a nice day :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2fc4faa7bb63" width="1" height="1" alt=""><hr><p><a href="https://medium.com/machine-learning-researcher/convlutional-neural-network-cnn-2fc4faa7bb63">Convlutional Neural Network(CNN)</a> was originally published in <a href="https://medium.com/machine-learning-researcher">Aorb Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Artificial Neural Network (ANN)]]></title>
            <link>https://medium.com/machine-learning-researcher/artificial-neural-network-ann-4481fa33d85a?source=rss----32a2162bf0c7---4</link>
            <guid isPermaLink="false">https://medium.com/p/4481fa33d85a</guid>
            <category><![CDATA[backpropagation]]></category>
            <category><![CDATA[multilayer-perceptron]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[artificial-neural-network]]></category>
            <category><![CDATA[neural-networks]]></category>
            <dc:creator><![CDATA[Amir Ali]]></dc:creator>
            <pubDate>Mon, 20 May 2019 08:00:30 GMT</pubDate>
            <atom:updated>2019-12-07T16:57:01.594Z</atom:updated>
            <content:encoded><![CDATA[<h3>Artificial Neural Network (ANN) with Practical Implementation</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*vtJ2n-_l-4D_dAMH3qpOKQ.png" /></figure><p>In this Second Chapter of Deep Learning, we will discuss the Artificial Neural Network. It is a Supervised Deep Learning technique and we will discuss both theoretical and Practical Implementation from Scratch.</p><p><strong>This chapter spans 5 parts:</strong></p><ol><li>What is an Artificial Neural Network?</li><li>Types of Artificial Neural Network.</li><li>Activation Functions and There types?</li><li>How Do Backpropagation works?</li><li>Practical Implementation of ANN in Keras and Tensorflow.</li></ol><h3>1. What is an Artificial Neural Network?</h3><p>Artificial neural networks are one of the main tools used in machine learning. As the “neural” part of their name suggests, they are brain-inspired systems that are intended to replicate the way that we humans learn. Neural networks consist of input and output layers, as well as (in most cases) a hidden layer consisting of units that transform the input into something that the output layer can use. They are excellent tools for finding patterns that are far too complex or numerous for a human programmer to extract and teach the machine to recognize.</p><p>While neural networks (also called “perceptrons”) have been around since the 1940s, it is only in the last several decades where they have become a major part of artificial intelligence. This is due to the arrival of a technique called “backpropagation,” which allows networks to adjust their hidden layers of neurons in situations where the outcome doesn’t match what the creator is hoping for — like a network designed to recognize dogs, which misidentifies a cat, for example.</p><p>Another important advance has been the arrival of deep learning neural networks, in which different layers of a multilayer network extract different features until it can recognize what it is looking for.</p><h4>1.1: Basic Structure of ANNs</h4><p>The idea of ANNs is based on the belief that working of the human brain by making the right connections can be imitated using silicon and wires as living <strong>neurons</strong> and <strong>dendrites</strong>.</p><p>The human brain is composed of 86 billion nerve cells called <strong>neurons.</strong> They are connected to other thousand cells by <strong>Axons.</strong> Stimuli from the external environment or inputs from sensory organs are accepted by dendrites. These inputs create electric impulses, which quickly travel through the neural network. A neuron can then send the message to another neuron to handle the issue or does not send it forward.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/528/1*ImtuSnzhVjvtk8aoQKD92g.png" /></figure><p>ANNs are composed of multiple <strong>nodes</strong>, which imitate biological <strong>neurons</strong> of the human brain. The neurons are connected by links and they interact with each other. The nodes can take input data and perform simple operations on the data. The result of these operations is passed to other neurons. The output at each node is called its <strong>activation</strong> or <strong>node value.</strong></p><p>Each link is associated with <strong>weight.</strong> ANNs are capable of learning, which takes place by altering weight values. The following illustration shows a simple ANN –</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/430/1*WUcH8RFLAoGFacURtonphA.png" /></figure><h3>2. Types of Artificial Neural Networks</h3><p>There are two Artificial Neural Network topologies − <strong>FeedForward</strong> and <strong>Feedback.</strong></p><p><strong>2.1: FeedForward ANN</strong></p><p>In this ANN, the information flow is unidirectional. A unit sends information to another unit from which it does not receive any information. There are no feedback loops. They are used in pattern generation/recognition/classification. They have fixed inputs and outputs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/332/1*7tJuwHIyruu-ZUOBM6A71g.png" /></figure><p><strong>2.2: FeedBack ANN</strong></p><p>Here, feedback loops are allowed. They are used in content-addressable memories.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/1*az3YJ0y3WbbVpv_U7Y0N4A.png" /></figure><h3>3. Activation Functions and There Types?</h3><h4>3.1: What is Activation Function?</h4><p>It’s just a thing function that you use to get the output of the node. It is also known as <strong>Transfer Function</strong>.</p><p><em>Activation functions</em> are really important for an Artificial Neural Network to learn and make sense of something reallocated and Non-linear complex functional mappings between the inputs and response variable. <em>They introduce non-linear properties to our Network</em>. <em>Their main purpose is to convert an input signal of a node in an ANN to an output signal.</em> That output signal now is used as an input in the next layer in the stack.</p><p>Specifically in A-NN we do the sum of products of inputs(<strong>X</strong>) and their corresponding Weights (<strong>W</strong>) and apply an Activation function <strong>f(x)</strong> to it to get the output of that layer and feed it as an input to the next layer.</p><h4>3.2: Types of activation Functions?</h4><p>It is used to determine the output of neural network like yes or no. It maps the resulting values in between 0 to 1 or -1 to 1 etc. (depending upon the function).</p><p><strong>The Activation Functions can be based on 2 types-</strong></p><p>1. Linear Activation Function</p><p>2. Non-linear Activation Functions</p><p><strong>Linear Activation Function</strong></p><p>As you can see the function is a line or linear. Therefore, the output of the functions will not be confined between any range.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/361/1*eIPQSMvZlRVxEK1Q0wwR4Q.png" /><figcaption><strong>Fig: Linear Activation Function</strong></figcaption></figure><p><strong>Equation: </strong>f(x) = x</p><p><strong>Range:</strong> (-infinity to infinity)</p><p>It doesn’t help with the complexity of various parameters of usual data that is fed to the neural networks.</p><h4>Non-linear Activation Function</h4><p>The Nonlinear Activation Functions are the most used activation functions. Nonlinearity helps to makes the graph look something like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/422/1*fS2GEcT6acdgdI5nHcpN4A.png" /><figcaption><strong>Fig: Non-linear Activation Function</strong></figcaption></figure><p>It makes it easy for the model to generalize or adapt to a variety of data and to differentiate between the outputs.</p><p>The main terminologies needed to understand for nonlinear functions are:</p><p><strong>Derivative or Differential: </strong>Change in y-axis w.r.t. change in the x-axis. It is also known as a slope.</p><p><strong>Monotonic function:</strong> A function that is either entirely non-increasing or non-decreasing.</p><p>The Nonlinear Activation Functions are mainly divided on based on <strong>range or curves</strong>-</p><p><strong>Different Types of Activation function in non-Linear</strong></p><p><strong>1. Sigmoid Activation Function</strong></p><p>The Sigmoid Function curve looks like an S-shape.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/458/1*z4Tkg2HbdueeJW9dnbX_GQ.png" /><figcaption>Sigmoid Function</figcaption></figure><p>The main reason why we use the sigmoid function is that it exists between <strong>(0 to 1). </strong>Therefore, it is especially used for models where we have to <strong>predict the probability</strong> as an output. Since the probability of anything exists only between the range of <strong>0 and 1,</strong> sigmoid is the right choice.</p><p>The function is <strong>differentiable</strong>. That means, we can find the slope of the sigmoid curve at any two points.</p><p>The function is <strong>monotonic </strong>but the function’s derivative is not.</p><p>The logistic sigmoid function can cause a neural network to get stuck at the training time.</p><p>The <strong>softmax function</strong> is a more generalized logistic activation function that is used for multiclass classification.</p><p><strong>2. Tanh Activation Function</strong></p><p>tanh is also like logistic sigmoid but better. The range of the tanh function is from (-1 to 1). tanh is also sigmoidal (s-shaped).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/298/1*kAWj5nIwy4RZeamhXrm7ow.png" /><figcaption>tanh</figcaption></figure><p>The advantage is that the negative inputs will be mapped strongly negative and the zero inputs will be mapped near zero in the tanh graph. The function is <strong>differentiable</strong>.</p><p>The function is <strong>monotonic</strong> while its <strong>derivative is not monotonic</strong>.</p><p>The tanh function is mainly used classification between two classes.</p><p>Both tanh and logistic sigmoid activation functions are used in feed-forward nets.</p><p><strong>3. ReLU (Rectified Linear Unit) Activation Function</strong></p><p>The ReLU is the most used activation function in the world right now. Since it is used in almost all the convolutional neural networks or deep learning.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/276/1*s-d5PJ75U9GFDzfZYmvosA.png" /><figcaption>Relu</figcaption></figure><p>As you can see, the ReLU is half rectified (from bottom). f(z) is zero when z is less than zero and f(z) is equal to z when z is above or equal to zero.</p><p><strong>Range: </strong>[ 0 to infinity)</p><p>The function and it is derivative <strong>both are</strong> <strong>monotonic</strong>.</p><p>But the issue is that all the negative values become zero immediately which decreases the ability of the model to fit or train from the data properly. That means any negative input given to the ReLU activation function turns the value into zero immediately in the graph, which in turn affects the resulting graph by not mapping the negative values appropriately.</p><h3>4: How Backpropagation works?</h3><p>Let’s dive into the mathematics part and see the backpropagation working with feedforward and feed backward Neural Network in depth.</p><p><strong>Approach</strong></p><p><strong>Step 1: </strong>Randomly initialize the Weights to a small number close to 0 (but not 0).</p><p><strong>Step 2: </strong>Input the first observation of your dataset in the input layer, each feature in one input node.</p><p><strong>Step 3:</strong> Forward-Propagation: from left to right, the neurons are activated in a way that the impact of each neuron’s activation is limited by the weights. Propagates the activations until getting the predicted result y.</p><p><strong>Step 4: </strong>Compare the predicted result to the actual result. Measure the generated error.</p><p><strong>Step 5: </strong>Back-Propagation: from left to right, the error is back-Propagated. Update the weights according to how much they are responsible for the error. The Learning rate decides how much we update the weights.</p><p><strong>Step 6: </strong>Repeat step 1 to step 5 and updates the weights after each observation.</p><p><strong>Step 7: </strong>When the whole training set passed through the ANN that makes an epoch. Redo more epoch.</p><h4>Architecture</h4><p>1. Build a Feed-Forward neural network with 2 hidden layers. All the layers will have 3 Neurons each.</p><p>2. 1st and 2nd hidden layers will have RELU and sigmoid respectively as activation functions. The final layer will have a Softmax activation function.</p><p>3. Error is calculated using cross-entropy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/628/1*epwoLULMidhXsUSiNsxonQ.png" /></figure><h3>4. How Does Backpropagation work?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/503/1*89CK0eYXfEDr0uZCLMzqaQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/578/1*honwdPc24tIqVdS1oqji9w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/489/1*sD-wvv1Pn1OcAaNjD06H0g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/609/1*zMNbyYpHjxP7rNljOCTcmw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/629/1*q-kRtX2uXLvSa_DcKkVDeQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/683/1*9HjKZiZ6st0K1kMkkpxq9Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/634/1*xiF-HgN8TIvFCAsPOSvzfg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/1*psIa5F1U8OP6OKpM1WtKNA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/465/1*cKKC9XfVRxt5eM9CXGCcrQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/617/1*2-1goYEy5hMwLfdqMufSkQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*p7N0A_JnC0V3W2TUJ5OTIA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/590/1*QMNZG5B04vFuiXpGAlzhqA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/1*xwZhw5aMT6JT9oZADfU_tQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/603/1*kYrsP7ROCO9h-gjzSiwD8g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/599/1*b9naDG7B3Nqwlh3zOMBvew.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/635/1*oquCYPWiTgvrnf1dUTkCvA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/376/1*hfPGmj6y0kv2iHi4jOdz8g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/599/1*_So05fSjXulnARnEzETpSQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/613/1*z2u-pGbGwD8e6gO79CqPzw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/666/1*8M0ntmzsspJjXPSI-IqJCQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/625/1*HH708T_gwjcbDmSjWu-EZw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/673/1*E56rIXzWciaoyPt5UJYRtQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/641/1*l6QmzfIpWU-F5k66ar6BDA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/612/1*SOIfbBJMGy7EMNMbcrY88g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/425/1*ZsCkYy0h09DwT6Hgd8UCiA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/511/1*mHYfYGptJONBwhT0vyU_pg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/1*MwzYGxy35-P04w9KUyC-dA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/590/1*6p3k4V6MOJLay_Pg5Bdplw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/448/1*-WHBHacZPMJOzp7Qmiw_OQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/664/1*B6CWQEV6Om5e3G93mLfBTw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/1*rmsqWlEK4HZZ1aZOzzLPrg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/643/1*43GbaJr_CzWqDIcmDrASLA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/553/1*-mpYZRzbgwHHVI9yCqh47A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/577/1*gFvVbYhvp7IAJScxTn931Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/558/1*2Rtnaw6AduzkJu3HkgUbrA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/583/1*VRC5kzGtruAlQtgB_9edYg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/614/1*8WHGsH6xPjLl-GA7eiDYtA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/633/1*N3-O5gAgEppT4cSuu1WoyQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/636/1*hwJ1dsyOgBSZW4g1hJnYnQ.png" /></figure><p>So Weights are updated in each layer. Again forward pass then recalculates the errors with actual output and then backward pass repeat the step until error is reduced.</p><p>So in these ways backpropagation algorithm work.</p><p><strong>Note</strong>: If you want this article check out my <a href="https://www.academia.edu/41193006/An_Intuitive_Guide_of_Artificial_Neural_Network_with_Practical_Implementation_in_Keras_and_Tensorflow"><strong>academia.edu</strong></a> profile.</p><h3>5. Practical Implementation of Artificial Neural Network?</h3><h4>Churn Modelling Problem</h4><p>In this part, you will be solving a data analytics challenge for a bank. You will be given a dataset with a large sample of the bank’s customers. To make this dataset, the bank gathered information such as customer id, credit score, gender, age, tenure, balance, if the customer is active, has a credit card, etc. During 6 months, the bank observed if these customers left or stayed in the bank.</p><p>Your goal is to make an Artificial Neural Network that can predict, based on geo-demographical and transactional information given above, if any individual customer will leave the bank or stay (customer churn). Besides, you are asked to rank all the customers of the bank, based on their probability of leaving. To do that, you will need to use the right Deep Learning model, one that is based on a probabilistic approach.</p><p>If you succeed in this project, you will create significant added value to the bank. By applying your Deep Learning model the bank may significantly reduce customer churn.</p><p><strong>Dataset sample:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*0Eiu5CfHaRW2MFfFU1_OYA.png" /></figure><p><strong>Part 1: Data Preprocessing</strong></p><p><strong><em>1.1 Import the Libraries</em></strong></p><p>In this step, we import three Libraries in Data Preprocessing part. A library is a tool that you can use to make a specific job. First of all, we import the <strong>numpy</strong> library used for multidimensional array then import the <strong>pandas </strong>library<strong> </strong>used to import the dataset and in last we import <strong>matplotlib </strong>library used for plotting the graph.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/381/1*9qJqMRr-8PHP5X-a01JlZQ.png" /></figure><p><strong><em>1.2 Import the dataset</em></strong></p><p>In this step, we import the dataset to do that we use the <strong>pandas</strong> library. After import our dataset we define our dependent and independent variable. Our independent variables are 1 to 12 attributes as you can see in the sample dataset which we call ‘<strong>X’</strong> and dependent is our last attribute which we call ‘<strong>y</strong>’ here.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/521/1*ANtOyphTGAMrJtAFXWM4lA.png" /></figure><p><strong><em>1.3 Encoding the Categorical data</em></strong></p><p>In this step, we Encode our categorical data. If we see our dataset then Geography &amp; Gender attribute is in Text and we Encode these two attributes in this part use the LabelEncoder and OneHOTEncoder from the Sklearn.processing library.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*lRBg4atAJPbZ9aWu8IOUwA.png" /></figure><p><strong><em>1.4 Split the dataset for test and train</em></strong></p><p>In this step, we split our dataset into a test set and train set and an 80% dataset split for training and the remaining 20% for tests. Our dataset contains 10000 instances so 8000 data we train and 2000 for the test.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*vLr-1eH0ayYKVRe__PyX4g.png" /></figure><p><strong><em>1.5 Feature Scaling</em></strong></p><p>Feature Scaling is the most important part of data preprocessing. If we see our dataset then some attribute contains information in Numeric value some value very high and some are very low if we see the age and estimated salary. This will cause some issues in our machinery model to solve that problem we set all values on the same scale there are two methods to solve that problem first one is Normalize and Second is Standard Scaler.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*wuCX1bjSh6YXcu8tuA5wyw.png" /></figure><p>Here we use standard Scaler import from Sklearn Library.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/478/1*nzphcHHJoA3nw7OUgw9xVw.png" /></figure><p><strong>Part 2: Building our Model</strong></p><p>In this part, we model our Artificial Neural Network model.</p><p><strong><em>2.1 Import the Libraries</em></strong></p><p>In this step, we import the Library which will build our ANN model. We import <strong>Keras</strong> Library which will build a deep neural network based on Tensorflow because we use Tensorflow backhand. Here we import the two modules from Keras. The first one is <strong>Sequential </strong>used for initializing our ANN model and the second is <strong>Dense </strong>used for adding different layers of ANN.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*EOyF486biPCs_Gu07PbctA.png" /></figure><p><strong><em>2.2 Initialize our ANN model</em></strong></p><p>In this step, we initialize our Artificial Neural Network model to do that we use sequential modules.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/359/1*hCbmccjcsrjsebZxjQZUFA.png" /></figure><p><strong><em>2.3 Adding the input layer and first hidden layer</em></strong></p><p>In this step, we use the Dense model to add a different layer. The parameter which we pass here first is output_dim=6 which defines hidden layer=6, the second parameter is init= uniform basically this is a uniform function that randomly initializes the weights which are close to 0 but not 0. The third parameter is activation= relu here in the first hidden layer we use relu activation. And the last parameter which we pass in dense function is input_dim= 11 which means the input node of our Neural Network is 11 because our dataset has 11 attributes that’s why we choose 11 input nodes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*d1vacSPJC2VCTbBp-FDNuQ.png" /></figure><p><strong><em>2.4 Adding the Second Hidden layer</em></strong></p><p>In this step, we add another hidden layer</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*xi-jrlLD_J9BbfBAA8Pe-Q.png" /></figure><p><strong><em>2.5 Adding the output layer</em></strong></p><p>In this step, we add an output layer in our ANN structure output_dim= 1 which means one output node here we use the sigmoid function because our target attribute has a binary class which is one or zero that’s why we use sigmoid activation function.</p><p><strong><em>2.6 Compiling the ANN</em></strong></p><p>In this step, we compile the ANN to do that we use the compile method and add several parameters the first parameter is <strong>optimizer = Adam</strong> here use the optimal number of weights. So for choosing the optimal number of weights, there are various algorithms of Stochastic Gradient Descent but very efficient one which is Adam<strong> </strong>so that’s why we use Adam optimizer here. The second parameter is loss this corresponds to loss function here we use <strong>binary_crossentropy</strong> because if we see target attribute our dataset which contains the binary value that’s why we choose the binary cross-entropy. The final parameter is <strong>metrics</strong> basically It’s a list of metrics to be evaluated by the model and here we choose the accuracy metrics.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*5G9dc_rVawWr9mJ-rAEF3A.png" /></figure><p><strong><em>2.7 Fitting the ANN</em></strong></p><p>In this step we fit the training data our model X_train, y_train is our training data. Here a <strong>batch size</strong> is basically a number of observations after which you want to update the weights here we take batch size 10. And the final parameter is <strong>epoch </strong>is basically when whole the training set passed through the ANN here we choose the 100 number of the epoch.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*YVFbNHYweeKtbwmC5ngl3g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*dh-6Tn_nimvGB61Mv4e-VQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*533Xl_VX7sKxaxqTQe5Ztw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*0OTlKvkUtKvhfQc8sFbVaA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*B8El16zwVnQ67ItX_3tjzw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*8bL7otx78ZnDqxX2o1AFuA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*Lur72K_B6ZP9u-hVs5I6ow.png" /></figure><p><strong>Part 3: Making the Prediction and Accuracy Result.</strong></p><p><strong><em>3.1 Predict the test set Result</em></strong></p><p>In this step, we predict our test set result here our prediction results in probability so we choose 1(customer leave the bank) if the probability is greater than one 0.5 otherwise 0(customer don’t leave the bank).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/398/1*LpkYIP68_TttdD82RjOj4Q.png" /></figure><p><strong><em>3.2 Confusion metrics</em></strong></p><p>In this step we make a confusion metric of our test set result to do that we import confusion matrix from sklearn.metrics then in confusion matrix, we pass two parameters first is y_test which is the actual test set result and second is y_pred which predicted the result.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/508/1*eHAsd0FYfdMGnxibpqwchw.png" /></figure><p><strong><em>3.3 Accuracy Score</em></strong></p><p>In this step, we calculate the accuracy score based on the actual test result and predict test results.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/466/1*q1eJBnqssry7nvIpTYPpSw.png" /></figure><p>So here we go we get 84.05% of our ANN model.</p><p>If you want dataset and code you also check my <a href="https://github.com/AmirAli5/Deep-Learning"><strong>Github</strong></a> Profile.</p><h3>End Notes</h3><p>If you liked this article, be sure to click ❤ below to recommend it and if you have any questions, <strong>leave a comment</strong> and I will do my best to answer.</p><p>For being more aware of the world of machine learning, <a href="https://amiraliryk1.wixsite.com/portfolio"><strong>follow me</strong></a>. It’s the best way to find out when I write more articles like this.</p><p>You can also follow me on <a href="https://github.com/AmirAli5"><strong>Github</strong></a> for code &amp; dataset follow on <a href="https://uet.academia.edu/AliAmir"><strong>Aacademia.edu</strong></a> for this article, <a href="https://twitter.com/amir_ali_cheema"><strong>Twitter</strong></a><strong> </strong>and<strong> </strong><a href="http://amirali.cheema@outlook.com/"><strong>Email </strong></a>me directly or find me on<strong> </strong><a href="https://www.linkedin.com/in/amiralicheema/"><strong>LinkedIn</strong>.</a> I’d love to hear from you.</p><p>That’s all folks, Have a nice day :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4481fa33d85a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/machine-learning-researcher/artificial-neural-network-ann-4481fa33d85a">Artificial Neural Network (ANN)</a> was originally published in <a href="https://medium.com/machine-learning-researcher">Aorb Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to Deep Learning]]></title>
            <link>https://medium.com/machine-learning-researcher/introduction-to-deep-learning-7186118db556?source=rss----32a2162bf0c7---4</link>
            <guid isPermaLink="false">https://medium.com/p/7186118db556</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[deep-learning-basics]]></category>
            <category><![CDATA[neural-networks]]></category>
            <dc:creator><![CDATA[Amir Ali]]></dc:creator>
            <pubDate>Sun, 31 Mar 2019 21:30:34 GMT</pubDate>
            <atom:updated>2019-12-05T02:01:14.202Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction of Deep Learning</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*06TImPiLXp7SSdJeTRtBPA.png" /></figure><p>In this chapter, we will discuss Deep Learning and introduces w real-life story and then provides applications in four different theaters to help beginners learn and know more about this.</p><p>This chapter spans Six parts:</p><ol><li>What is Deep Learning?</li><li>Deep Learning Basic Concept.</li><li>How Deep Learning Work?</li><li>Example of Deep Learning.</li><li>Future of Deep Learning.</li></ol><h3>1. What is Deep Learning?</h3><p>Deep Learning is a machine learning subfield concerned with algorithms inspired by the brain’s structure and a function called artificial neural networks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/394/1*Vts9jUwNFNYfwqp9isaNZQ.jpeg" /></figure><p>Deep learning is a procedure of machine learning that teaches computers to do what comes of course to humans: learn by example. Deep learning is a key technology behind driverless cars, enabling them to be familiar with a stop sign or distinguish a pedestrian from a lamppost. It is the key to voice control in consumer devices such as phones, tablets, TVs and hands-free speakers. Deep learning is gaining.</p><p>A computer model learns to perform classification tasks directly from images, text, or sound in deep learning. Deep learning models can achieve state-of-the-art accuracy, sometimes exceeding performance at the human level. Models are trained using a large set of labeled data and neural network architectures that contain many layers.</p><h3>2. Deep Learning Basic Concepts</h3><p>In progressive Feature Learning, we extricate different layers of non-direct highlights and pass them to a classifier that consolidates every one of the highlights to make forecasts. We are keen on stacking such profound chains of the importance of non-direct highlights since we can’t take in complex highlights from a couple of layers. It tends to be indicated numerically that for pictures the best highlights for a solitary layer are edges and masses since they contain the most data that we can extricate from a solitary non-direct change. To create highlights that contain more data we can’t work on the sources of info straightforwardly, however, we have to change our first highlights (edges and masses) again to get increasingly unpredictable highlights that contain more data to recognize classes.</p><p>It has been demonstrated that the human cerebrum does the very same thing: The main progressive system of neurons that gets data in the visual cortex is delicate to explicit edges and masses while mind districts further down the visual pipeline are touchy to increasingly complex structures, for example, faces.</p><p>While various leveled include learning was utilized before the field Deep learning existed, these designs experienced serious issues, for example, the disappearing angle issue where the slopes turned out to be too little to even think about providing a learning signal for profound layers, hence influencing these models to perform ineffectively when contrasted with shallow learning calculations, (for example, bolster vector machines).</p><p>The term Deep taking in started from new techniques and systems intended to produce these Deep progressive systems of non-straight highlights by beating the issues with evaporating slopes so we can prepare models with many layers of non-direct various leveled highlights. In the mid-2010s, it was demonstrated that consolidating GPUs with enactment works that offered a better slope stream was adequate to prepare Deep models without real challenges. From here the enthusiasm for profound learning developed consistently.</p><p>Deep learning isn’t connected just with adapting profound non-straight various leveled highlights yet also with figuring out how to distinguish exceptionally long non-direct time conditions in successive information. While most different calculations that take a shot at successive information just have a memory of the keep going 10-time advances, long momentary memory (LSTM) repetitive neural systems (designed by Sepp Hochreiter and Jürgen Schmidhuber in 1997) enable the system to get on movement several time-ventures in the past to make exact expectations. While LSTM systems have been generally overlooked in the previous 10 years, their use has developed quickly since 2013 and together with convolutional nets they structure one of two noteworthy examples of overcoming the adversity of Deep learning.</p><h3>3. How Deep Learning works?</h3><p>Deep Learning in gets its name from how it’s utilized to investigate “unstructured” information or information that hasn’t been recently marked by another source and may require definition. That requires cautious examination of what the information is, and rehashed trial of that information to finish up with a last, usable end. PCs are not customarily great at breaking down unstructured information like this.</p><p>Consider it as far as composing: If you had ten individuals compose a similar word, that word would appear to be extremely unique from every individual, from messy to perfect, and from cursive to print. The human cerebrum has no issue understanding that it’s everything a similar word since it realizes how words, composing, paper, ink, and individual characteristics all work. An ordinary PC framework, in any case, would have no chance to get of realizing that those words are the equivalent since they all look so changed.</p><p>That brings us to using neural systems, the calculations explicitly made to imitate how the neurons in the mind collaborate. Neural systems endeavor to parse information on how that a brain can: they will probably manage chaotic information — like composition — and reach valuable determinations, similar to the words that composing is endeavoring to appear. It’s almost effortless to comprehend neural systems on the off chance that we break them into three imperative parts</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/696/1*5J3dimBLLahHg3bk_pSEUw.png" /></figure><p><strong>The Input Layer:</strong> At the information layer, the neural system retains all the unclassified information that it is given. This implies separating the data into numbers and transforming them into bits of yes-or-no information, or “neurons”. If you needed to show a neural system to perceive words, at that point the information layer would be numerically characterizing the state of each letter, separating it into advanced language so the system can begin working. The info layer can be really basic or fantastically unpredictable, contingent upon the fact that it is so natural to speak to something numerically.</p><p><strong>The Hidden Layer: </strong>At the focal point of the neural system are concealed layers — somewhere in the range of one to many. These layers are made of their advanced neurons, which are intended to enact or not initiate dependent on the layer of neurons that goes before them. A solitary neuron is an essential “on the off chance that this, at that point that” show, yet layers are made of long chains of neurons, and a wide range of layers can impact one another, making complex outcomes. The objective is to enable the neural system to perceive a wide range of highlights and consolidate them into a solitary acknowledgment, similar to a kid figuring out how to perceive each letter and afterward framing them together to perceive a full word, regardless of whether that word is composed somewhat messy.</p><p>The concealed layers are additionally where a great deal of profound getting the hang of preparing goes on. For instance, if the calculation neglected to precisely perceive a word, software engineers send back, “Sorry, that is not right,” and the calculation would modify how it gauged information until it found the correct answers. Rehashing this procedure (software engineers may likewise alter loads physically) enables the neural system to develop strong concealed layers that are adroit at searching out the correct answers through a great deal of experimentation also, some outside guidance — once more, much like how the human cerebrum functions. As the above picture appears, concealed layers can turn out to be extremely mind-boggling!</p><p><strong>The output layer:</strong> The yield layer has generally a couple of “neurons” since it’s the place ultimate choices are made. Here the neural system applies the last examination, settles on definitions for the information, and reaches the customized inferences dependent on those definitions. For instance, “Enough of the information lines up to the state that this word is a lake, not path.” Ultimately all information that goes through the system is limited to explicit neurons in the yield layer. Since this is the place the objectives are understood, it’s regularly one of the initial segments of the system made.</p><h3>4.Examples of Deep Learning</h3><p>Deep learning applications are used in industries from automated driving to medical devices.</p><p><strong>Automated Driving</strong>: Automotive researchers are using deep learning to automatically detect objects such as stop signs and traffic lights. Besides, deep learning is used to detect pedestrians, which helps decrease accidents.</p><p><strong>Aerospace and Defense:</strong> Deep learning is used to identify objects from satellites that locate areas of interest, and identify safe or unsafe zones for troops.</p><p><strong>Medical Research:</strong> Cancer researchers are using deep learning to automatically detect cancer cells. Teams at UCLA built an advanced microscope that yields a high-dimensional data set used to train a deep learning application to accurately identify cancer cells.</p><p><strong>Industrial Automation:</strong> Deep learning is helping to improve worker safety around heavy machinery by automatically detecting when people or objects are within an unsafe distance of machines.</p><p><strong>Electronics:</strong> Deep learning is being used in automated hearing and speech translation. For example, home assistance devices that respond to your voice and know your preferences are powered by deep learning applications.</p><h3>5. Types of Deep Learning Algorithms</h3><p>There some variations of how to define the types of Deep Learning Algorithms but commonly they can be divided into categories according to their purpose and the main categories are the following:</p><ul><li><strong>Supervised learning</strong></li><li><strong>Unsupervised Learning</strong></li></ul><h4>Supervised Learning</h4><p>I like to think of supervised learning with the concept of function approximation, where we train an algorithm and at the end of the process, we pick the function that best describes the input data, the one that for a given X makes the best estimation of y (X -&gt; y). Most of the time we are not able to figure out the true function that always makes the correct predictions and another reason is that the algorithm relies upon an assumption made by humans about how the computer should learn and these assumptions introduce a bias, Bias is topic I’ll explain in another post.</p><ul><li>Here the human experts act as the teacher where we feed the computer with training data containing the input/predictors and we show it the correct answers (output) and from the data, the computer should be able to learn the patterns.</li><li>Supervised learning algorithms try to <em>model relationships and dependencies between the target prediction output and the input features</em> such that we can predict the output values for new data based on those relationships which it learned from the previous data sets.</li></ul><p><strong>List of Common Algorithms</strong></p><ul><li>Artificial Neural Network</li><li>Convolutional Neural Network</li><li>·Recurrent Neural Network</li></ul><h4>Unsupervised Learning</h4><ul><li>The computer is trained with unlabeled data.</li><li>Here there’s no teacher at all, actually, the computer might be able to teach you new things after it learns patterns in data, these algorithms a particularly useful in cases where the human expert doesn’t know what to look for in the data.</li><li>are the family of Deep learning algorithms which are mainly used in <em>pattern detection</em> and <em>descriptive modeling</em>. However, <em>there are no output categories or labels</em> here based on which the algorithm can try to model relationships. These algorithms try to use techniques on the input data to <em>mine for rules</em>, <em>detect patterns</em>, and <em>summarize and group the data points which</em> help in deriving meaningful insights and describe the data better to the users.</li></ul><p><strong>List of Common Algorithms</strong></p><ul><li>Self-Organizing Maps</li><li>Boltzmann Machine</li><li>Auto Encoders</li></ul><p>As we can Understand the actually Structure of Deep Learning from below Diagram:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/629/1*cxhABNn09KCEAjq61iwHmg.jpeg" /></figure><h3>1.6: Future of Deep Learning</h3><p>The eventual fate of Deep learning is especially splendid! The incredible thing about a neural system is that it exceeds expectations at managing a huge measure of unique information (consider everything our cerebrums need to manage, constantly). That is particularly applicable in our period of cutting edge savvy sensors, which can accumulate a fantastic measure of data. Conventional PC arrangements are starting to battle with arranging, naming and making determinations from so much information.</p><p>Deep learning, then again, can manage the computerized heaps of information we are gathering. Actually, the bigger the measure of information, the more effective Deep learning progresses toward becoming contrasted with different strategies for investigation. This is the reason associations like Google put such a great amount in Deep learning calculations, and why they are probably going to turn out to be progressively regular later on.</p><h3>End Notes</h3><p>If you liked this article, be sure to click ❤ below to recommend it and if you have any questions, <strong>leave a comment</strong> and I will do my best to answer.</p><p>For being more aware of the world of machine learning, <a href="https://amiraliryk1.wixsite.com/portfolio"><strong>follow me</strong></a>. It’s the best way to find out when I write more articles like this.</p><p>You can also follow me on <a href="https://github.com/AmirAli5"><strong>Github</strong></a> for code &amp; dataset also follow on <a href="https://uet.academia.edu/AliAmir"><strong>Aacademia.edu</strong></a> for this article, <a href="https://twitter.com/amir_ali_cheema"><strong>Twitter</strong></a><strong> </strong>and<strong> </strong><a href="http://amirali.cheema@outlook.com/"><strong>Email </strong></a>me directly or find me on<strong> </strong><a href="https://www.linkedin.com/in/amiralicheema/"><strong>LinkedIn</strong>.</a> I’d love to hear from you.</p><p>That’s all folks, Have a nice day :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7186118db556" width="1" height="1" alt=""><hr><p><a href="https://medium.com/machine-learning-researcher/introduction-to-deep-learning-7186118db556">Introduction to Deep Learning</a> was originally published in <a href="https://medium.com/machine-learning-researcher">Aorb Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dimensionality Reduction(PCA and LDA)]]></title>
            <link>https://medium.com/machine-learning-researcher/dimensionality-reduction-pca-and-lda-6be91734f567?source=rss----32a2162bf0c7---4</link>
            <guid isPermaLink="false">https://medium.com/p/6be91734f567</guid>
            <category><![CDATA[apc]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[scikit-learn]]></category>
            <category><![CDATA[dimensionality-reduction]]></category>
            <category><![CDATA[lda]]></category>
            <dc:creator><![CDATA[Amir Ali]]></dc:creator>
            <pubDate>Sun, 10 Mar 2019 05:11:37 GMT</pubDate>
            <atom:updated>2019-12-03T04:20:17.127Z</atom:updated>
            <content:encoded><![CDATA[<h3>Dimensionality Reduction(PCA and LDA) with Practical Implementation</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/632/1*z8ysJEwuCz-_WxisMg13LA.png" /></figure><p>In this chapter, we will discuss Dimensionality Reduction Algorithms (Principal Component Analysis (PCA) and Linear Discriminant Analysis (LDA)).</p><p>This chapter spans 5 parts:</p><ol><li>What is Dimensionality Reduction?</li><li>How the Principal Component Analysis(PCA) Work?</li><li>How the Linear Discriminant Analysis (LDA) Work?</li><li>Practical Implementation of Principle Component Analysis(PCA).</li><li>Practical Implementation of Linear Discriminant Analysis (LDA).</li></ol><h3>1. What is Dimensionality Reduction?</h3><p>In Machine Learning and Statistic, Dimensionality Reduction the process of reducing the number of random variables under consideration via obtaining a set of principal variables. It can be divided into feature selection and feature extraction.</p><p><strong>We will deal with two main algorithms in Dimensionality Reduction</strong></p><ol><li>Principle Component Analysis (PCA)</li><li>Linear Discriminant Analysis (LDA)</li></ol><h3>2: How Dimensionality Reduction Algorithms Work?</h3><h4>2.1: Principal Component Analysis (PCA).</h4><h4>2.1.1: What is Principle Component Analysis (PCA)?</h4><p>If you’ have worked with a lot of variables before, you know this can present problems. Do you understand the relationship between each variable? Do you have so many variables that you are in danger of overwriting your model to your data or that you might be violating the assumptions of whichever modeling tactic you’re using?</p><p>You might ask the question “how do I take all of the variables. I’ve collected and focused on only a few of them? In technical terms, you want to “reduce the dimension of your feature space. By reducing the dimension of your feature space, you have fewer relationships between variables to consider and less likely to overheat your model.</p><p>Somewhat unsurprisingly, reducing the dimension of the feature space is called “dimensionality reduction” There are many ways to achieve dimensionality reduction, but most of the techniques fall into one of two classes.</p><p>· Feature Elimination</p><p>· Feature extraction</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*gLUHHLNL_kPY9666LlsPEQ.png" /></figure><p><strong>Feature Elimination: </strong>we reduce the feature space by elimination feature. The advantages of the feature elimination method include simplicity and maintainability features. We’ve also eliminated any benefits those dropped variables would bring.</p><p><strong>Feature Extraction: </strong>PCA is a technique for feature extraction. So it combines our input variables in a specific way, then we can drop the “least important” variables while still retaining the most valuable parts of all the variables.</p><p><strong>When should I use PCA?</strong></p><p>1. Do you want to reduce the no. of variables, but are not able to identify variables to completely remove from consideration?</p><p>2. Do you want to ensure your variables are independent of one another?</p><p>3. Are you comfortable making your independent variable less interpretable?</p><h4>2.1.2: How Principle Component Analysis (PCA) work?</h4><p>We are going to calculate a matrix that summarizes how our variables all relate to one another.</p><p>We’ll then break this matrix down into two separate components: direction and magnitude. we can then understand the direction of our data and its magnitude.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/356/1*V4scOI8msKTBPZfUaNAqLw.png" /></figure><p>The above picture displays the two main directions in this data: the back direction and the blue direction. In red direction is the most important one. We’ll get into why this is the case later, but given how the case later, but given how the dots are arranged can you see why the red direction looks more important than the green direction (What would be fitting a line of best fit to the data look like?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/327/1*xUe_0r7anX4DmviW8ju9iA.png" /></figure><p>In the above pic, we will transform our original data into aligning with these important directions. The fig. The show is the same extract data as above but transformed. So that the X- &amp; Y axis are now direction.</p><p>What would the line of best fit look like here:</p><p>1. Calculate the covariance matrix X of data points.</p><p>2. Calculate eigenvectors and correspond eigenvalues.</p><p>3. Sort eigenvectors accordingly to their given value in decrease order.</p><p>4. Choose first k eigenvectors and that will be the new k dimensions.</p><p>5. Transform the original n-dimensional data points into k_dimensions</p><p><strong>Let’s dive into mathematics:</strong></p><p><strong>Dataset:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/628/1*DnZZWj8RQR-Ll1Gd3-qKzQ.png" /></figure><p><strong>Sample size n = 10</strong></p><p><strong>Variables p = 2</strong></p><p>Construct a scatter plot to see how the data is distributed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*7dpTfrXUPI5O0eeOyx4h5A.png" /></figure><p>So Correlation</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/373/1*m5X074GFUUxOFEoNrelhnQ.png" /></figure><p>Positive correlation high redundancy</p><p><strong>Mean of our variables</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/281/1*xA7gz9UNo7G6dzDbstXnJQ.png" /></figure><p>Now</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*FQQqxQVCzWQz7mRxQgqpWw.png" /></figure><p><strong>Step 1:</strong></p><p>· Subtract the mean from the corresponding data component to recentre the dataset.</p><p>· Reconstruct the scatter plot to view.</p><p>· Write the “adjusted” data as a matrix X.</p><p>Note: that “adjusted” data set will have mean zero.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/641/1*FGQ7ZsAp19OjUYuWsQjWHQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*7dpTfrXUPI5O0eeOyx4h5A.png" /></figure><p>Now write the “adjusted” data as a Matrix X.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/1*hCXgJlYNuj2oJap52b_hRA.png" /></figure><p>Note: that the adjusted “dataset will have means zero.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/120/1*pQB-utuwnL5fRTsI44RKnw.png" /></figure><p>Step 2:</p><p>Compute the sample variance-covariance matrix C.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/374/1*g5r-xDZ9cuCnhSOqbbgNWQ.png" /></figure><p>Step 3:</p><p>Compute the eigenvalues lambda 1 and eigenvalue</p><p>Of C order the corresponding pairs from the highest to the lowest eigenvalues.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/206/1*eK9yo91m9tACiam7q2T_hQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/569/1*2VW4r0uPb0SIfKG6D96hbQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/368/1*z3xiqUMm2QxXl9ipUuwluQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/571/1*aVjNVF6E4wTiU7Unzpe-kQ.png" /></figure><p>After solving that’s matrix we get the value of Eigen Vector</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/446/1*h0c0CMK9hfudWYremS32ew.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/631/1*adi0Zz_mN4-FNfj2AIZx9A.png" /></figure><p>So finally</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/173/1*5x4JVSgK49vDt3L0w9QR6g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/569/1*2VW4r0uPb0SIfKG6D96hbQ.png" /></figure><p>Now Eigen Vector</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/144/1*w4MpKkgMRrzPb6zX-k2LKA.png" /></figure><p>In Eigen Vector1 move right direction and 0.735 directions are up</p><p>In Eigen Vector2 move right direction and -0.678 directions are up</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*CNW8MlaggVaGRu8VWcH6wQ.png" /></figure><p>It can be proven</p><p>Total Sample Variance = Sum of Eigen Value</p><p>= 1.28 +0.0490</p><p>=1.33</p><p>By this process, we will be able to exact lines that characterize the data. The first eigenvector will go through the middle of the data points as if it is the lines of best fit.</p><p>The Second eigenvector will give us the other less important pattern in the data. That is all the data points follow the mainline. But are the off to the side of the mainline by some amount?</p><p>Step 4:</p><p>Choose the components and form the eigenvector matrix V. By ordering the eigenvectors according to the eigenvalue, this gives the components in order of their Significance. Hence the eigenvector with the highest eigenvalue is the principal component. The components of lesser significance can be ignored. To reduce the dimensions of the data set.</p><p>Select both components then</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*z4wBYVaBXiBefKdt_4VrbA.png" /></figure><p>So discard the less Significant component (we take PC1 which is 96% information capture)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/271/1*37scEryJRejBdLQMRndILA.png" /></figure><p>Step 5:</p><p>Divide the new data set by taking</p><p>Y = XV</p><p>We have transformed our data. So that it is expressed in terms of the pattern between them, where the patterns are the lines that most closely describe the relationship between data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/564/1*o5HlQETprPq7i42xBK30Fw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/246/1*Sl0yGoJxOXUECt1uEO--Ww.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/227/1*8975hgBK79Wrmwol3YRvNQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*6F_YK_55CxljwbRTRNRbaw.png" /></figure><p>Now again discard the significant component</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/157/1*HcbYUHcWpEamcSan8t5BLg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/359/1*DijY82sgqvmxiCIhhU70NA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/145/1*MEvpwuEB9_amc1FwvuCLrQ.png" /></figure><p>Now</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*jdEyYb2fOeYEML26OUQcUA.png" /></figure><p>In this case, PCA reduces one dimension.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/308/1*SEudNi0JCUrJmsoksmmUEA.png" /></figure><p>In this way, PCA works.</p><p><strong>Note: </strong>If you want this article check out my<strong> </strong><a href="https://www.academia.edu/41161889/A_Briefly_Explanation_of_Principal_Component_Analysis_PCA_with_Practical_Implementation_in_Scikit_Learn"><strong>academia.edu</strong></a><strong> </strong>profile.</p><h4>2.2: Linear Discriminant Analysis (LDA).</h4><h4>2.2.1: What is Linear Discriminant Analysis (LDA)?</h4><p>LDA is a type of Linear combination, a mathematical process using various data items and applying a function to that site to separately analyze multiple classes of objects or items.</p><p>Following Fisher’s Linear discriminant, linear discriminant analysis can be useful in areas like image recognition and predictive analysis in marketing.</p><p>The fundamental idea of linear combinations goes back as far as the 1960s with the Altman Z-scores for bankruptcy and other predictive constructs. Now LDA helps in preventative data for more than two classes, when Logistics Regression is not sufficient. The linear Discriminant analysis takes the mean value for each class and considers variants to make predictions assuming a Gaussian distribution.</p><p>Maximizing the component axes for class-separation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/405/1*1EswxGVdkF8WOW_MKzti0g.png" /></figure><h4>2.2.2: How the Linear Discriminant Analysis (LDA) work?</h4><p>First general steps for performing a Linear Discriminant Analysis</p><p>1. Compute the d-dimensional mean vector for the different classes from the dataset.</p><p>2. Compute the Scatter matrix (in between class and within the class scatter matrix)</p><p>3. Sort the Eigen Vector by decrease Eigen Value and choose k eigenvector with the largest eigenvalue to from a d x k dimensional matrix w (where every column represent an eigenvector)</p><p>4. Used <strong>d * k</strong> eigenvector matrix to transform the sample onto the new subspace.</p><p>This can be summarized by the matrix multiplication.</p><p>Y = X x W (where X is a <strong>n * d</strong> dimension matrix representing the n samples and <strong>you</strong> are transformed <strong>n * k</strong> dimensional samples in the new subspace.</p><p><strong>Let’s Dive into Mathematics</strong></p><p><strong>Dataset:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/374/1*ivnI1tQSnnG-H7RJbL1nhw.png" /></figure><p>Here W1 and W 2 Two different classes w1 belong to class 1 and W 2 belongs to class 2</p><p>Solution:</p><p><strong>For Class 1</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/678/1*v0zADcFMnbpz9SQuUdJQsg.png" /></figure><p><strong>For Class 2</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/668/1*0SBaF47g1mHHCE1z-KR4wA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/658/1*QFvYJCPdTgo73sYd0BswgQ.png" /></figure><p>Now</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/324/1*mxI9UieOiDyrtwX8KAZnwA.png" /></figure><p>So the equation applies to the above table and we get</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/536/1*MKXaWshlp8cKTidtyrmY0A.png" /></figure><p><strong>Similarly, the procedure for others row</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/255/1*MGklH_IM74wezZjQo_6HKA.png" /></figure><p>Now</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/435/1*I2aGl4pGAMJe_qVJhg9RLw.png" /></figure><p>Now find Eigen Value and Eigen Matrix</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/278/1*CfiaaI2Li9lJDiWDj0BWdA.png" /></figure><p>Apply the Quadratic formula and we get the 2 lambda values, these values are eigenvalues.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/380/1*OaCL9wxNIhlW4Fzz_ObxHw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/532/1*FYzUKc5jnOkNIqe0-a2uAQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/207/1*rq4eUTas2iCH2Ik3BnM28w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/643/1*wOQyLsq2VzXM2DhPwRi0bA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/227/1*5og7Vaa3WKR2QEsyoWKLaA.png" /></figure><p>Now From w1</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/637/1*U0ckCXtOhK1nxYjUlXX_Jw.png" /></figure><p>Now From w2</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/645/1*kfivaaRcCOc0Bng_A2qg7A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/281/1*HnknMhJaWfsT6CVIusngXQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/573/1*N9alSLih2zgobnPm5s1stw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/588/1*1c3ik9259fXVHGI66Rj8_Q.png" /></figure><p>After finding the S1 and S2 we can Sw</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/399/1*WjV1UgvP2Y7ZWHWrJgfokg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*R2FJedz5eDI8I_WigUWr5A.png" /></figure><p>In this way, LDA works.</p><p><strong>Note: </strong>If you want this article check out my<strong> </strong><a href="https://www.academia.edu/41161916/A_Deep_Level_Understanding_of_Linear_Discriminant_Analysis_LDA_with_Practical_Implementation_in_Scikit_Learn"><strong>academia.edu</strong></a><strong> </strong>profile.</p><h3>3: Practical Implementation of Dimensionality Reduction.</h3><h4>3.1: Practical Implementation of PCA</h4><p><strong>Dataset Description:</strong></p><p>These data are the results of a chemical analysis of wines grown in the same region in Italy but derived from three different cultivars. The analysis determined the quantities of 13 constituents found in each of the three types of wines. The initial data set had around 30 variables, but for some reason Only have the 13-dimensional version. The attributes are:1) Alcohol 2) Malic acid 3) Ash 4) Alcalinity of ash 5) Magnesium 6) Total phenols 7) Flavanoids 8) Nonflavanoid phenols 9) Proanthocyanins 10)Color intensity 11)Hue 12)OD280/OD315 of diluted wines 13)Proline. All attributes are continuous: No statistics available, but suggest to standardize the variables for certain uses (e.g. For use with classifiers which are NOT scaled invariant) NOTE: 1st attribute is the class identifier (1–3). I use the PCA technique for the Dimensionality Reduction of the wine dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/586/1*AX8x5B_Yowl7EqFgIJnfMw.png" /></figure><p><strong>Part 1: Data Preprocessing:</strong></p><p><strong><em>1.1 Import the Libraries</em></strong></p><p>In this step, we import three Libraries in Data Preprocessing part. A library is a tool that you can use to make a specific job. First of all, we import the <strong>numpy</strong> library used for multidimensional array then import the <strong>pandas</strong> library used to import the dataset and in last we import <strong>matplotlib</strong> library used for plotting the graph.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*CrQA-_brfKBaB-3gql2pNQ.png" /></figure><p><strong><em>1.2 Import the dataset</em></strong></p><p>In this step, we import the dataset to do that we use the <strong>pandas</strong> library. After import our dataset we define our Predictor and target attribute. we call ‘<strong>X</strong>’ predictor here and target attribute which we call ‘<strong>y</strong>’ here.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/589/1*xMmVZ-buamv5Bo1MctTmLQ.png" /></figure><p><strong><em>1.3 Split the dataset for test and train</em></strong></p><p>In this step, we split our dataset into a test set and train set and an 80% dataset split for training and the remaining 20% for tests.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*ZpR41QvN7Y6V2F1qV-Q-MQ.png" /></figure><p><strong>Feature Scaling</strong></p><p>Feature Scaling is the most important part of data preprocessing. If we see our dataset then some attribute contains information in Numeric value some value very high and some are very low if we see the age and estimated salary. This will cause some issues in our machinery model to solve that problem we set all values on the same scale there are two methods to solve that problem first one is Normalize and Second is Standard Scaler.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*IpCDo_Bqik7eg6QzRcZHJA.png" /></figure><p>Here we use standard Scaler import from Sklearn Library.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/556/1*Q9b7SoejqAAhva4DGJmeZg.png" /></figure><p><strong>Part 2: Applying the principal component analysis</strong></p><p>In this part, we use PCA for Dimensionality Reduction.</p><p><strong><em>2.1 Import the Libraries</em></strong></p><p>In this step, we import a PCA model from Scikit Learn Library.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/410/1*jC2uaOq3QIVLOAq82-lLuQ.png" /></figure><p><strong><em>2.2 Initialize our model</em></strong></p><p>In this step, we use the number of components =2 which have high covariance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*Iwz6OG1fuUFHIi-hEIc9pQ.png" /></figure><p><strong><em>3.3 Fitting the Model</em></strong></p><p>In this step, we fit the X data into the model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/448/1*q7URQASqE-bzmnQLlqlZ7Q.png" /></figure><p><strong><em>3.4 Check the Variance</em></strong></p><p>In this step we explain our variance (n_componets = 2)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/504/1*oShcG1OYiOqDvux8A2ZJOQ.png" /></figure><p><strong>Part 3: Applying a model after Dimensionality Reduction Step.</strong></p><p><strong><em>3.1 Import the Libraries</em></strong></p><p>In this step, we are building our model to do this first we import a model from Scikit Learn Library.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/543/1*89sOFAt_3NDpOxBnpdClqQ.png" /></figure><p><strong><em>3.2 Initialize our Logistic Regression model</em></strong></p><p>In this step, we initialize our Logistic Regression model</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/458/1*-3x3ki-BaQqkP0OE6X-fng.png" /></figure><p><strong><em>3.3 Fitting the Model</em></strong></p><p>In this step, we fit the training data into our model X_train, y_train is our training data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*IinnniYjks4NQ71ikdPvUg.png" /></figure><p><strong>Part 4: Making the Prediction and Visualizing the result:</strong></p><p>In this Part, we make a prediction of our test set dataset and visualizing the result using the <strong>matplotlib</strong> library.</p><p><strong><em>4.1 Predict the test set Result</em></strong></p><p>In this step, we predict our test set result.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*LqIBeYxyw5nfywSJXMk4yg.png" /></figure><p><strong><em>4.2 Confusion Metric</em></strong></p><p>In this step we make a confusion metric of our test set result to do that we import confusion matrix from sklearn.metrics then in confusion matrix, we pass two parameters first is y_test which is the actual test set result and second is y_pred which predicted result.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/584/1*Tzng5UOSOZJ5iuhT29GBng.png" /></figure><p><strong><em>4.3 Accuracy Score</em></strong></p><p>In this step, we calculate the accuracy score based on the actual test result and predict test results.</p><p><strong>Note</strong>: accuracy is not good, but our mission is to try to understand how our model works in the practical implementation</p><p><strong><em>4.4 Visualize our Test Set Result</em></strong></p><p>In this Step, we Visualize our test set result.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*_8jKpz7C2cPDwmOXjB4AiQ.png" /></figure><p>If you want dataset and code you also check my <a href="https://github.com/AmirAli5/Machine-Learning"><strong>Github</strong></a> Profile.</p><h4>3.2: Practical Implementation of LDA.</h4><p><strong>Dataset Description:</strong></p><p><strong>Note:</strong> Same Wine dataset which we use in the PCA model using here in the LDA model. Because our accuracy result is not good in PCA and here we obtain much more accuracy to use this model.</p><p>These data are the results of a chemical analysis of wines grown in the same region in Italy but derived from three different cultivars. The analysis determined the quantities of 13 constituents found in each of the three types of wines. The initial data set had around 30 variables, but for some reason Only have the 13-dimensional version. The attributes are:1) Alcohol 2) Malic acid 3) Ash 4) Alcalinity of ash 5) Magnesium 6) Total phenols 7) Flavanoids 8) Nonflavanoid phenols 9) Proanthocyanins 10)Color intensity 11)Hue 12)OD280/OD315 of diluted wines 13)Proline. All attributes are continuous: No statistics available, but suggest to standardize the variables for certain uses (e.g. For use with classifiers which are NOT scaled invariant) NOTE: 1st attribute is the class identifier (1–3). I use the PCA technique for the Dimensionality Reduction of the wine dataset.</p><p><strong>Part 1: Data Preprocessing:</strong></p><p><strong><em>1.1 Import the Libraries</em></strong></p><p>In this step, we import three Libraries in Data Preprocessing part. A library is a tool that you can use to make a specific job. First of all, we import the <strong>numpy</strong> library used for multidimensional array then import the <strong>pandas</strong> library used to import the dataset and in last we import <strong>matplotlib</strong> library used for plotting the graph.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*CrQA-_brfKBaB-3gql2pNQ.png" /></figure><p><strong><em>1.2 Import the dataset</em></strong></p><p>In this step, we import the dataset to do that we use the <strong>pandas</strong> library. After import our dataset we define our Predictor and target attribute. we call ‘<strong>X</strong>’ predictor here and target attribute which we call ‘<strong>y</strong>’ here.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/589/1*xMmVZ-buamv5Bo1MctTmLQ.png" /></figure><p><strong><em>1.3 Split the dataset for test and train</em></strong></p><p>In this step, we split our dataset into a test set and train set and an 80% dataset split for training and the remaining 20% for tests.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*ZpR41QvN7Y6V2F1qV-Q-MQ.png" /></figure><p><strong>Feature Scaling</strong></p><p>Feature Scaling is the most important part of data preprocessing. If we see our dataset then some attribute contains information in Numeric value some value very high and some are very low if we see the age and estimated salary. This will cause some issues in our machinery model to solve that problem we set all values on the same scale there are two methods to solve that problem first one is Normalize and Second is Standard Scaler.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*IpCDo_Bqik7eg6QzRcZHJA.png" /></figure><p>Here we use standard Scaler import from Sklearn Library.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/556/1*Q9b7SoejqAAhva4DGJmeZg.png" /></figure><p><strong>Part 2: Applying the Linear Discriminant analysis</strong></p><p>In this part, we use LDAA for Dimensionality Reduction.</p><p><strong><em>2.1 Import the Libraries</em></strong></p><p>In this step, we import an LDA model from Scikit Learn Library.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*Y8UmHVF2VPlponaGg0DrJw.png" /></figure><p><strong><em>2.2 Initialize our model</em></strong></p><p>In this step, we use the number of components =2 which have high covariance</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/452/1*iYSGEEdgsT1Ez68U-4th-g.png" /></figure><p><strong><em>2.3 Fitting the Model</em></strong></p><p>In this step, we fit the X data into the model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/575/1*CLs1mV9kikyY-qFLViryUA.png" /></figure><p><strong>Part 3: Applying a model after Dimensionality Reduction</strong></p><p><strong><em>3.1 Import the Libraries</em></strong></p><p>In this step, we are building our model to do this first we import a model from Scikit Learn Library.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/543/1*89sOFAt_3NDpOxBnpdClqQ.png" /></figure><p><strong><em>3.2 Initialize our Logistic Regression model</em></strong></p><p>In this step, we initialize our Logistic Regression model</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/338/1*HxNWy3FQuO0ezvrWanykng.png" /></figure><p><strong><em>3.3 Fitting the Model</em></strong></p><p>In this step, we fit the training data into our model X_train, y_train is our training data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*9l8c3qsjBMs7qHi7jyboqQ.png" /></figure><p><strong>Part 4: Making a Prediction and Visualize the result</strong></p><p>In this Part, we make a prediction of our test set dataset and visualizing the result using the <strong>matplotlib</strong> library.</p><p><strong><em>4.1 Predict the test set Result</em></strong></p><p>In this step, we predict our test set result.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/335/1*-1HCXB-5_emZSWqDN3naRg.png" /></figure><p><strong><em>4.2 Confusion Metric</em></strong></p><p>In this step we make a confusion metric of our test set result to do that we import confusion matrix from sklearn.metrics then in confusion matrix, we pass two parameters first is y_test which is the actual test set result and second is y_pred which predicted result.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/445/1*Bv_D_GOBg_HMjzi9g3VYXQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/158/1*MicUaCNyHqJgttLmmdepJw.png" /></figure><p><strong><em>4.3 Visualize our Test Set Result</em></strong></p><p>In this Step, we Visualize our test set result.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*nYR-qpjWPTTBov7nlUWibA.png" /></figure><p>If you want dataset and code you also check my <a href="https://github.com/AmirAli5/Machine-Learning"><strong>Github</strong></a> Profile.</p><h3>End Notes:</h3><p>If you liked this article, be sure to click ❤ below to recommend it and if you have any questions, <strong>leave a comment</strong> and I will do my best to answer.</p><p>For being more aware of the world of machine learning, <a href="https://amiraliryk1.wixsite.com/portfolio"><strong>follow me</strong></a>. It’s the best way to find out when I write more articles like this.</p><p>You can also follow me on <a href="https://github.com/AmirAli5"><strong>Github</strong></a> for code &amp; dataset follow on <a href="https://uet.academia.edu/AliAmir"><strong>Aacademia.edu</strong></a> for this article, <a href="https://twitter.com/amir_ali_cheema"><strong>Twitter</strong></a><strong> </strong>and<strong> </strong><a href="http://amirali.cheema@outlook.com/"><strong>Email </strong></a>me directly or find me on<strong> </strong><a href="https://www.linkedin.com/in/amiralicheema/"><strong>LinkedIn</strong>.</a> I’d love to hear from you.</p><p>That’s all folks, Have a nice day :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6be91734f567" width="1" height="1" alt=""><hr><p><a href="https://medium.com/machine-learning-researcher/dimensionality-reduction-pca-and-lda-6be91734f567">Dimensionality Reduction(PCA and LDA)</a> was originally published in <a href="https://medium.com/machine-learning-researcher">Aorb Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Clustering(K-Mean and Hierarchical Cluster)]]></title>
            <link>https://medium.com/machine-learning-researcher/clustering-k-mean-and-hierarchical-cluster-fa2de08b4a4b?source=rss----32a2162bf0c7---4</link>
            <guid isPermaLink="false">https://medium.com/p/fa2de08b4a4b</guid>
            <category><![CDATA[hierarchical-clustering]]></category>
            <category><![CDATA[k-means-clustering]]></category>
            <category><![CDATA[scikit-learn]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[cluster]]></category>
            <dc:creator><![CDATA[Amir Ali]]></dc:creator>
            <pubDate>Sun, 10 Feb 2019 16:36:04 GMT</pubDate>
            <atom:updated>2019-12-02T17:20:25.985Z</atom:updated>
            <content:encoded><![CDATA[<h3>Clustering(K-Mean and Hierarchical) with Practical Implementation</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/638/1*Ts9tsjeygQPgCRhzeXC5zQ.png" /></figure><p>In this chapter, we will discuss Clustering Algorithms (k-Mean and Hierarchical) which are unsupervised Machine Learning Algorithms.</p><p>This chapter spans 5 parts:</p><ol><li>What is Clustering?</li><li>How k-Mean Cluster Work?</li><li>How Hierarchical Cluster Work?</li><li>Practical Implementation of k-Mean Cluster.</li><li>Practical Implementation of Hierarchical Cluster.</li></ol><h3>1. What is Clustering?</h3><p>Clustering analysis or Clustering is the task of grouping a set of an object in such a way object in the same group(called cluster) are more similar( in some sense or another to each other than to those in another group (clusters). It is the main task of exploratory data mining &amp; a common technique for statistical data analysis used in many fields including Machine Learning, Pattern Recognition, Image Analysis, Information Retrieval, Bioinformatics, Data Compression, and Computer Graphics. Example: Library</p><p><strong>we will be dealing with two main algorithms</strong></p><ol><li>K-means clustering</li><li>2.Hierarchical Clustering</li></ol><h3>2. How does Clustering Algorithm work?</h3><h4>2.1: k-Mean Cluster.</h4><h4>2.1.1: What is k-Mean?</h4><p>K-Means clustering aims to partition n observation into k clusters in which each observation belongs to the cluster with the nearest mean, serving as a prototype of the cluster.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/235/1*8-fVkj9l8AnQUfIqSOlMnw.png" /></figure><h4>2.1.2: How k-Mean Cluster work?</h4><p>The k-Means clustering algorithm attempt to split a given anonymous data set(a set of containing information as to class identity into a fixed number (k) of the cluster.</p><p>Initially, k number of the so-called centroid is chosen. A centroid is a data point (imaginary or real) at the center of the cluster.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/367/1*er4Y8d_W60WrbAMXvsSLcg.png" /></figure><p><strong>Dataset Description:</strong></p><p>This dataset has three attributes first is an item which is our target to make a cluster of similar items second and the third attribute is the informatics value of that item.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/573/1*XXf9WqsO2sXUA_StoPYHkA.png" /></figure><p>Now In the first step take any random row to let’s suppose I take row 1 and row 3.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/568/1*h186kOX-CuLk9vqWJ-Q56Q.png" /></figure><p>Now take these above centroid values to compare with observing the value of the respected row of our data by using the Euclidean Distance formula.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/539/1*yTGAAIZxuNSIUhKyAt_qrA.png" /></figure><p>Now let’s solve one by one</p><p><strong>Row 1 (A)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/211/1*eVI6MLxjOcJhBPndVTwnlA.png" /></figure><p><strong>Row 2 (B)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/197/1*ehI2Ne6OifOSS4bfLVDJ4g.png" /></figure><p><strong>Row 3 (C )</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/215/1*BwJ5g9kTpD4D893RAkMUDQ.png" /></figure><p><strong>Row 4 (D)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/211/1*6gnxz8c0dEGUaad1yhyqXA.png" /></figure><p><strong>Row 5 (E)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/199/1*ZjyrjsvHOr3FPXpd6_xN-w.png" /></figure><p><strong>Now</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/585/1*jeb8YgtZ6npRMEDhMHofsA.png" /></figure><p>Let’s say A and B are belong the Cluster 1 and C, D and E.</p><p>As we show in below table</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/1*vOWMShUGFWJeebfdQByFCQ.png" /></figure><p>Now calculate the centroid of cluster 1 and 2 respectively and again calculate the closest mean until calculate when our centroid is repeated previous one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/566/1*PiRZnfoiJHogqTl3p2HSeg.png" /></figure><p>Now find the Centroid of respected Cluster 1 and Cluster 2</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/225/1*d7wR-5mIhstAk_f849tu_A.png" /></figure><p><strong>New Centroid</strong></p><p>X1 = (1, 0.5)</p><p>X2 = (1.7,3.7)</p><p><strong>Previous Centroid</strong></p><p>X1 = (1, 1)</p><p>X2 = (0, 2)</p><p>If New Centroid Value is equal to previous Centroid Value then our cluster is final otherwise if not equal then repeat the step until new Centroid value is equal to previous Centroid value.</p><p>So in our case new centroid value is not equal to previous centroid.</p><p>Now recalculate cluster having the closest mean.</p><p>So</p><p>X1 = (1, 0.5)</p><p>X2 = (1.7,3.7)</p><p>Similarly procedure as we calculate above</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/595/1*0aP5NKPzB4EREUyFxoJrXA.png" /></figure><p>So based on based one, A B and C belongs to cluster 1 &amp; D and E from cluster 2.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/1*93cX0dBjwf5W2k77gQilCw.png" /></figure><p>So mean of Cluster I and 2</p><p>X1( Cluster 1 ) = ( 0.7 , 1)</p><p>X1( Cluster 2 ) = ( 2.5 , 4.5)</p><p><strong>New Centroid</strong></p><p>X1 = ( 0.7 , 1)</p><p>X2 = ( 2.5 , 4.5)</p><p><strong>Previous Centroid</strong></p><p>X1 = (1, 0.5)</p><p>X2 = (1.7,3.7)</p><p>If New Centoid Value is equal to previous Centroid Value then our cluster is final otherwise if not equal then repeat the step until new Centroid value is equal to previous Centroid value .</p><p>So in our case new centroid value is not equal to previous centroid.</p><p>Now recalculate cluster having a closest mean similar step</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/579/1*HlSOcgZhz0pqVzcVCBCbsQ.png" /></figure><p>So based on closest distance, A B and C belongs to cluster 1 &amp; D and E from cluster 2.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/575/1*SVav4FKNDJ7rdJD2DocNsQ.png" /></figure><p>So mean of Cluster I and 2</p><p>X1( Cluster 1 ) = ( 0.7 , 1)</p><p>X1( Cluster 2 ) = ( 2.5 , 4.5)</p><p><strong>New Centroid</strong></p><p>X1 = (1, 0.5)</p><p>X2 = (1.7,3.7)</p><p><strong>Previous Centroid</strong></p><p>X1 = (1, 0.5)</p><p>X2 = (1.7,3.7)</p><p>So here we have New Centroid values is Equal to previous value and Hence our cluster are final. A, B and C are belong to cluster 1 and D and E are belong to Cluster 2.</p><p>As shown in fig:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*zjh6FUTW02gLpYPNHHa_pQ.png" /></figure><p><strong>Note: </strong>If you want this article check out my<strong> </strong><a href="https://www.academia.edu/41158164/A_Deep_Level_Understanding_of_K-Mean_Cluster_with_Practical_Implementation_in_Scikit_Learn"><strong>academia.edu</strong></a><strong> </strong>profile.</p><h4>2.2: Hierarchical Cluster.</h4><h4>2.2.1: What is Hierarchical?</h4><p>Similar working like K-Mean clustering but the difference is that we create a tree structure.So</p><p><strong>Bottom-up:</strong></p><p>Initially, each point is a cluster.</p><p>Repeatedly combine the two “nearest” clusters into one.</p><p><strong>Top-Down:</strong></p><p>Start with one cluster and recursively split it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/194/1*dJjZcAcZMO5N_hw2XOBMYg.png" /></figure><p>Used for clustering similar things join and make a hierarchical clustering.</p><h4>2.2.2: How Hierarchical Cluster work?</h4><p>Agglomerative with Dendogram</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/569/1*0KxE5W6M6-PZirnvaM0tlg.png" /></figure><p>Consider only one part (lower triangle part)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/599/1*liR_ka4mGolvXBITKJcUWA.png" /></figure><p>Now find the minimum distance</p><p>Minimum distance = 1 for <strong>E &amp; A</strong></p><p>Hence merge EA</p><p>So</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/490/1*3YUewbUXwqdzj5axtz0HWw.png" /></figure><p><strong>Now Find the minimum distance from EA to other</strong></p><p>C = min [ dist { (E, A), C} ]</p><p>= min [ dist(E, C) , dist(A, C) ]</p><p>= min [2, 2]</p><p>= 2</p><p>B = min [ dist { (E, A), B} ]</p><p>= min [ dist(E, B) , dist(A, C) ]</p><p>= min [2, 5]</p><p>= 2</p><p>D = min [ dist { (E, A), D} ]</p><p>= min [ dist(E, D) , dist(A, D) ]</p><p>= min [3, 3]</p><p>= 3</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/491/1*TlcT6x-JeziaOMQM-bg9Gg.png" /></figure><p>In this minimum distance = 1</p><p>So for CB</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/497/1*oes0kbwkNuWht1Tz-NZ4JQ.png" /></figure><p><strong>Now again find the minimum distance from CB to another point</strong> as we find above So</p><p>EA = min [ dist { (E, A), (C, B} ]</p><p>= min [ dist { (E, C) , (E, B) , (A, C), (A, B) } ]</p><p>= min dist[2, 2, 2, 5]</p><p>= 2</p><p>D = min [ dist { (C, B), D} ]</p><p>= min [ dist{(C, D) , (B, D)} ]</p><p>= min dist[6, 3]</p><p>= 3</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/616/1*79zZTsAQIzZ1LwRGiSHbIA.png" /></figure><p>Now minum distance = 2 for EA , and CB from above table</p><p>D = min(dist [ ( E, A , C, B ) , D ]</p><p>= min dist [ (E, D), (A, D). (C, D) , (B, D)</p><p>= min dist [3, 3, 6, 3]</p><p>= 3</p><p>So</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/323/1*snfDY9kl9Oa0HQTgWWjCYQ.png" /></figure><p>So finally are dendogram are final</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*vqk8C68jR0G3pxYnXM6_vA.png" /></figure><p><strong>Note: </strong>If you want this article check out my<strong> </strong><a href="https://www.academia.edu/41158299/An_Intuitive_Guide_of_Hierarchical_Cluster_with_Practical_Implementation_in_Scikit_Learn"><strong>academia.edu</strong></a><strong> </strong>profile.</p><h3>3. Practical Implementation of Clustering Algorithms.</h3><h4>3.1: Practical Implementation of k-Mean Cluster</h4><p><strong>Dataset Description:</strong></p><p>This Dataset has complete the information about Mall Customer Spending Score. The Dataset contains five attributes and 200 instances. The first attribute is Customer ID which has every Customer has Unique Second is Gender which is of course male/female third attribute is age which is between 19 to 70 of different customers 4th attribute is Annual Income in k$ which have different customer have a different Income some have very low some have middle and some have very high income and last attribute Spending Score which he spends on Mall.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/569/1*g4KtVulya8Y55uQszX9ofA.png" /></figure><p><strong>Part 1: Data Preprocessing:</strong></p><p><strong><em>1.1 Import the Libraries</em></strong></p><p>In this step, we import three Libraries in Data Preprocessing part. A library is a tool that you can use to make a specific job. First of all, we import the <strong>numpy</strong> library used for multidimensional array then import the <strong>pandas</strong> library used to import the dataset and in last we import <strong>matplotlib</strong> library used for plotting the graph.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*CrQA-_brfKBaB-3gql2pNQ.png" /></figure><p><strong><em>1.2 Import the dataset</em></strong></p><p>After importing the Libraries using the pandas library import the dataset Note that we are working with Unsupervised Learning so we use the only X.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/596/1*lUk13fMnaRQqjALhA_M8cg.png" /></figure><p><strong>Part 2: elbow method to find the optimal number of clusters</strong></p><p>In this second part, we import our model. And apply the Elbow method to choose the optimal clusters.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*JdIdiQqNpsymD-NY-Zk2GA.png" /></figure><p>So as we see in the diagram the line bend on 5 so 5 clusters are decided to take.</p><p><strong>Part 3: Applying kMeans to the mall dataset and Visualizing the Clusters.</strong></p><p><strong><em>3.1 Init the Model</em></strong></p><p>In the final step, we use the Our Model which is the K-Means cluster and take several Cluster 5 and makes a cluster of five different customers based on spending score in the mall.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/612/1*aulDMFHncsn0v7cZ8cvsVg.png" /></figure><p><strong><em>3.2 Fit and Predict the Dataset</em></strong></p><p>In the step, we fit the dataset into our model and predict them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/259/1*M2-agAu0FsDKEPBtOKgwCA.png" /></figure><p><strong><em>3.3 Visualizing the Result</em></strong></p><p>In the visualizing step, we make a graph take an Income on X and Spending Score on y. So we can easily visualize the different customers in our graph. As we can see there are different customer have a different behavior which is Careful, Standard, Target, Careless, and Sensible.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*iut7UDTLqX7ycEBSo2iMJg.png" /></figure><p>If you want dataset and code you also check my <a href="https://github.com/AmirAli5/Machine-Learning"><strong>Github</strong></a> Profile.</p><h4>3.2: Practical Implementation of Hierarchical Cluster.</h4><p><strong>Dataset Description:</strong></p><p>This Dataset has complete the information about Mall Customer Spending Score. The Dataset contains five attributes and 200 instances. The first attribute is Customer ID which has every Customer has Unique Second is Gender which is of course male/female third attribute is age which is between 19 to 70 of different customers 4th attribute is Annual Income in k$ which have different customer have a different Income some have very low some have middle and some have very high income and last attribute Spending Score which he spends on Mall.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/569/1*g4KtVulya8Y55uQszX9ofA.png" /></figure><p><strong>Part 1: Data Preprocessing:</strong></p><p><strong><em>1.1 Import the Libraries</em></strong></p><p>In this step, we import three Libraries in Data Preprocessing part. A library is a tool that you can use to make a specific job. First of all, we import the <strong>numpy</strong> library used for multidimensional array then import the <strong>pandas</strong> library used to import the dataset and in last we import <strong>matplotlib</strong> library used for plotting the graph.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*CrQA-_brfKBaB-3gql2pNQ.png" /></figure><p><strong><em>1.2 Import the dataset</em></strong></p><p>After importing the Libraries using the pandas library import the dataset Note that we are working with Unsupervised Learning so we use the only X.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/596/1*lUk13fMnaRQqjALhA_M8cg.png" /></figure><p><strong>Part 2: Use the dendogram method to find the optimal number of clusters</strong></p><p>In this second part, we apply the Dendogram method to choose the optimal clusters.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/1*NXyNcm6TpMhzGtyteZYH1g.png" /></figure><p>So based on the dendogram we choose the number of cluster =5.</p><p><strong>Part 3: Applying Hierarchical to the mall dataset and Visualizing the Clusters</strong></p><p><strong><em>3.1 Import and Init the model</em></strong></p><p>In the final step, we import our model from Scikit Learn Library and then initialize the model by taking five numbers of the cluster which we decide from the Dendogram method.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/461/1*h3fSeEy9_UKSOTbRN_9R4g.png" /></figure><p><strong><em>3.2 Fit and Predict the Dataset</em></strong></p><p>In the step, we fit the dataset into our model and predict them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/259/1*M2-agAu0FsDKEPBtOKgwCA.png" /></figure><p><strong><em>3.3 Visualizing the Result</em></strong></p><p>In the visualizing step, we make a graph take an Income on X and Spending Score on y. So we can easily visualize the different customers in our graph. As we can see there are different customer have a different behavior which is Careful, Standard, Target, Careless, and Sensible.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*2lS6-GV13cVD0peWzIYtUA.png" /></figure><p>If you want dataset and code you also check my <a href="https://github.com/AmirAli5/Machine-Learning"><strong>Github</strong></a> Profile.</p><h3>End Notes:</h3><h3>End Notes:</h3><p>If you liked this article, be sure to click ❤ below to recommend it and if you have any questions, <strong>leave a comment</strong> and I will do my best to answer.</p><p>For being more aware of the world of machine learning, <a href="https://amiraliryk1.wixsite.com/portfolio"><strong>follow me</strong></a>. It’s the best way to find out when I write more articles like this.</p><p>You can also follow me on <a href="https://github.com/AmirAli5"><strong>Github</strong></a> for code &amp; dataset follow on <a href="https://uet.academia.edu/AliAmir"><strong>Aacademia.edu</strong></a> for this article, <a href="https://twitter.com/amir_ali_cheema"><strong>Twitter</strong></a><strong> </strong>and<strong> </strong><a href="http://amirali.cheema@outlook.com/"><strong>Email </strong></a>me directly or find me on<strong> </strong><a href="https://www.linkedin.com/in/amiralicheema/"><strong>LinkedIn</strong>.</a> I’d love to hear from you.</p><p>That’s all folks, Have a nice day :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fa2de08b4a4b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/machine-learning-researcher/clustering-k-mean-and-hierarchical-cluster-fa2de08b4a4b">Clustering(K-Mean and Hierarchical Cluster)</a> was originally published in <a href="https://medium.com/machine-learning-researcher">Aorb Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Association Rule(Apriori and Eclat Algorithm)]]></title>
            <link>https://medium.com/machine-learning-researcher/association-rule-apriori-and-eclat-algorithm-4e963fa972a4?source=rss----32a2162bf0c7---4</link>
            <guid isPermaLink="false">https://medium.com/p/4e963fa972a4</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[association-rule]]></category>
            <category><![CDATA[eclat]]></category>
            <category><![CDATA[fp-growth]]></category>
            <category><![CDATA[apriori]]></category>
            <dc:creator><![CDATA[Amir Ali]]></dc:creator>
            <pubDate>Sun, 03 Feb 2019 17:15:07 GMT</pubDate>
            <atom:updated>2020-12-14T16:36:21.294Z</atom:updated>
            <content:encoded><![CDATA[<h3>Association Rule(Apriori and <strong>FP</strong>-<strong>Growth Algorithms</strong>) with Practical Implementation</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*YnK9Bk-bAIKKevRcwsH_cQ.png" /></figure><p>In this chapter, we will discuss Association Rule (Apriori and FP-Growth Algorithms) which is an unsupervised Machine Learning Algorithm and mostly used in data mining.</p><p>This chapter spans 5 parts:</p><ol><li>What is the Association Rule?</li><li>How does the apriori Algorithm work in Association Rule?</li><li>How FP-Growth Algorithm Work in Association Rule?</li><li>Practical Implementation of the Apriori Algorithm.</li><li>Practical Implementation of FP-Growth Algorithm.</li></ol><h3>1. What is the Association Rule?</h3><p>Most ML algorithms in DS work with <em>numeric data</em> and tend to be quite <em>mathematical</em>. *But, ARM is perfect for categorical data and involves <strong>little more than simple counting</strong>!</p><p>· It’s a <strong><em>rule-based</em></strong> ML method for discovering interesting relations between variables in large databases.</p><p>· Identifies strong rules using some measures of <strong><em>interestingness</em></strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/513/1*I3mbQeRtjUUTFqfuFVhHBg.png" /></figure><p><strong>No love lost.</strong></p><p><strong>On Friday afternoons, young American males who buy diapers (nappies) also have a predisposition to buy beer.</strong></p><p>This anecdote became popular as an example of how <em>unexpected</em> association rules might be found from <strong>everyday data</strong>.</p><p>Such information can be used as the basis for decisions about marketing activities such as <em>Promotional Pricing</em> or <em>Market Basket Analysis</em>.</p><p><strong>Mathematics Involved</strong></p><p><em>The problem can be seen as:</em></p><p>· Let <strong>I = {i_1,i_2,….}</strong> be a set of binary attributes called items.</p><p>· Let <strong>D = {t_1,t_2,….}</strong> be a set of transactions called the database.</p><p>· Each transaction in D contains a <em>subset</em> of items in me.</p><p>The simple rule looks like -<br> <strong>t_1 </strong>⇒<strong> t_2</strong> (Here, t_i is generally a single item or a set of items)<br> *t1: Antecedent, t2: Consequent</p><h4>Supermarket Example</h4><p>I = {milk, bread, butter, beer, diapers}<br> D is as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/325/1*TUHC2jC7PfJdHZpEUUX31g.png" /></figure><p><strong>1 indicates the presence of the item in that transaction, and 0 shows the absence.</strong></p><p>Rule: <strong>{butter, bread} </strong>⇒<strong> {milk}</strong>, meaning that if butter and bread are bought, customers also buy milk.</p><p><strong>Thresholds used for Relations</strong></p><p>· <strong>Support</strong> — Indication of <em>how frequently</em> the itemset appears in the database. It is defined as the fraction of records that contain X∪Y to the total number of records in the database. Suppose, the support of an item is 0.1%, it means only 0.1% of the transactions contain that item.</p><p><strong>Support (XY) = Support count of (XY) / Total number of transaction in D</strong></p><p>· <strong>Confidence</strong> — Fraction of the number of transactions that contain X∪Y to the total number of records that contain X. <br> It’s is a measure of the <em>strength of the association rules.</em> <br> Suppose, the confidence of the association rule X⇒Y is 80%, it means that 80% of the transactions that contain X also contain Y together.</p><p><strong><em>Confidence (X|Y) = Support (XY) / Support (X)</em></strong></p><p>· <strong>Other measures</strong> include Lift, Conviction, All-Confidence, Collective strength and Leverage.</p><h3>2. How does the Association Rules Algorithm work?</h3><h4>2.1: How the Apriori algorithm works?</h4><p><strong>Dataset Description:</strong></p><p>This dataset has two attributes and 5 transactions of different item here M= mango, O=orange, N=nut, E=Elderberry, y= yam, D= date, A= apple, U= Uglifruit, c=cherry, and k= kiwifruit and our target is that we take this transaction of five instances to make an association rule of this and recommend the item.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/571/1*Rz_CXPm9NCxDRHytTFDqrw.png" /></figure><p>Min support = 60%</p><p>Min confidence = 80%</p><p><strong>Now find the support count of each item set</strong></p><p><strong>C1 =</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/573/1*yB3ByN45Z29T2nynVweg7A.png" /></figure><p>Support count = Number of items set repeat in a different transaction.</p><p>Compare min support with each item set support count.</p><p>So</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/341/1*2jlVRC37bEmwdGwgMd2S2g.png" /></figure><p>So skip the item set which is repeated less than 3 from above C1 table.</p><p><strong>L1 =</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/560/1*8shz5ooy1ssUDscQma0-og.png" /></figure><p>Now make a combination of Item Set in pair and count the Support to generate C2</p><p><strong>C2=</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/579/1*UaOVd8U3Urpz0HWPQoK95g.png" /></figure><p>Support Count = No of itemset repeat in a different transaction.</p><p>Again Compare C2 with Support which is 3 so Skip the itemset which supports count less than 3.</p><p>As we showed in below table</p><p><strong>L2=</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/578/1*UOwMm7qN54WlVokzP6FltA.png" /></figure><p>Now Make a Pair to Generate C3</p><p><strong>C3=</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/571/1*mPuHR5m6BK-3INnMq6vVgA.png" /></figure><p>Support Count = No of itemset repeat in a different transaction.</p><p>Again Compare C3 with Support which is 3 so Skip the itemset which supports count less than 3.</p><p>As we showed in below table</p><p><strong>L3=</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/581/1*n_y16_nUQeXqRemrVgWaHA.png" /></figure><p>Now create an association rule with support &amp; confidence from O, K, E.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/573/1*8WPhC0cbuJgYsQu9oWKHPQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/317/1*1VPA1SWvszno_G6nvZ7NfA.png" /></figure><p><strong>Now Compare Confidence with min confidence which we mention earlier which 80% so skip Itemset with less than 80% confidence</strong></p><p>As we have shown Below in Table</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/424/1*nQNq0i81ptEDkKsQdWVEwA.png" /></figure><p>Hence Final Association Rule Are</p><p><strong>Market Basket Analysis.</strong></p><p>O Ʌ K ⇒ K</p><p>Orange Ʌ Kiwi fruit ⇒ Elderberry</p><p>O Ʌ E ⇒ K</p><p>Orange Ʌ Elderberry ⇒ Kiwi fruit</p><p><strong>So Finally</strong></p><p>If you buy Orange and Kiwi Fruit together then he prefers or recommends also buy Elder Berry.</p><p>Or if you buy Orange and Elderberry together then he prefers or recommends also buy Kiwi Fruit.</p><p><strong>Note: </strong>If you want this article check out my<strong> </strong><a href="https://www.academia.edu/41141835/An_Intuitive_Guide_of_Apriori_Algorithm_with_Practical_Implementation"><strong>academia.edu</strong></a><strong> </strong>profile.</p><h4>2.2: How the FP-Growth algorithm works?</h4><p><strong>Dataset Description:</strong></p><p>This dataset has two attributes and five instances first attribute is Transaction Id and the Second attribute is basically Itememset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/569/1*1bcgEddyaUxd3V4zyN5xZg.png" /></figure><p><strong>Four Step to Solve this</strong></p><p>1. Find the minimum support of each item.</p><p>2. Order frequent itemset in descending order.</p><p>3. Draw an FP tree.</p><p>4. Minimum frequent pattern from the FP tree.</p><p>So let’s solve step by step</p><p><strong>Step 1: Find the minimum support of each item</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/578/1*pFrQjd0wm-2y-geBO7oSNQ.png" /></figure><p><strong>Minimum support = 3</strong></p><p>Skip item from the above table which is less than 3 so</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/575/1*80Ws0BmXOGA6izdQSou-3g.png" /></figure><p><strong>Step 2: Order frequent item in descending order</strong></p><p>f = 4, c= 4, a= 3, b= 3, m= 3, p=3</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/579/1*ZvGkizwnf33JEg8Z8pJB6g.png" /></figure><p><strong>Step 3: FP tree</strong></p><ol><li>Insert the first transaction</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/344/1*iLEm5FSLIO-YX6ZnfbcstA.png" /></figure><p>2. Insert the second transaction</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/487/1*b-MAPGMsmTLRYB5I7SviPQ.png" /></figure><p>3. Insert the third transaction</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/531/1*uhgvxhpef2HG_Q__kQpO5A.png" /></figure><p>4. Insert the fourth transaction</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/514/1*pnthLneOhYew2qeIo9pJxQ.png" /></figure><p>5. Insert the fifth transaction</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*I2WAM65d7hgc8AFY4hQFlQ.png" /></figure><p><strong>Step 4: Mining frequent Pattern from FP tree.4</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/562/1*dH_3gKANcXmy-3xhI663vQ.png" /></figure><p>So finally</p><p>If you buy</p><p>1. <strong>c</strong> then he suggests <strong>p</strong></p><p>2. <strong>F, c, a</strong> suggest <strong>a</strong></p><p>3. <strong>F, c </strong>suggest <strong>a</strong></p><p>4. <strong>F </strong>suggest <strong>c</strong></p><p><strong>Note: </strong>If you want this article check out my<strong> </strong><a href="https://www.academia.edu/41141885/A_Briefly_Explanation_of_Eclat_Algorithm_with_Practical_Implementation"><strong>academia.edu</strong></a><strong> </strong>profile.</p><h3>9.3: Practical Implementation of Association Rule.</h3><h4>9.3.1: Implementation of Apriori Algorithm</h4><p><strong>Dataset Description:</strong><br>This dataset contains information on Market Basket Optimization which has 7500 instances data of different items that have max 20 items in one instance and a minimum 1 item may have contained in some instances. We use this dataset to make a recommendation system for our market Basket Analysis and we use the apriori algorithm to make the rule for Market Basket Analysis.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/573/1*Q3_eEpzNbBGs_lCtYPRjLQ.png" /></figure><p><strong>Part 1: Data Preprocessing:</strong></p><p><strong><em>1.1 Import the Libraries</em></strong></p><p>In this step, we import three Libraries in Data Preprocessing part. A library is a tool that you can use to make a specific job. First of all, we import the <strong>numpy</strong> library used for multidimensional array then import the <strong>pandas</strong> library used to import the dataset and in last we import <strong>matplotlib</strong> library used for plotting the graph.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*-5kWlWeNCanhR5t3Ihv-1g.png" /></figure><p><strong><em>1.2 Import the dataset</em></strong></p><p>After importing the Libraries using the pandas library import the dataset which is in CSV and then makes a new list of transaction makes and appends our dataset in this list to make the right format of the index.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*jBAZphPOBdASpSs8n4ZpBg.png" /></figure><p><strong>Part 2: Building the apriori model:</strong></p><p>In this part we building the apriori model but unfortunately not such library for association rule in scikit learn so we use developer made library and used after import the library we initialize the apriori algorithm and pass some parameter first is transaction which is our dataset take min_supprot=0.003 min_confidence=0.2 min_lift=3 and min_length=2 which I already explain in mathematical portion.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*Q7Poi7ASYdr4FKWTjktFIQ.png" /></figure><p><strong>Part 3: Check the Rule:</strong></p><p>In this part, we check our rule for Market Basket Analysis</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/417/1*-j1m41KEFye7Qd0W_bSWxg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*LD-XZzZcWbqI9ve2EDTZAg.png" /></figure><p>These above are the rule if you buy this and this then these recommendations as we see above So that’s it.</p><p>If you want dataset and code you also check my <a href="https://github.com/AmirAli5/Machine-Learning"><strong>Github</strong></a> Profile.</p><h4>3.2: Implementation of FP Growth Algorithm</h4><p>Unfortunately, there is no such library to Build an FP tree So we doing from Scratch.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/765/1*5D3GxAkrPkAjVBWNNDsRfw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/860/1*3OZKmVVvmWL0zcYl6qGooA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/859/1*qOsa0Xda_7kUvZkPlZlCEA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/854/1*gddXVTJOLkUp5PUm3_maYw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/863/1*nwSi7jUvCxWKxGXAqxamdA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/882/1*hEORH75NBBA0QvfWQbEFsA.png" /></figure><p>If you want dataset and code you also check my <a href="https://github.com/AmirAli5/Machine-Learning"><strong>Github</strong></a> Profile.</p><h3>End Notes:</h3><p>If you liked this article, be sure to click ❤ below to recommend it and if you have any questions, <strong>leave a comment</strong> and I will do my best to answer.</p><p>For being more aware of the world of machine learning, <a href="https://amiraliryk1.wixsite.com/portfolio"><strong>follow me</strong></a>. It’s the best way to find out when I write more articles like this.</p><p>You can also follow me on <a href="https://github.com/AmirAli5"><strong>Github</strong></a> for code &amp; dataset follow on <a href="https://uet.academia.edu/AliAmir"><strong>Aacademia.edu</strong></a> for this article, <a href="https://twitter.com/amir_ali_cheema"><strong>Twitter</strong></a><strong> </strong>and<strong> </strong><a href="http://amirali.cheema@outlook.com/"><strong>Email </strong></a>me directly or find me on<strong> </strong><a href="https://www.linkedin.com/in/amiralicheema/"><strong>LinkedIn</strong>.</a> I’d love to hear from you.</p><p>That’s all folks, Have a nice day :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4e963fa972a4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/machine-learning-researcher/association-rule-apriori-and-eclat-algorithm-4e963fa972a4">Association Rule(Apriori and Eclat Algorithm)</a> was originally published in <a href="https://medium.com/machine-learning-researcher">Aorb Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>