<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Raghu Raj Rai ⚡️ on Medium]]></title>
        <description><![CDATA[Stories by Raghu Raj Rai ⚡️ on Medium]]></description>
        <link>https://medium.com/@raghurajrai?source=rss-78d81445e932------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Ib8UA7BP94E56VE3ikwQnw.jpeg</url>
            <title>Stories by Raghu Raj Rai ⚡️ on Medium</title>
            <link>https://medium.com/@raghurajrai?source=rss-78d81445e932------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 09:01:20 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@raghurajrai/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Train your Neurons on Artificial Neural Networks [featuring Keras]]]></title>
            <link>https://raghurajrai.medium.com/train-your-neurons-on-artificial-neural-networks-featuring-keras-2757f51bb7ed?source=rss-78d81445e932------2</link>
            <guid isPermaLink="false">https://medium.com/p/2757f51bb7ed</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[keras]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[neural-networks]]></category>
            <dc:creator><![CDATA[Raghu Raj Rai ⚡️]]></dc:creator>
            <pubDate>Fri, 29 Jun 2018 13:05:28 GMT</pubDate>
            <atom:updated>2018-06-29T13:05:56.754Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kP8k4ZBl8xO--7xM9xsaCg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/kCrrUx7US04?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Lurm</a> on <a href="https://unsplash.com/search/photos/patterns?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p><strong><em>Congratulations! You just took your first step towards transcending into a Wizard. Grab a cup of coffee and have a seat.</em></strong></p><p>Neural Networks work like magic! It is possible to implement an image recognition neural network in just under fifty lines of code using ResNet50 and it will recognize your Cats or Dog pictures with a pretty good accuracy. This is pure magic, and the essence of this being possible today, even after understanding how it works still seems like magic to me. Understanding Deep Learning is not knowing that this is not magic but pure statistics and code, but it’s understanding how this magic works. It’s knowing how to be a Data Wizard.</p><p>I intend to make this article as easy to understand as possible for anyone with little to no background on neural networks. After demystifying the wizardry of it, we will train a simple neural network on Keras(Nothing too complex. We won’t be diving into Image Recognition or GANs for now) for some hands on fun. I will provide links and other resources for a better visual understanding and I highly advice that you go through them as we go along with the article. At the end of the article, I will add all the resources I personally used to develop my understanding of any concepts, and I’m sure these resources are excellent for anyone getting started in this field.</p><p>To answer one of the most common and popular questions that people have about Deep Learning:</p><blockquote>How much time will it take for me to learn Deep Learning and making Neural Networks? Does it involve a lot of complex Mathematics(Calculus and Matrices)?</blockquote><blockquote>It takes a lot of time to develop any significant skills in Deep Learning. The field is HUGE! You can of course just get an intuition of what the code is doing and build some fancy project in no time, but do you want to just do that? As for the second part, yes, it does involve a substantial amount of Mathematics especially Calculus. It is easy to understand the initial topics but the complexity takes a Tangential slope as you progress in the field. I found it really hard to understand many topics. But once I got in touch with a research student and told him that I’m finding the Mathematics to be a bit too complex for my level. The advice I received was one of the best I ever got: Find out why you want to learn Deep Learning? If the reason is to earn money or follow the trend, it is easy to lose track. Find something you’d want to make and work on it. This was honestly the best thing I heard and I think it stuck with me.</blockquote><p><strong><em>Embrace!</em></strong></p><h3>How Neural Networks came into existence</h3><p>The work and research on Neural Networks and Deep Learning go way way back to the 1950&#39;s when researchers actually used<em> electrical circuits to implement a simple neural network</em>. The underlying inspiration for the research was to implement how our actual neurons work and if it is possible to implement a machine which can work in a similar fashion. More and more research has been done on the topic since then. But it was only in recent years that we found out ways to implement these algorithms in our daily life to maximize efficiency and reduce complexity.</p><p>We started with Perceptrons and eventually there came more useful concepts like Support Vector Machines, Back Propagation and different types of Neural Networks for different applications. We have reached a stage where we can use a pre-trained model and just modify it’s end to make it applicable for our use(Transfer Learning), which is just like transferring memories from one brain to another!</p><p><em>As a result, we have this booming industry based entirely on Data.</em></p><p>You can read more about the history of neural networks by following these links. They are really interesting and it’s always good to know how the concepts came to be:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*CghyBtUI5LVRHAMgoOaqIg.jpeg" /><figcaption>Chris Bishop. Source: Wikipedia</figcaption></figure><ul><li><a href="http://www.ijritcc.org/download/Research%20Paper%20on%20Basic%20of%20Artificial%20Neural%20Network.pdf">Research Paper on Basic of Neural Network</a></li><li><a href="https://cs.stanford.edu/people/eroberts/courses/soco/projects/neural-networks/History/history1.html">1940’s to 1970’s History by Stanford</a></li></ul><blockquote>“The basis of Machine Learning. . . Deep Neural Networks”</blockquote><blockquote>— Chris Bishop</blockquote><h3>How Neural Networks Work</h3><p>The best way to understand Neural Networks are with visual examples. I will provide some great resources at the end of this section but it is important to understand the topic textually or read it once for a better understanding.</p><blockquote>An important thing to remember is that Artificial Neural Networks are closely related to the Neural Networks in our brain.</blockquote><p>The only difference is that, our Brain’s networks are capable of a much wider domain of understanding, whereas an Artificial Neural Network is constrained to just one or a few domains of understanding. You can think of it as the differences between a musician and a music player. A musician can invent, modify and play a genre of music and much more. A music player can play any song you feed into it. And it will be able to play the same music over and over and over again without any errors. A musician will fail here cause however hard he tries, there will always be some difference in playing the same tune again. Maybe a chord struck with a negligibly different force. But the point remains that if we think of the music player as a neural network, it is able to do something that a musician can do. But it is constrained to that one thing only(or that one domain of application). It is incapable of anything more but the one thing it does, it never fails at it.</p><p>A neural network generally works in this way:</p><ul><li>You feed information to the input end of the network.</li><li>The information flows through the network’s edges and nodes.</li><li>At the end we are left with a final output. This output is not necessary to be a number but probabilities of the output being an object in case we are classifying something. So in case of classification, we will be left with the neural network telling us the probabilities of the outputs. This is the understanding of our network that which output it believes to match better with the input.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1008/1*A45QNFTWQdGewSN1anYVJA.png" /><figcaption>Source: <a href="https://www.extremetech.com/">https://www.extremetech.com</a></figcaption></figure><p>A neural networks consist of 3 types of layers: <strong>Input Layer(in which we feed our inputs), Hidden Layer(where the processing happens) and Output Layer(the results that we obtain)</strong>.You might wonder why we stack “layers” of neurons to build a neural network and how can we determine the number of layers or nodes in each layer that we need. Well this is a really brief topic and there is no hard coded rule for selecting the number of layers and nodes. There are some general approaches however but the number of layers and nodes and determine the <em>overfitting</em> and <em>underfitting</em> of your model. So generally we have to test and evaluate our model to check which one works the best. Coming to the concept of layers, learning is a process which combines many small information packets into a big information packet. Suppose you are asked to solve this equation: “4 + 7”. You will instantly derive the answer as 11. But let’s think for a moment. Was this information hard-coded into your brain, that whenever you see this equation written, you can derive that it equalizes to 11? No. Take this example: “1234 * 432”. I’m sure you’ll need a little time to solve that but you will eventually. When we look at an equation, out brain first breaks it down into small information packets. In this case, we first saw the “4” ,“7” and “+” operator. Our brain made the assumption that “4” and “7” are the operands. The next step for our brain was to determine the operation we need to do on these 2 numbers or addition in our case. So our brain finally determined that we have to add these two numbers and the output was “11”. Now why were we so fast at evaluating these 2 numbers and not the other two bigger numbers? This is where the concepts of “weights” come in. As we start with mathematics at an early age, our brain is trained on smaller numerical examples. And as we grow, we tend to do more of these smaller operations. “2*2” is “4”, we hardly need a fraction to determine this cause we have generally dealt with this equations thousands of times in our life. And with each time, our brain was adding weight between the input “2*2” and “4”, just like our neural networks maps different neurons in each layer. The edge connection these 2 layers is assigned weight, which goes on increasing as we do this equation repeatedly over time. We feel more positive about the output being “4” whereas we know for certain that the output won’t be “5”(hence, the weight of the edge connecting our input to this output being “0”).</p><p>The concept of determining an output in a neural network is based entirely on <em>“Activation”</em>. The neurons of a neural network simply holds a number. There may be different numbers in different neurons of the input layer or maybe none(which amounts to 0). This data of all the neurons flows to the next layer through weighted edges. The edges are weighted to represent which neurons are more important in determining our results. When the weighted data reaches the next layer of neurons, it is met with an Activation Function. On a side note, we call this network the <em>Feed Forward Neural Network</em> cause information flows forwards. What the Activation Function does is: It simply converts the input to a positive or a negative value while adding some complexity to it to support the Gradient Descent algorithm. By converting the input to a signed value, we can determine weather that neuron should activate/fire or not, which means, weather it should pass that information forward or not. The neuron is essentially determining weather this input is important for our next step or it would be better if we just stop this here cause it’s not adding more value and would only confuse our network.</p><p>But even after activations, we can expect some non required values to reach the outputs in case our neural network didn’t had access to ample information to make it smart enough to recognize these differences. Suppose that we had to identify a “5”, so we might get 2 outputs: a “5” and a “S” cause they are visually similar to some extent. The outputs have a number assigned to them between 0 and 1 which tells us the probability of the output being our actual answer. So if our neural network is totally stupid, it might favor “S” more than “5” but if it’s reasonably smart, it might say that the probability of the input being a “5” is 0.78 whereas the probability of it being an “S” is 0.52. Our neural networks are very truthful. They don’t lie. If they feel they’re unsure, they’ll simply tell us that they think 2 or more outputs are possible but they feel one is more probable than the others.</p><p>Here are some excellent visual explanation on how a neural network works:</p><ul><li><a href="https://www.youtube.com/watch?v=aircAruvnKk&amp;list=WL&amp;index=5&amp;t=0s">3Blue1Brown’s Youtube Video on Neural Networks</a></li><li><a href="https://www.youtube.com/watch?v=5aHRBCVTNKE">Brandon Rohrer’s Youtube Video on Convolution Neural Networks</a></li><li><a href="https://www.blog.google/topics/machine-learning/understanding-inner-workings-neural-networks/">Google Blog’s Post on inner workings of neural networks</a></li></ul><h3>Some Important Concepts in Artificial Neural Networks</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*jyOsGn6immM7_rams2x1Ow.gif" /><figcaption>Source: <a href="https://nbmpub.com/">https://nbmpub.com/</a></figcaption></figure><p><strong>Backpropagation:</strong> The concept of backpropagation is really important in understanding how Deep Neural Networks train. In the beginning when we have our neural network architecture fixed, we initialize some random weights to all edges of our model. After that, we starting passing our training data through our neural network. Of course most of the time, we won’t be getting a correct output in the beginning cause our model is just not tuned for it as we initialized the weights of the edges randomly. This is where the concept of backpropagation kicks in. When we get an output, we can calculate the “<em>error</em>” of our output as compared to the actual value. We feedback this error to our neural network and tell it to adjust it’s weights and model parameters to minimize this error and hence increase it’s accuracy. This is done, using gradient descent and chain rule. (<a href="https://www.youtube.com/watch?v=WZDMNM36PsM">Watch this video by RimstarOrg which explains the concept visually</a>)</p><p><em>In case you want to understand the Mathematics behind the concept, here is a great resource which explains back propagation on point! </em><a href="https://brilliant.org/wiki/backpropagation/"><em>Back Propagation on Brilliant.org</em></a></p><p><strong>Activation Function:</strong> When an input is received in a neuron, the neuron is assigned two tasks: <strong>1. Produce an output by modifying the input as per it’s need &amp; 2. Decide weather to pass it as an output</strong>. The activation function primarily provides us with a <em>non-linear function</em> which is essential in training a neural network to solve complex problems. A neural network without an activation function is just a linear regression model. <em>To implement back-propagation, we need to use gradient descent, which cannot be implemented if we have a linear function</em>. If the output from the activation function is positive and relevant, the neuron would pass it on to the next neuron else ignore it.</p><p>There are many kinds of activation functions which are more efficient in their own domain of applications(<em>Binary Step Classifier, ReLU, Tanh</em> to name a few popular ones). Refer the following resources for an in-depth understanding of activation functions and their types and how to chose one for your application:</p><ul><li><a href="https://en.wikipedia.org/wiki/Activation_function">Activation Functions Wikipedia</a></li><li><a href="https://www.analyticsvidhya.com/blog/2017/10/fundamentals-deep-learning-activation-functions-when-to-use-them/">Analytics Vidhya Article</a></li><li><a href="https://www.quora.com/How-should-I-choose-a-proper-activation-function-for-the-neural-network">Quora Discussion</a></li></ul><p><strong>Regularization: </strong>Regularization is required in neural networks to avoid over-fitting. The word “penalty” resonates well with the concept of regularization. There are many ways of regularizing a neural network by tuning it’s parameters.</p><p>References for understanding the regularization techniques:</p><ul><li><a href="http://Andrej Karpathy">Slides based on materials by Andrej Karpathy</a></li><li><a href="http://James D. McCaffrey">James D. McCaffrey’s Blog</a></li></ul><p><strong>Transfer Learning:</strong> Transfer Learning can be used in situations where we already have a trained model available to us and we want to use it for other tasks which are similar to the ones the model was trained for. Think of a model trained to recognize all kinds of animals. This model would have been trained on a big training set. Now we have this model with us but we don’t want to recognize all animals. We want to build a model which can recognize Dog breeds. For this, we won’t have to train an entirely new model. We already have a highly efficient model. All we’ll need to do is to tune that model for our needs. <strong>This tuning is done by just changing the last layer of the pre-trained neural network to make predictions as per our need.</strong></p><p>A good example could be the <em>ImageNet</em> model, which is a highly efficient pre-trained model available for image recognition. We can directly pull the model in Keras, remove the last layer and feed it our last layer based on the objects we want it to recognize.</p><p>Read more about Transfer Learning here:</p><ul><li><a href="https://www.tensorflow.org/tutorials/image_retraining">Tensorflow Tutorial on Image Retraining</a></li><li><a href="http://cs231n.github.io/transfer-learning/">CS231 Course Notes</a></li><li><a href="http://ruder.io/transfer-learning/">Sebastian Ruder’s Blog</a>[Really Well Detailed]</li></ul><p><strong>Optimization: </strong>When we talk about Neural Network Optimization, we actually mean to <em>reduce the error in the objective function, which is the mean square error function (loss/cost function)</em>. We have to optimize weights of neural network to minimize the objective function. Backpropagation is currently the most widely used optimization techniques for training neural networks, but it’s scope is limited after an extent. Also, there are other means of optimization which might generate the same results but can significantly reduce the training time, which is an important commodity in Deep Learning. These other optimization techniques are easy to use and can be set using a parameter while training a Keras model.</p><p>It is important to read about Optimization techniques as we will be frequently using them while training our models. These are some good resources I used to understand the basics of other optimization techniques:</p><ul><li><a href="http://www.deeplearningbook.org/contents/optimization.html">Optimization related chapter from Ian Goodfellow’s Deep Learning Book</a></li><li><a href="https://arxiv.org/pdf/1703.00441.pdf">Learning to Optimize Neural Nets- paper by Ke Li and Jitendra Malik</a></li><li><a href="http://cs231n.github.io/neural-networks-3/#update">Parameter Updates section from CS231n</a></li></ul><p><strong>Dead Neurons: </strong>If we are using an activation function like ReLU(<em>Rectified Linear Unit</em>), we may face the issue of Dead Neurons. The ReLU function returns the integer if it is positive and zero when the output is negative(rectified). There are cases when a neuron has to deal with many negative values as input to it, and the gradient of these inputs will always be 0 as the gradient for negative input is always 0. Due to this nature of the Activation function, some neurons may never be adjusted because of the nature of the training set and die. Generally, while using ReLU activation, we deal with a few dead neurons in our network but it is not problematic. But in some cases if the number of dead neurons are too high, there may be significant problems with our training. <em>A solution to this could be to use a leaky ReLU Activation function</em>.</p><h4>Types of Neural Networks</h4><p>There are so many types of Neural Networks that it might take an entire article to just discuss the basic concepts on a high level.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AevLgsCHY9IamWQXW06EzA.png" /><figcaption>Source: asimovinstitute.org</figcaption></figure><p>There is a neural network for each set of applications. The most popular one is definitely the <em>Convolutional Neural Network</em>(CNN) due to it’s excellent capabilities at learning from images, which is one of the most used application of deep learning.</p><p>But you can’t use CNNs if suppose, you want to develop a program that can generate art in Van Gogh’s style. You’ll need to use the <em>Generative Adversarial Network</em>(GAN) for it. GANs are the best part of Neural Networks and I love it! If Deep Learning is magic, GANs are the next dimension. <strong>The Google Brain team developed a new form of encryption using Adversarial Networks. It’s a really interesting paper. Do check it out! </strong><a href="https://arxiv.org/pdf/1610.06918.pdf"><strong>Official Paper from arXiv</strong></a></p><p>The picture alongside sums up all the types of Neural Networks available today. Do take a look at it. Try to think on how they differ from each other.</p><h4>Deep Learning Libraries for Python</h4><blockquote>When it comes to making Artificial Neural Networks, the Data Science community is blessed with a wide array of tools and choices!</blockquote><p>Some of the most popular ones are:</p><ul><li><a href="https://www.tensorflow.org/">Google’s Tensorflow</a></li><li><a href="http://deeplearning.net/software/theano/">Theano</a></li><li><a href="https://www.microsoft.com/en-us/cognitive-toolkit/">Microsoft Cognitive Toolkit(CNTK)</a></li></ul><p>It may be a bit hard for a beginner to use these libraries as their code tend to be a little complicated for someone entirely new to the field to understand. So there are even better, <em>easy to understand and intuitive frameworks available</em>, which uses the above mentioned libraries as their back-end. As a result, constructing new models becomes really easy and short to code and highly intuitive. Two of the most popular ones are:</p><ul><li><a href="https://keras.io/#getting-started-30-seconds-to-keras">Keras</a></li><li><a href="http://caffe.berkeleyvision.org/">Caffe</a></li></ul><p>All these libraries are really flexible and easy to set up and begin with. Personally, I prefer Keras with the Tensorflow back-end. One reason I really like Keras is because the stacking of neuron layers and compiling the model is really intuitive and easy. You are free to look around and check out the code samples of all of them to see which one seems more intuitive to you.</p><h3>Introduction to Keras</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*LBjjmGofNJ_6vetddYAvIQ.jpeg" /><figcaption>Source: blog.keras.io</figcaption></figure><p>If I have to say why I prefer Keras over any other framework, I’ll just say: “<strong>Keras Prioritizes developer experience</strong>”. That matters a lot. Most of the frameworks when being built have a major objective of making them fast and efficient due to which most of the times they miss out on the developer experience, i.e., how easy it is for a developer to work with them and learn to use them.</p><p>Keras supports all major versions of Python from 2.7–3.6 and is one of the most popular Deep Learning Library as per analyzing the mentions from Stackoverflow and arXiv papers.</p><p>Keras also support many hardware configurations, including Nvidia GPUs and Google TPUs which extends to multi GPU and distributive training support.</p><p>Below is a sample code from the Keras homepage. Can you guess what it is doing?</p><pre><strong>from</strong> keras.models <strong>import</strong> Sequential <br><strong>from</strong> keras.layers <strong>import</strong> Dense, Activation</pre><pre>model = Sequential() <br>model.add(Dense(32, input_dim=784)) <br>model.add(Activation(&#39;relu&#39;))</pre><p><strong><em>If you can make some inferences from the sample code, you will ❤️ Keras!</em></strong></p><p><strong><em>Please go through the </em></strong><a href="https://keras.io/getting-started/sequential-model-guide/"><strong><em>Kera’s Getting Started</em></strong></a><strong><em> guide on their homepage to see Keras in action.</em></strong></p><h3>Implementing a Neural Network in Keras</h3><p>Ok! So this is the best part. We are going to implement a really simple Neural Network in Keras. (<em>“under 15 lines of codes” and yada yada!</em>)</p><p>We will feed a sample of 8-bit binary values to the neural network. It has to identify which one of them is an odd number. Here is an example of what we’ll feed to our neural network and what output it should produce:</p><pre>__________________________<br>Input             | Output   <br>__________________________<br>1 1 1 0 0 1 1 1 1 |  1<br>1 0 0 0 1 0 0 0 0 |  0<br>1 1 0 0 1 1 0 1 0 |  0<br>1 0 0 1 0 1 0 0 0 |  0<br>1 0 0 1 1 0 1 0 1 |  1<br>0 0 1 0 0 0 0 1 1 |  1<br>__________________________  . . . and so on.</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*ClskFQM_8eTw8ytexmmzsg.png" /></figure><p>This task seems fairly simple! “n%2&quot;, and we’re done. But then again, the purpose is not to use it as an application but to demonstrate in the simplest way how a neural network learns.</p><p>For this application, we will only need 2 layers of neurons. We won’t need any hidden layer right now as there is essentially no need of them. You can see how our neural network would look like in the illustration to the left.</p><p>We are using Keras with the Tensorflow backend.</p><pre><em>#We set the seed value with a constant number to get consistent #results every time our neural network is trained. <br>#This is because when we create a model in Keras, it is assigned #random weights every time. Due to this, we might receive different #results every time we train our model.<br>#However this won&#39;t be a general issue, our training set is small, #so we take this precaution</em><br><strong>import numpy as np<br>np.random.seed(1)<br>import tensorflow as tf<br>tf.set_random_seed(1)<br>import keras</strong></pre><pre><em>#We create a training set of fifteen 8-bit binary numbers</em><strong><br>train_X = np.array([[0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,1], [0,0,0,0,0,0,1,0], [0,0,0,0,0,0,1,1], [0,0,0,0,0,1,0,0], [0,0,0,0,0,1,0,1], [0,0,0,0,0,1,1,0], [0,0,0,0,0,1,1,1], [0,0,0,0,1,0,0,0], [0,0,0,0,1,0,0,1], [0,0,0,0,1,0,1,0], [0,0,0,0,1,0,1,1], [0,0,0,0,1,1,0,0], [0,0,0,0,1,1,0,1], [0,0,0,0,1,1,1,0], [0,0,0,0,1,1,1,1]]) <br>train_y = np.array([0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1]) <br>test_X = np.array([[1,0,0,1,1,1,0,1], [1,0,0,0,0,1,1,0]])</strong></pre><pre><em>#We create a Sequential model</em><strong><br>model = keras.models.Sequential()</strong></pre><pre><em>#In the next line, we add both the required layers to our model<br>#The input_dim parameter is the number of input neurons and the #first parameter, &quot;1&quot; is the number of neurons in our first hidden #layer(which happens to be the output layer)</em><strong><br>model.add(keras.layers.Dense(1, input_dim=8, activation=&#39;sigmoid&#39;))</strong></pre><pre><em>#Configuring the model for training</em><br><strong>model.compile(loss=&#39;binary_crossentropy&#39;, optimizer=keras.optimizers.SGD(lr=1.0), metrics=[&#39;accuracy&#39;])</strong></pre><pre><em>#We have defined all parameters, so we train our model with the training data we created.<br>#epochs: Number of times the dataset is passed through the network<br>#batch_size: Number of samples passed at a time</em><br><strong>model.fit(train_X, train_y, epochs= 20, batch_size= 5)</strong></pre><pre><em>#Our Neural Network has been trained now. We pass two inputs to the #model to check the results it produce.<br>#The results would be in the range of 0.98 or 0.02 cause we might #still be left with some error rate(which could&#39;ve been fixed if we #used a bigger training set or different model parameters.<br>#Since we desire binary results, we just round the results using the #round function of Python.<br>#The predictions are actually in </em><br><strong>print([round(x[0]) for x in model.predict(test_X)])</strong></pre><p>It is clearly understood to us that the 8th bit of the input determines weather the number is even or odd. But this is not known to the neural network. It has been assigned random weights when it was created. Now, we understand that to judge an even or odd number, we only need to bother with the last bit so intuitively, the neuron connecting the last bit to the output should be the only one getting activated(should have the weight set as “1”) while the rest should be dead by the end of the training process. And this is exactly what happens! The neural network determines the output error, and using back propagation, makes gradual changes to the weights until all the first seven neurons are dead. And hence, our neural network determines an even or odd number.</p><blockquote>Congratulations! You have built your first Artificial Neural Network!</blockquote><h4>Further Learning Resources</h4><p>As I mentioned in the beginning, here are some excellent resources to get started with Deep Learning. I took a detour from the general route and learned in a very haphazard manner without committing to one resource, which is not a very efficient practice. But one thing I discovered is that it is practically useless to go around scrounging the internet, searching for the one best course/book/video that will teach you everything about Deep Learning.</p><p>There may be more better learning resources available but there are just the ones I’ll mention cause I have personally used these for my reference.</p><p>Youtube Channels:</p><ul><li><a href="https://www.youtube.com/user/shiffman">The Coding Train</a></li><li><a href="https://www.youtube.com/channel/UCYO_jab_esuFRV4b17AJtAw">3Blue1Brown</a></li><li><a href="https://www.youtube.com/user/sentdex">Sentdex</a></li><li><a href="https://www.youtube.com/channel/UCWN3xxRkmTPmbKwht9FuE5A">Siraj Raval</a></li><li><a href="https://www.youtube.com/user/BrandonRohrer">Brandon Rohrer</a></li></ul><p>Books(Both of the books are available to read for free online):</p><ul><li><a href="http://www.deeplearningbook.org/">The Deep Learning Book by Ian Goodfellow</a></li><li><a href="https://web.stanford.edu/~hastie/ElemStatLearn/">The Elements of Statistical Learning by Trevor Hastie</a></li></ul><p>Some websites:</p><ul><li><a href="https://www.analyticsvidhya.com/">Analytics Vidhya</a></li><li><a href="https://machinelearningmastery.com/">MachineLearningMastery</a></li><li><a href="https://elitedatascience.com/">EliteDataScience</a></li></ul><p>For papers, you can head over to <a href="https://arxiv.org/">arXiv.org</a>.</p><p>I haven’t taken any courses but I do plan on committing to one soon. The two courses that are really popular in the community are:</p><ul><li><a href="https://www.fast.ai/">Fast.ai</a></li><li><a href="https://www.deeplearning.ai/">Deeplearning.ai</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2757f51bb7ed" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[XGBoost: The Excalibur for Everyone]]></title>
            <link>https://medium.com/data-science/xgboost-the-excalibur-for-everyone-8009bd015f1e?source=rss-78d81445e932------2</link>
            <guid isPermaLink="false">https://medium.com/p/8009bd015f1e</guid>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[xgboost]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Raghu Raj Rai ⚡️]]></dc:creator>
            <pubDate>Sun, 24 Jun 2018 16:51:49 GMT</pubDate>
            <atom:updated>2018-06-24T17:28:21.593Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B9a8zerXDcTMu-SouKaZeg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/ai6IRDJQMKw?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Daniel Mayovskiy</a> on <a href="https://unsplash.com/search/photos/rocket?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>When I discovered the XGBoost algorithm, I was a bit sceptical of it’s capabilities cause wherever I read about it, everyone was chiming on how great and magical it is. On digging up further on the “<em>magical</em>” factor of XGBoost, I found out that it has been the essential element of many Kaggle competition winners, and in some cases, the “<em>only</em>” algorithm that people applied to their dataset.</p><p>The natural course of action was to just test out the algorithm from a code sample already available and see for myself how good it is. I did that on a running project of my own where I first used the Random Forrest Regressor and calculated it’s Mean Absolute Error, and then I passed the same Dataframe to my XGB Regressor and calculated it’s <a href="https://en.wikipedia.org/wiki/Mean_absolute_error"><em>Mean Absolute Error</em></a>. The results varied on a dramatic scale!(<strong>It was nearly 20% better than my previous model</strong>)</p><p>On visiting the official documentation on XGBoost, I found out that there are even parameters to tune this further for better results. This is amazing! With no time to waste, I quickly read the documentation and added a few parameters to my model. I got a few errors and could not understand what most of those parameters were doing, leave a few like <em>n_estimators</em> and <em>learning_rate</em>, but I was able to fit my model and the results were again breaking the previous records with an even better accuracy.(<em>Not a dramatic increase but I guess it varies from model to model</em>)</p><blockquote>I’ll share some of my findings here which I’m sure will get you a good idea of how you can put XGBoost to your use in your next analysis.</blockquote><h4>Some Inspiration:</h4><blockquote>Tianqi Chen developed XGBoost, which started as a research project as part of the <a href="http://dmlc.ml/">Distributed (Deep) Machine Learning Community (DMLC) group</a>. The first release came in March 2014.</blockquote><p>The capabilities of boosted trees have been brought to great use beyond the use of Machine Learning and Data Analysis. It is a good point to note that the discovery of <strong>Higgs Boson</strong> was possible with the use of Boosted Trees. You can read the <a href="http://proceedings.mlr.press/v42/chen14.pdf">paper related to this discovery</a>.</p><h4>The Difference between Bagging and Boosting &amp; How XGBoost Works</h4><p><em>To understand how XGBoost works and what makes it better, we must understand how Boosted Trees differ from Random Forrest.</em></p><p>The Bagging Concept is used in Random Forrest Regressor. Bagging stands for <em>Bootstrap Aggregating</em> which means choosing a random sample <strong>with replacement</strong>. The basic steps of a Bagging algorithm is to generate n samples from the dataset(as opposed to a single tree formed in the Decision Tree Regressor), train each sample individually and average all of their predictions at the end. One important point to note is that Bagging <em>reduces the variance </em>of our model.</p><p>The Boosting concept is used in our XGBoost Regressor. In Boosting, the random sample that we take for training each mini-tree is picked <em>with replacement over weighted data</em>. Due to this fact, we can term each sample to be a <strong>weak learner</strong>. Each of these weak learners are assigned a weights based on their accuracy of classification. After these weak learners are trained, a weighted average of their estimates are taken for the final predictions at the end. So our weak learners are combined together to form a strong learner.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/912/1*TebQuJsPc7upto5dvURjSA.png" /><figcaption>Source: XGBoost</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/938/1*lZdcfBG2wm9fSMs4gRi4fQ.png" /><figcaption>Source: XGBoost</figcaption></figure><p><strong>XGBoost stands for Extreme Gradient Boosting</strong>. Gradient boosting is an <em>ensemble method </em>that sequentially adds our trained predictors and assigns them a weight. However, instead of assigning different weights to the classifiers after every iteration, this method fits the new model to new residuals of the previous prediction and then minimizes the loss when adding the latest prediction. <em>So, in the end, you are updating your model using gradient descent and hence the name, gradient boosting. </em>This is supported for both regression and classification problems. XGBoost specifically, implements this algorithm for decision tree boosting with an additional custom regularization term in the objective function.</p><blockquote>A good way to think of it is to consider a project group with each individual being better in one domain than the others, and these individuals can be combined together to make a great project. So, many weak learners making a strong learner. Pretty practical!</blockquote><p>The algorithm is implemented using the O<em>bjective function</em>(Loss Function + Penalty) with an important regularization term added to it(<em>the Penalty, which puts the ‘Boosting’ in Gradient Boosting</em>).</p><p>You can read more about the working of the algorithm on the <a href="https://xgboost.readthedocs.io/en/latest/model.html">XGBoost Introduction Page</a>.</p><p><a href="https://arxiv.org/abs/1603.02754">The official published paper by Tianqi Chen.</a></p><p>SauceCat has also written a great <a href="https://towardsdatascience.com/boosting-algorithm-xgboost-4d9ec0207d">post going in depth with the Maths behind the algorithm and it’s code </a>on Towards Data Science.</p><h4>XGBoost in Code</h4><p>Using the XGBoost Regressor is just like using any other regression-based approach like Random Forrest. We follow the same methods:</p><ul><li>Clean the Data</li><li>Select the important parameters</li><li>Make a training and test set</li><li>Fit the model to your training set</li><li>Evaluate your model on your test data</li></ul><p><em>and of course, every other step you might take in between.</em></p><p>We consider that you already have the training and test data with you and you have performed the required steps before the fitting of the model. In case you haven’t, just make a simple Dataframe in Pandas and use Scikit-Learn’s <a href="http://scikit-learn.org/stable/modules/generated/sklearn.model_selection.train_test_split.html"><em>train_test_split</em> function</a> to split your data into a training and test set automatically.</p><pre>from xgboost import XGBRegressor #The library to be imported</pre><pre>model = XGBRegressor()<br>model.fit(training_Set_X, training_Set_y, verbose=False)<br>predictions = model.predict(testing_Set_X)</pre><pre>from sklearn.metrics import mean_absolute_error</pre><pre>#Computing the MAE of our predictions<br>print(&quot;Mean Absolute Error : &quot; + str(mean_absolute_error(predictions, testing_Set_y)))</pre><p>A better way to use the XGBRegressor is to make use of the additional parameters that could be passed to it. You can see in the screenshot below how parameters can have a great effect on the accuracy of our predictions.(<em>The difference may be bigger or smaller depending on your dataset</em>)</p><p><strong>XGBRegressor offers many tuning parameters which can be used to reduce the training time and accuracy significantly.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/887/1*Faj_riHOB8B5zEDOwpFJTQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/677/1*RB9iIk37at1tiNHEEkM1jw.png" /></figure><p>Another great feature offered by XGBoost is the <em>plot_importance</em> function which can provide a plot of the features of our model and their importance.</p><p>This is a great addition to analyse our model and evaluate our features. We may chose to drop some features in case they don’t add meaning to our model.</p><p>Do visit the <a href="http://xgboost.readthedocs.io/en/latest/">XGBoost Website</a> because they’ve provided an easy to understand and good explanation of the features and algorithm without confusing the reader with heavy mathematical notations.(<em>Although most of the notations we see related to Machine Learning consist of just the Summation notation, there is something about that sign that scares people out.</em>)</p><blockquote>I hope this introduction was enough to get you up and running with XGBoosting(This name is surely the coolest name on the DataScience Block). Post any insights if you’ve been using the algorithm. I’ll try to update the article to introduce the Mathematical Concept of it.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8009bd015f1e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/xgboost-the-excalibur-for-everyone-8009bd015f1e">XGBoost: The Excalibur for Everyone</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Art of Deduction: featuring Pandas and Python]]></title>
            <link>https://medium.com/data-science/the-art-of-deduction-featuring-pandas-and-python-a61dbb622986?source=rss-78d81445e932------2</link>
            <guid isPermaLink="false">https://medium.com/p/a61dbb622986</guid>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[pandas]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Raghu Raj Rai ⚡️]]></dc:creator>
            <pubDate>Thu, 21 Jun 2018 17:46:22 GMT</pubDate>
            <atom:updated>2018-06-22T12:33:24.112Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5wpLsj2xz2bHenQuG611wQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/RzA62WEBXDk?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Jeremy C</a> on <a href="https://unsplash.com/search/photos/panda?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Almost everyone starting out with Machine Learning or Data Analytics or almost any other Data Science related topic must learn to use Pandas if you are chosing Python as your accomplice. (Personally, I miss R. No love lost there yet)</p><p>This is a short and general introduction to Pandas and probably all that you’ll need to get started. There’s more to Pandas than we cover in this article but you will definitely pick it up as you go along with your Data Science journey. But this will definitely make you ready to dive into reading some code and understanding what exactly that “<em>pd</em>” notation is doing at places.</p><h3>Why do we need Pandas?</h3><p>Well, <em>because Pandas are essential for the survival of the bamboo forests of China</em>(BBC and various other sources have laid out the importance of these beautiful creatures which are running towards extinction). Wow! You’re already loving Pandas! <br>Talking about the Pandas library for Python, it has become the standard for data analysis and modelling in Python. Unless you are using R(no love lost there yet), you will need to rely on Pandas for everything-data.</p><p>Pandas comes with the following <strong>advantages</strong> which has made it the de facto standard in data analysis with Python:</p><ul><li><em>Data Frame</em></li><li><em>Easy to read and write data in many tabular formats(CSV, Excel and even SQL)</em></li><li><em>Dealing with missing data</em></li><li><em>Easy to reshape data</em></li><li><em>Easy slicing and jumbling operations</em></li><li><em>The library has been writen in C which gives it a performance boost<br>. . . and many more!</em></li></ul><h3><strong>How to install Pandas?</strong></h3><p>Refer the official <a href="https://pandas.pydata.org/pandas-docs/stable/install.html">Pandas documentation for installation notes</a>. I promise it’s really easy to setup and would probably only take one line of code execution.</p><p>The standard notation of importing the pandas library is:</p><pre>import pandas as pd</pre><h3><strong>Importing Data</strong></h3><p>There are several types of data file formats you can load in as a Pandas <em>DataFrame</em>. There are specific formats to load the different types of data which has the general format of:</p><pre>my_data = pd.read_csv(‘ __link to data file here with .csv extension__ ‘)</pre><p>Most of the times we’ll be dealing with CSV(<em>Comma-separated values</em>) type of files, so this notation should suffice. CSV files are favored over XLS cause the Excel files have some formatting problems which can get messy at times. We don’t want to deal with that sort of situation right? Like it’s 2018!<br>Pandas support many other file loading services which can be found from the official documentation(<a href="http://pandas.pydata.org/pandas-docs/stable/io.html">link</a>).</p><p>We’ve used the term DataFrame in this article. There are actually twokinds of objects that Pandas provides us with:</p><h4><strong>DataFrame:</strong></h4><p>A <em>table format</em>(can be visualized as an SQL table or Excel table)<br>The notation for constructing a dataframe is:</p><pre>my_frame = pd.DataFrame({‘col_1’:[val_1,val_2,val_3], ‘col_2’:[val_4,val_5,val_6]}, index=[‘index_1’, ‘index_2’, ‘index_3’])</pre><p>The above code would create a 3*2 sized DataFrame called <em>my_frame</em>.<br><strong>You can look at DataFrames as Python Dictionaries who’s keys are the column names and values are the list of values in a column.</strong><br>The additional parameter in the DataFrame assigns a specific index to our data. This however, can be ignored for now as we’ll be totally fine with the general auto indexing starting from 1.</p><h4>Series:</h4><p>An <em>array of values</em>. Just like a list in Python.</p><pre>my_list = pd.Series([val_1, val_2, val_3], index=[index_1, index_2, index_3], name=’Column_name’) </pre><p><em>Viola! This one was easy!<br></em>A series is visualized as a column of a DataFrame. So it has the required attributes. Again, we can skip the indexing part but we should keep the name part in mind. (In case you’re adding this column to your DataFrame, you’ll want a name for the new column)</p><p>The shape of the DataFrame that you loaded can be described using the following line of code:</p><pre>print(my_dataframe.shape)</pre><p>This will print out something like: (1000,10)<br>This means that your DataFrame has 1000 rows of data and 10 columns. Neat!</p><p>You can also use the “<em>head()</em>” function to print out the first 5 rows of your DataFrame(just to get a general idea of the kind of data or maybe the kind of values your columns contain).</p><pre>my_dataframe.head()</pre><p>On the flip side, you can store your modified DataFrame into various formats too.</p><pre>my_dataframe.to_csv(“ __name of file with .csv extension__ “)</pre><p>And your file would be saved to your working directory with all the data in your DataFrame.</p><blockquote>Hope everything’s been clear till now. These are the basic things we do when we perform an analysis- Loading and Reading the Data, seeing what we’re dealing with. Moving on!</blockquote><h4>Selecting, Slice and various other data formatting operations:</h4><p>Most of the select operations on DataFrame are very similar to the ones we perform on native python objects like Lists and Dictionaries.<br>An entire column can be accessed in a following way using the dot notation:</p><pre>my_data.column_1<br>#or<br>my_data[‘column_1’]</pre><p>Furthermore, in case we need a specific row of data from the selected column, we can use indexing in a similar way to select that specific row:</p><pre>my_data[‘column_1’][5]<br>#Remember that DataFrames follow the zero indexing format</pre><p>We can also use the <strong>iloc</strong> operator to slice over the dataset purely based on indexes, i.e., we will we using the column name’s index to select the column and row’s index for that row.</p><pre>my_data.iloc[:,0]<br>#This would select all the rows from the column index 0(1st column). #Just “:” represents “everything”.</pre><pre>#Or to select the first 3 rows: <br>my_data.iloc[:3,0]</pre><p><strong>It is to be noted that when we use the “0:4” format, the number to the left represents the index from which the slicing begins and the number to the right represents the index till which the slicing occurs, i.e., the index at the right won’t be selected. This notation also worked in the slicing operations in Python. Nothing to worry about!</strong></p><p>We can also pass a list to select specific columns than slice in an orderly fashion:</p><pre> my_data.iloc[[0,5,6,8],0]</pre><p>It is best to explore all your options. Tweak with the function more and more to test it’s capabilities and uses.</p><p>Now, the most important selection feature that we MUST remember is the <strong>conditional select</strong>. In many scenarios, conditional select can save the day and a considerable amount of time. <em>It acts a lot like the “WHERE” clause in SQL</em>. <br>In these situations, iloc’s brother “<strong>loc</strong>” comes into the picture. Just like iloc supported integer based indexing, <em>loc can access data based on labels or a boolean array passed to it</em>.</p><pre>my_data.column_1 == some_numeric_value</pre><pre>#This would return a Series of boolean data based on wether the condition was evaluated as true or not. We can then pass this Series to the loc function to conditionally pick all the rows who’s index evaluated to be TRUE for the condition</pre><pre>my_data.loc[my_data.column_1 == some_numeric_value]</pre><p>Do go through the official <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.loc.html">Pandas documentation</a> of the loc operator for a more comprehensive understanding: <br>(Don’t worry about iloc cause what you read was pretty much it)</p><p>You may also scroll through the official documentation related to <a href="https://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-integer">Indexing and Selecting Data in Pandas</a>.</p><p>Some really useful functions in Pandas for summarizing your data:</p><pre>my_data.head()<br>#Prints out the first five rows of your DataFrame</pre><pre>my_data.column_name.describe()<br>#Prints out some important statistical values like count, mean, max etc of a specific column. In case the column containts String values, it will print the count, freq and top etc</pre><pre>my_data.column_name.mean()<br>#You get it</pre><pre>my_data.column_name.unique()<br>#If the column contains String values, this function will print out all the unique values present in that column</pre><p>These are some of the most frequently used summary functions on the DataFrame. There are more of these which are not used as frequently as these. Do refer the documentation for more on the <a href="https://pandas.pydata.org/pandas-docs/stable/basics.html">Summary functions</a>.</p><h3>Handling Missing Data</h3><p>Often our DataFrame will have missing data in it. These are fields for which no data has been described. This could cause problems in our model’s evaluation or analysis. It is important to resolve all <em>NaN</em> values to some actual value before we continue with other stages. <br>NaN stands for “<em>Not a Number</em>” and the dtype of NaN is set to <em>float64</em>.<br>We have an excellent operator for selecting these data fields with ease called “<strong>isnull</strong>” and conversely, “<strong>notnull</strong>”. These functions will automatically select all the rows of a specified column having any NaN values in it so we can collectively assign some value to them.</p><pre>my_dataframe[my_dataframe.column_name.isnull()]</pre><p>We have an excellent function provided by Pandas to resolve the above issue: <strong>fillna</strong>. We can call the fillna over our DataFrame or selected DataFrame to assign a value to all the NaN values in a specified column.</p><pre>my_data.column_name.fillna(value_to_be_passed)</pre><p>These are some important parts of the documentation that you should go through to understand some further key concepts. There was no point in compressing it as it is better to understand these with proper detailed examples:</p><ul><li><a href="https://pandas.pydata.org/pandas-docs/stable/groupby.html">Group by: split-apply-combine</a></li><li><a href="https://pandas.pydata.org/pandas-docs/stable/merging.html">Merge, join and concatenate</a></li></ul><p>Other than that, it is important to understand the concept of Method Chaining. I can’t stress on the fact that how important method chaining is in phases of Data Analysis. <br>Joost H. van der Linden has made an excellent <a href="https://github.com/joosthvanderlinden/pandas-method-chaining-tutorial">repository</a>, based on the Method Chaining concept with an iPython Notebook that you can run and edit and tinker with. So make sure you check it out on Github.</p><p>An excellent practice dataset that you can tinker with would be the <a href="https://www.kaggle.com/c/titanic">Titanic Survival Problem</a>’s Dataset you can find on <a href="https://www.kaggle.com/">Kaggle</a>. You can find excellent methodologies developed by many people on various sources or you can checkout other Kernels submitted by other users. Almost all of them would follow the necessary data summarizing and cleaning steps initially.</p><p><em>I attempted the problem using R so I could not post my own solution for now. But just in case you want to try out R, this would be a good opportunity. All the phases of analysis would generally be the same but you can expect a more clean and focused environment while working with R. In case you need a tutorial for the problem in R, I’d like to suggest </em><a href="https://www.youtube.com/channel/UCRhUp6SYaJ7zme4Bjwt28DQ"><em>David Langer’s Youtube Channel</em></a><em>. I really loved the flow with which he guides the viewer through all the necessary steps and the working behind the code.</em></p><blockquote>And with this, we wrap up this gentle introduction to sweet Pandas. <br>Use Pandas, Love Pandas, Save Pandas!</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a61dbb622986" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/the-art-of-deduction-featuring-pandas-and-python-a61dbb622986">The Art of Deduction: featuring Pandas and Python</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Capricious Models of Machine Learning]]></title>
            <link>https://medium.com/data-science/the-capricious-models-of-machine-learning-23cd2f36dbbe?source=rss-78d81445e932------2</link>
            <guid isPermaLink="false">https://medium.com/p/23cd2f36dbbe</guid>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[mathematics]]></category>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Raghu Raj Rai ⚡️]]></dc:creator>
            <pubDate>Wed, 20 Jun 2018 14:49:47 GMT</pubDate>
            <atom:updated>2018-06-22T12:33:14.186Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3tAxNGPEol7rW4IhhA2GAA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/uAFjFsMS3YY?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Marten Newhall</a> on <a href="https://unsplash.com/search/photos/funny?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><blockquote>The title speaks volumes on the issue of fitting of models in machine learning. Man, statistics have a very different take on modelling which is not exactly on par with our perception.</blockquote><h3>The Issue:</h3><p>These models in machine learning have a problem of fitting the data well. The two concerns are:</p><p>Overfitting: The <strong>model absorbed the data too well</strong> and fits perfectly over it effectively making the <em>Mean Average Error</em> very small in proportion and almost perfect. Sounds like a bliss, but it’s not. We don’t want our models to fit too perfectly. Datasets, like corrupt politicians, have some dirt hidden in them. They are generally neither linear, nor curved in nature. They have some sort of rough shape to them but it almost never fits a geometrical shape perfectly. The data must have some values which are too different from other values. For example, consider the favorite dataset used in the machine learning community: <em>The housing price dataset</em>. Now suppose that the shape of the dataset is roughly linearly incrementing with size. But there is one specific house whose previous tenants murdered themselves and hence it is classified as “haunted” by the locals. For such a house, the price would be too low. And consider another house which was previously home to some really popular movie star who died in a crash. Such house would have a really good market value. These two kinds of data are the anomalies of our dataset which were recorded at some specific area(or the x-axis) value. We don’t want our model to make inferences from this data cause it’s not necessary that when we are predicting the housing prices in a different community, a similar house with the same area would be haunted or previously owned by a celebrity. We want to minimize our model from fitting these anomalies. And to do that, we need to find a perfect number of leaf nodes(if using a decision tree) or neurons(if using deep learning).</p><p>Underfitting: As the name goes, the model is unable to absorb anything from the data. Hence it is <strong>not learning as much as we’d want it to</strong>. (Dumb model!). To visualize the scenario, you can imagine that the plot of housing prices follows a sort of linear increment up to one point but then it starts rising steeply from that point cause houses from that area onward start becoming more expensive. A good fit would be that our line of regression goes almost straight and then curve upward. A dumb fit would be the line of regression being linear throughout, totally ignoring the rising curve and going straight below it. Or even a straight line going straight from the start and going through the curve.</p><p>The image below visually represents the scenario. The orange line in each case represents the optimal fit for the data(this is what we desire to attain). The blue line in the first image to the left describes how a model underfits. The blue line in the rightmost image describes how a model overfits. The image in the centre describes an optimal fit. We can observe that the fit is not perfectly overlapping the orange line but that’s okay. (That level of error is always expected in data modelling)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*94PW-U1fK7LoDCNKGMMBsw.png" /><figcaption>Source: Scikit-Learn</figcaption></figure><p>To tackle these two major concerns, <em>visualizing the data using plots is important</em>.(Oh, beautiful plots!)</p><p>It is also important that we find the optimal value of nodes so that the model fits optimally with the data.</p><p>This problem becomes highly complex with Neural networks. But thankfully we have many high level libraries(<em>like </em><a href="https://keras.io/"><em>Keras </em></a><em>and </em><a href="http://caffe.berkeleyvision.org/"><em>Caffe</em></a>) to abstract all that work away from us(for most of the general times).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/550/1*GIscS9fYvlX8T7udtwv6lw.png" /><figcaption>Source: <a href="https://www.neuraldesigner.com/">https://www.neuraldesigner.com</a></figcaption></figure><p>Below is a code which consists of a function we use to find the optimal number of nodes in a decision tree to fit a model perfectly. When we run the script, we can observe that it iterates over the number of nodes continuously and prints out the values. We can then use visual inspection to decide the right number of nodes we should use in our decision tree for an optimal fit as we can observe the mean average error is <strong>high in the beginning</strong>(less number of nodes, underfit) and eventually it <strong>goes on decreasing to a point</strong>(optimal point) and then <strong>goes back increasing</strong>(too many number of nodes, overfit).</p><p>Some basic explanation has been provided as comments.</p><pre>#First, import all the libraries. Ok, this is too formal<br>import pandas as pd<br>from sklearn.tree import DecisionTreeRegressor<br>from sklearn.metrics import mean_absolute_error<br>from sklearn.model_selection import train_test_split</pre><pre>#We import the dataset that we will be using. You can import any dataset you want that probably have 5-6 columns with numerical data(preferably something to do with housing prices)</pre><pre>#The data will be imported in the form of a pandas dataframe. Pandas provide an excellent dataframe for all statistical application by formatting all the data in a spreadsheet like table</pre><pre>my_data = pd.read_csv(&#39;*The file destination here without asterisk*&#39;)</pre><pre># print the column names of the dataset as we&#39;ll be calling names in a while<br>print(my_data.columns)</pre><pre>#Now select the columns that we&#39;ll be using for making our decision tree and form a new dataframe with those values<br>interest_data = my_data[&#39;col1&#39;,&#39;col2&#39;,...,&#39;coln&#39;]<br>interest_data.describe()<br>X = interest_data</pre><pre>#Load the column that we need to predict into a new variable called y(maths!)<br>y = my_data.col_name</pre><pre>#Define the data model that we&#39;ll be using, in this case, decision tree regressor<br>data_model = DecisionTreeRegressor()</pre><pre>#Fit the data on the model<br>data_model.fit(X,y)</pre><pre>#It&#39;s not good to use the same values for testing the dataset so we use the train_test_split function by Scikit-Learn to randomly split the dataset into a training set and validation set<br>train_X, val_X, train_y, val_y = train_test_split(X, y,random_state = 0)</pre><pre>#Fitting the data model using the training values<br>data_model.fit(train_X,train_y)</pre><pre>#We use the validation set we splitted earlier to check the accuracy of our model by printing the MAE of the predictions<br>predictions = my_model.predict(val_X)<br>print(mean_absolute_error(val_y, predictions))</pre><pre>#Now, to fit the entire model optimally, we&#39;ll have to change the number of leaf nodes to find the optimal requirement for which the MAE would be the lowest. For this, we develop one function to calculate the MAE</pre><pre>def get_mae(max_leaf_nodes, predictors_train, predictors_val, targ_train, targ_val):<br>    model = DecisionTreeRegressor(max_leaf_nodes=max_leaf_nodes, random_state=0)<br>    model.fit(predictors_train, targ_train)<br>    preds_val = model.predict(predictors_val)<br>    mae = mean_absolute_error(targ_val, preds_val)<br>    return(mae)</pre><pre>#Now take some random values in an array that denote the number of leaf nodes. We will be using these values to test the fit so try out a good amount of them <br>n = [10,50,100,200,400,500,800,1000]</pre><pre>#We define another function to iterate over all the leaf node values we described above and find the optimal nodes for which MAE would be the least.</pre><pre>def optimal_nodes(n, train_X, val_X, train_y, val_y):<br>    on = 1000000 #Just a really high random value<br>    leaf = 0 #The variable which will save the minimum nodes we need<br>    for max_leaf_nodes in n:<br>        my_mae = get_mae(max_leaf_nodes, train_X, val_X, train_y, val_y)<br>        if my_mae &lt; on:<br>            on = my_mae<br>            leaf = max_leaf_nodes<br>        print(&quot;Max leaf nodes: %d  \t\t Mean Absolute Error:  %d&quot; %(max_leaf_nodes, my_mae))<br>    return(leaf)</pre><pre>#By running the above function, we derive the optimal leaf nodes we need in our decision tree to have the least MAE. For that number of nodes, we can say that the model fits optimally.</pre><pre>print(&quot;The optimal number of nodes for our model would be: &quot;+str(optimal_nodes(n, train_X, val_X, train_y, val_y)))</pre><blockquote>In case you need to understand the concepts of fitting better, do refer to this excellent book on Deep Learning written by Ian Goodfellow: <a href="http://www.deeplearningbook.org/">The Deep Learning Book</a>, available for free online.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=23cd2f36dbbe" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/the-capricious-models-of-machine-learning-23cd2f36dbbe">The Capricious Models of Machine Learning</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Round Robin Scheduling Algorithm (Implementation in C)]]></title>
            <link>https://medium.com/cold-brewed/round-robin-scheduling-algorithm-implementation-in-c-d84ec97c6fb7?source=rss-78d81445e932------2</link>
            <guid isPermaLink="false">https://medium.com/p/d84ec97c6fb7</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[productivity]]></category>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[operating-systems]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Raghu Raj Rai ⚡️]]></dc:creator>
            <pubDate>Mon, 19 Mar 2018 09:05:18 GMT</pubDate>
            <atom:updated>2018-03-19T09:05:18.247Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1_XnykOzybp686iLqx4q3A.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/OiiThC8Wf68?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Matthew Smith</a> on <a href="https://unsplash.com/search/photos/schedule?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>I spend a better half of the entire day working on this algorithm.</p><p>I’ve looked at code written by other people that were available online, tried writing my own code, using different data structures and what not!</p><p>At the end, I was able to create a working code of my own from scratch.</p><p>I want it to stay on the internet so that someone might find it in case they are looking for it.</p><p>The code has been commented heavily to help the reader understand better.</p><p>The code is not very efficient and does not focus on space and memory management and usage. (Irony!)</p><p>The main algorithm can be split into 3 main parts and 2 sub-parts of execution:</p><blockquote>Execute the first process in the queue</blockquote><blockquote>Meanwhile, load the other processes that arrive</blockquote><blockquote>Push the current process to the end of the queue and execute the next process</blockquote><blockquote>If a process has finished executing, delete it from the process queue</blockquote><blockquote>Repeat until the number of processes running is 0.</blockquote><p>Please take a look, copy, share, edit.</p><p>Happy Coding!</p><pre>#include&lt;stdio.h&gt;<br>#include&lt;conio.h&gt;<br>#include&lt;stdlib.h&gt;</pre><pre>//Function to return the average wait time of the system<br>float avg_wait_time(int wt[], int n)<br>{<br>    float x = 0;<br>    int i,sum = 0;<br>    for(i=0;i&lt;n;i++)<br>        sum = sum + wt[i];</pre><pre>x = sum * 1.0;<br>    x = x / n;<br>    return x;<br>}</pre><pre>//Function to return the average turnaround time of the system<br>float avg_turnaround_time(int tat[], int n)<br>{<br>    float x = 0;<br>    int i,sum = 0;<br>    for(i=0;i&lt;n;i++)<br>        sum = sum + tat[i];<br>    x = sum * 1.0;<br>    x = x / n;<br>    return x;<br>}</pre><pre>//Function to fill the gantt chart<br>//Index is used as the instance of time in the array and the data number at that index represents the process executing at that time<br>void fill_gantt(int gantt[],int from,int to,int process)<br>{<br>    int i;<br>    for(i=from;i&lt;=to;i++)<br>        gantt[i] = process;<br>}</pre><pre>//After a process has executed it&#39;s burst cycle, the process queue is rearranged<br>//The first process is queued at the end and the next process is to be executed<br>//This function shifts the array elements to 1 position left and attached the first element at the last index<br>void rearrange_process_queue(int pq[],int n,int running_processes)<br>{<br>    int i;<br>    int temp = pq[0];<br>    for(i=0;i&lt;running_processes;i++)<br>    {<br>        pq[i] = pq[i+1];<br>    }<br>    pq[running_processes-1] = temp;<br>}</pre><pre>int main()<br>{<br>  int count,i,j; //Counter variables<br>  int time_quantum,n; //Time quantum and number of processes<br>  int time = 0; //Variable to keep record of time<br>  int t_check =0; //keeps track of the time<br>  FILE *fp;</pre><pre>printf(&quot;\t--------------------------------------------------\n&quot;);<br>  printf(&quot;\t\tROUND ROBIN SCHEDULING ALGORITHM\n&quot;);<br>  printf(&quot;\t--------------------------------------------------\n&quot;);</pre><pre>//Reading data from the file<br>  fp = fopen(&quot;data.txt&quot;, &quot;r&quot;);<br>  if (fp == NULL)<br>    {<br>      printf(&quot;File could not be accessed!\n&quot;);<br>      return 0;<br>    }</pre><pre>fscanf(fp, &quot;%d\n%d&quot; ,&amp;n,&amp;time_quantum);<br>  //Check if the variables are valid<br>  //Time quantum and number of processes must be natural numbers<br>  if(n &lt;= 0 || time_quantum &lt;= 0)<br>  {<br>      printf(&quot;Invalid data!&quot;);<br>      return 0;<br>  }<br>  printf(&quot;The number of processes are set to: %d\nThe time quantum is set to:%d\n&quot; , n,time_quantum);</pre><pre>//Arrays to keep track of states<br>  //at - arrival time, bt - burst time, rt - remaining time, pq - process queue, pflag - denotes wether the process has arrived, tat - turnaround time, wt - wait time<br>  //The index of each array denotes the (Process index - 1) except pq<br>  int at[10],bt[10],rt[10],pq[10],pflag[10],tat[10],wt[10];</pre><pre>//Initially filling all the values as default<br>  for(j=0;j&lt;n;j++)<br>    {<br>        pq[j] = 0;<br>        pflag[j] = 0;<br>    }</pre><pre>//Scanning other data from the files<br>  printf(&quot;The scanned process data is:\n\n&quot;);<br>  printf(&quot;--------------------------------------------------\n&quot;);<br>  printf(&quot;|\tINDEX\t|\tAT\t|\tBT\t|\n&quot;);<br>  for(count=0;count&lt;n;count++)<br>  {<br>      fscanf(fp,&quot;%d\t%d&quot;,&amp;at[count],&amp;bt[count]);<br>      printf(&quot;|\t%d\t|\t%d\t|\t%d\t|\n&quot;,count+1,at[count],bt[count]);<br>      rt[count]=bt[count];<br>      t_check += bt[count];</pre><pre>//Check for invalid data read<br>      if(at[count] &lt; 0 || bt[count] &lt;= 0)<br>      {<br>          printf(&quot;Invalid Data!&quot;);<br>          return 0;<br>      }<br>  }<br>  printf(&quot;--------------------------------------------------\n&quot;);</pre><pre>//The index of the gantt variable would represent the time instance<br>  //The data number at the index would denote the process that was executed at that time<br>  int gantt[200];<br>  //Initially filled with default values<br>  for(i=0;i&lt;200;i++)<br>    gantt[i] = 0;<br>  //current variable is used to keep track of the time from which a new process started execution<br>  int current = 0;</pre><pre>printf(&quot;\nThe order of execution:\n\n&quot;);</pre><pre>//Denotes the number of active process in the process queue<br>  int running_processes = 0;</pre><pre>//Putting process 1 in the process queue for a start<br>    pq[0] = 1;<br>    running_processes = 1;<br>    pflag[0] = 1;<br>    int flag = 0;</pre><pre>//Main loop<br>    while(running_processes!=0)<br>        {<br>        flag = 0; //To represent weather a process has ended execution so it can be removed from the process queue</pre><pre>//Printing status of pq and rt so we can see the changes taking place<br>        printf(&quot;Process queue: &quot;);<br>        for(i=0;i&lt;running_processes;i++)<br>            printf(&quot;%d &quot;,pq[i]);<br>        printf(&quot;\t&quot;);<br>        printf(&quot;Remaining Time: &quot;);<br>        for(i=0;i&lt;n;i++)<br>            printf(&quot;%d &quot;,rt[i]);<br>        printf(&quot;\tRunning processes: %d\n&quot;,running_processes);</pre><pre>//Running the first process in queue(at index 0) in the process queue</pre><pre>//If the remaining time of the process is more than the burst time<br>        if(rt[pq[0]-1]&gt;time_quantum)<br>        {<br>            rt[pq[0]-1] = rt[pq[0]-1] - time_quantum;<br>            time = time + time_quantum;<br>            printf(&quot;Process %d executed for %d bursts till time %d\n&quot;,pq[0],time_quantum,time);<br>            fill_gantt(gantt,current,time,pq[0]);<br>            current = time;<br>        }<br>        //if the remaining time is less than or equal to the burst time<br>        //The process will finish it&#39;s execution and terminate<br>        else<br>        {<br>            time = time + rt[pq[0]-1];<br>            printf(&quot;Process %d executed for %d bursts till time %d\n&quot;,pq[0],rt[pq[0]-1],time);<br>            rt[pq[0]-1] = 0;<br>            flag = 1;<br>            fill_gantt(gantt,current,time,pq[0]);<br>            current = time;<br>            //We&#39;ll fill the turnaround time and wait time of that process now as it has finished it&#39;s execution<br>            //and the data we need is accessible right now<br>            tat[pq[0]-1] = time - at[pq[0]-1];<br>            wt[pq[0]-1] = tat[pq[0]-1] - bt[pq[0]-1];<br>        }</pre><pre>//Loading the processes that arrived during the time that the first process in pq was executing and adding those processes to the process queue<br>        for(i=0;i&lt;n;i++)<br>        {<br>            if(at[i] &lt;= time &amp;&amp; pflag[i]== 0)<br>            {<br>                pq[running_processes] = i+1;<br>                running_processes = running_processes + 1;<br>                pflag[i] = 1;<br>            }<br>        }</pre><pre>//Rearranging the process queue by pushing back all the processes and queuing the first process to the end of the queue<br>        rearrange_process_queue(pq,n,running_processes);</pre><pre>//Check if the running process has finished it&#39;s execution<br>        if(flag == 1)<br>            running_processes = running_processes - 1;</pre><pre>}</pre><pre>printf(&quot;\n\nExecution Data:\n&quot;);<br>   printf(&quot;----------------------------------------------------------------------------------\n&quot;);<br>   printf(&quot;|\tProcess\t|\tAT\t|\tBT\t|\tTAT\t|\tWT\t|\n&quot;);<br>   for(i=0;i&lt;n;i++)<br>   {<br>       printf(&quot;|\t%d\t|\t%d\t|\t%d\t|\t%d\t|\t%d\t|\n&quot;,i+1,at[i],bt[i],tat[i],wt[i]);<br>   }<br>   printf(&quot;----------------------------------------------------------------------------------\n&quot;);</pre><pre>printf(&quot;\n\nAverage Waiting Time= %f\n&quot;,avg_wait_time(wt,n));<br>  printf(&quot;Avg Turnaround Time = %f\n&quot;,avg_turnaround_time(tat,n));</pre><pre>return 0;<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d84ec97c6fb7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/cold-brewed/round-robin-scheduling-algorithm-implementation-in-c-d84ec97c6fb7">Round Robin Scheduling Algorithm (Implementation in C)</a> was originally published in <a href="https://medium.com/cold-brewed">Cold Brewed</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simple Regression in R (involving 2 variables)]]></title>
            <link>https://medium.com/cold-brewed/simple-regression-in-r-involving-2-variables-4892d6dbbe35?source=rss-78d81445e932------2</link>
            <guid isPermaLink="false">https://medium.com/p/4892d6dbbe35</guid>
            <category><![CDATA[statistics]]></category>
            <category><![CDATA[linear-regression]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[mathematics]]></category>
            <category><![CDATA[r-programming]]></category>
            <dc:creator><![CDATA[Raghu Raj Rai ⚡️]]></dc:creator>
            <pubDate>Sat, 10 Mar 2018 20:57:30 GMT</pubDate>
            <atom:updated>2018-03-10T20:57:30.809Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ErgQ_NMwOCW1-kLQkiVqwg.jpeg" /><figcaption><a href="https://unsplash.com/photos/dBI_My696Rk">https://unsplash.com/photos/dBI_My696Rk</a></figcaption></figure><p>This is actually the first tutorial I’ve ever written on the internet.</p><p>I really enjoyed writing this tutorial and plan on writing more.</p><p>So please do comment if you liked it or if you have any suggestions on improving the content.</p><p>The tutorial does not hit the basics of R Programming but rather dives straight to the part where the fun begins. You can learn the basics in an hour on 2 from anywhere, including the official R documentation (CRAN).</p><p>Do speed through topics like: Variable types, Types of Plots, Dataframes, Lists etc.</p><p>The tutorial is written in the form of an R script with comments as I think that is the most interactive way to visualize the content. Make sure you make your own modifications and try tweaks and edits to see the effects it has on your data.</p><p>Feel free to copy the code on R Studio. Use “CTRL+ENTER” on a line of code to execute that line of code.</p><pre>In short: What is Regression? If I have to put it in a way where you won’t have to get into the details of the mathematics involved, then:</pre><pre>Regression defines the strength of relations between 2 or more variables in a data-set. To put it into even more simpler terms, regression is to fit a line through a set of data points on a graph such that the line is optimized to cover as many points as it can or stay close to as many points as it can. This way, we can follow the line to regions where we don’t have any data recorded to predict the data at that point (which will be effectively following the trends in data from the previous points).</pre><pre>You might refer this for a detailed version: <a href="https://www.thebalance.com/what-is-simple-linear-regression-2296697">https://www.thebalance.com/what-is-simple-linear-regression-2296697</a> </pre><p>Here’s the script:</p><pre>#Use help(function-name) to see the description of the function,argument,feature,attribute etc. provided <br>#by the official R documentation<br>#Visit <a href="https://cran.r-project.org/">https://cran.r-project.org</a> for a comprehensive documentation</pre><pre>#Go on executing each line of code by bringing the pointer anywhere on the line and pressing &quot;Ctrl+Enter&quot;<br>#Try changing values and variables to see the changes in effect.</pre><pre># by - Raghu_Raj_Rai &gt; <a href="/service/mailto:raidestro@gmail.com">raidestro@gmail.com</a></pre><pre>#Scatter Plots - x vs y type of plot - plot() function<br>#Loading the women dataset for height and weight data<br>women</pre><pre>#Loading the 2 data columns in x and y for short names while using the terms<br>x &lt;- women$height<br>y &lt;- women$weight</pre><pre>#And here a basic plot of x on y and then y on x (General format of the function is plot(x,y))<br>plot(x,y)<br>plot(y,x)</pre><pre>#Read the description of the plot() function provided in the R documentation to know the additional features of the function and parameters<br>help(&quot;plot&quot;)</pre><pre>#Using additional parameters in the function. pch defines the shape of plots on the graph. Use help for more<br>help(pch)<br>plot(x,y,xlab = &quot;Height&quot;,ylab = &quot;Weight&quot;,main = &quot;Relation between Heights and Weights&quot;,col=&quot;Blue&quot;,pch=20)</pre><pre>#Basics finished here. Coming to Linear Regression and Multiple Regression model in the graph<br>#The data is preloaded in the x and y variables which we&#39;ll be using now, but just to be clear.<br>#loading data set into variables<br>x &lt;- women$height<br>y &lt;- women$weight<br>typeof(x)</pre><pre>#Constructing the relation between the 2 variables to form the relation between them<br>#This defines the parameters of the regression line that we&#39;ll pull over the data<br>relation &lt;- lm(y~x)<br>#Use summary to obtain the coefficients of the regression lines<br>summary(relation)</pre><pre>#Creating a plot with the regression line overlay<br>plot(x,y,xlab = &quot;Height&quot;,ylab = &quot;Weight&quot;,main = &quot;Relation between Heights and Weights&quot;,col=&quot;Blue&quot;,pch=20,abline(relation))</pre><pre>#Load the data in the following manner to use it as input for &quot;Predict&quot;. We can&#39;t fit the data directly as the predict function will not recognize wether it&#39;s the x feature or y feature that we want to predict<br>a &lt;- data.frame(x=70)<br>prediction &lt;- predict(relation,a)<br>#So now we know that if a women has a height of 70, the weight as per the dataset provided would be roughly 154<br>prediction</pre><pre>#Points can be overlayed over a previously drawn plot using points() function. Check description<br>help(&quot;points&quot;)</pre><pre>#Plot the point on the graph to see wether the predicted data fits on the graph. <br>#In this case, it will match a previous plot cause we used an already provided data for prediction<br>points(70,prediction,col=&quot;Red&quot;,pch=24)</pre><pre>#The general form of the regression equation is y = ax+b(y-response var,x-predictor var)<br>#The above example refers to Simple Regression where only 2 variables are involved and we have to obtain a direct relation on them.<br>#Check the values of relation to see it&#39;s intercept and slope<br>relation</pre><pre>#Multiple Regression - form: y = a + b1.x1 + b2.x2 + . . . . + bn.xn - ( y - response variable , a,b1,b2,bn - coefficients , x1,x2,xn - predictor variables)<br>#General methodology of execution remains the same except the way some functions are used.</pre><pre>#Loading a different dataset now as we&#39;ll need more than 2 variables<br>data()<br>#Loading presidents dataset for our experimentation<br>presidents<br>#We notice that we have some &quot;NA&quot; in our dataset which might represent that the data related to that particular value might not have been recorded<br>#We resolve this issue by replacing all &quot;NA&quot;s in our dataset with an average value of 50.<br>summary(presidents)<br>#We copy the presidents dataset to our own dataset. Just to keep the workbench clean and organized.<br>my_dataset &lt;- presidents<br>#Now we replace all the NAs with 50 in our dataset. 50 is used as an average value. It could be anything in different cases, even 0.<br>my_dataset[is.na(my_dataset)] &lt;- 50<br>my_dataset</pre><pre>#Creating the relationship model between the attributes using the lm() function<br>#We&#39;ll be using qtr1,qtr2 and qtr3 as the predictor variables and qtr4 as the response variable</pre><p>Will be continuing with Multiple Regression and maybe covering the basics at the end. (lol)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4892d6dbbe35" width="1" height="1" alt=""><hr><p><a href="https://medium.com/cold-brewed/simple-regression-in-r-involving-2-variables-4892d6dbbe35">Simple Regression in R (involving 2 variables)</a> was originally published in <a href="https://medium.com/cold-brewed">Cold Brewed</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>