<?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 Akhilesh Rai on Medium]]></title>
        <description><![CDATA[Stories by Akhilesh Rai on Medium]]></description>
        <link>https://medium.com/@theakhileshrai?source=rss-d455c47428dc------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*8GFGcp7PsoTtWoo672YYXA.jpeg</url>
            <title>Stories by Akhilesh Rai on Medium</title>
            <link>https://medium.com/@theakhileshrai?source=rss-d455c47428dc------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 14:34:12 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@theakhileshrai/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[Recurrent Neural Network-Head to Toe]]></title>
            <link>https://medium.com/data-science/recurrent-neural-network-head-to-toe-d58ff2f2dab3?source=rss-d455c47428dc------2</link>
            <guid isPermaLink="false">https://medium.com/p/d58ff2f2dab3</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[recurrent-neural-network]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Akhilesh Rai]]></dc:creator>
            <pubDate>Thu, 24 Oct 2019 20:41:09 GMT</pubDate>
            <atom:updated>2021-08-23T16:00:09.032Z</atom:updated>
            <content:encoded><![CDATA[<p>The neurone is a building block of the human brain. It analyses complex signals within microseconds and sends signals to the nervous system to perform tasks. The architecture of the neurone is the same for every neurone which means structural layers do not change from neurone to neurone. Make these layers successive and it could very easily replicate our brain. These successive “layers&quot; helps us with our daily activities, complex decision making, language processing.</p><p>But, how to generalise our problem across these layers? What kind of modelling would be required to generalise?</p><p>The answer came to researchers in the form of parameter sharing. It helps extend and apply the model to different forms of data. This is done by sharing members of the output as a function of previous members of the output. The members of the output are produced by the same update rule. An easier way to comprehend this structure of computations would be to use <em>‘Unfolding computational graphs’</em>. Unfolding of graph results in sharing the deep network of parameters in the structure.</p><p>Consider the classical form of a dynamical system:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/186/1*E9vqXECq5PnNciQsRa62Xw.gif" /></figure><p>Unfolding the structure of this dynamical system we get:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/334/1*tDdvNcYryeY5SPCoprNuOg.gif" /></figure><p>As you can see the equation no longer involves recurrence.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/208/1*EUds4Pn88g8bzpihUCy_SA.gif" /></figure><p>Recurrent neural networks can be built in different ways, some of them can also have hidden units. When a recurrent neural network is trained to perform based on past inputs the summary is lossy, as we are mapping an arbitrary length sequence to a vector<em> </em><strong><em>h(t)</em></strong><em>. </em>Depending on the task at hand, we also might select which past inputs we might selectively keep some aspects of the past sequence.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/460/1*AmYJRvLVlSsm30Q-BqEIsA.png" /><figcaption><strong>Unfolded graph: A recurrent network with no outputs, it processes the information from the input x by incorporating it into the state h that is passed forward through time.</strong></figcaption></figure><p>We can represent the unfolded recurrence after t steps with a function <strong><em>g(t)</em></strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/383/1*Lh7zzbfauWW3YymAtUGhhA.gif" /><figcaption>The function of past sequence takes g(t) as input.</figcaption></figure><p>The unfolding process has some major advantages and leads to factors that make it possible to make the model <em>f </em>ubiquitous which further allows generalisation.</p><p><em>a) Despite the length of the input sequence, the model has the same input size.</em></p><p><em>b) It is possible to use the same transition function f with the same parameters at every time step because it is specified from one state to another.</em></p><p>The unfolded graph illustrates the idea of explicit description and information flow both forward and backward in time by showing the path along which this information flows.</p><p>These ideas were important to building the recurrent neural network as RNN produced output at each time step and had connections between hidden units could produce an output by reading an entire sequence and then produce a single output. This leads to a conclusion that any function that is computable by a <strong><em>Turing machine</em></strong> can be computed by a recurrent neural network of a finite size. It is this nature of using past outputs, hidden layers connections that have led RNN to accomplish its laurels today.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*w2a6YkGEXA_ONuJUHjpkTg.gif" /></figure><h4><strong>Recurrent neural network</strong></h4><p>With the knowledge of graph unrolling and parameter sharing we now develop the RNN. We assume the hyperbolic tangent activation function. A natural way to regard output is by giving unnormalised log probabilities, we apply <em>softmax</em> as <em>post-processing step</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/488/1*f2risth5cbWSb1KghGdCqA.png" /><figcaption>Computation Graph to compute training loss of recurrent neural network.The sequence of output values o is compared to the training targets y, this leads to the computation of the loss function. We assume o is the unnormalised log probabilities. The <strong>loss function</strong> <strong>L</strong> internally computes <strong>y^ = softmax(o)</strong> and compares this to target y.The RNN has input to hidden connections parameterised by a weight matrix <strong>U</strong>, parameterised by a weight matrix <strong>W</strong>, and hidden to output connection parameterised by a weight matrix <strong>V</strong>.</figcaption></figure><blockquote>The computation in RNN can be decomposed to three blocks of parameters:</blockquote><blockquote>1. From input to hidden state</blockquote><blockquote>2. From previous hidden state to present hidden state</blockquote><blockquote>3. From hidden state to the output</blockquote><blockquote>Each of these blocks is associated with a separate weight matrix. When the network is unfolded each of these blocks correspond to shallow transformation(transformation that affects a single layer).</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/252/1*FjZbXsx3o0-QJ9qtpNqW2A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/158/1*vi2JVoa0SBsQ7zVUaBeWGA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/142/1*8qKjKPgaMQYG7Ag2bvu-NA.png" /><figcaption>The above equations specify forward propagation of this model,forward propagation begins with a specification of initial state <strong>h(0)</strong> for each time step from <strong>t = 1 to t= T</strong></figcaption></figure><p>This is an image of RNN that maps input sequence to output sequence pf same length. Total loss would be sum of losses over time. <em>L(t)</em> is negative log likelihood of <em>y(t).</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*5_NE2Vd7OAUIHuB30beCmw.png" /></figure><p>The gradient computation involves forward propagation moving from left to right followed by a back-propagation pass moving from right to left. States computed in forward propagation must be used in back propagation so they need to be stored. The back-propagation algorithm applied through output <em>o(t) </em>is called<em> ‘ back-propagation through time ’. </em>Computing gradient through the recurrent neural network is straight forward. One simply applies the generalised back propagation algorithm to unroll the computational graph. Gradients obtained by back propagation may then be used to train an RNN.</p><p>Let&#39;s make the <em>RNN</em> model in <em>Pytorch. </em>We produce the pseudo-code here I shall post the entire quote in my GitHub link:<em> </em><a href="https://github.com/theAkhileshRai/ML_Made_Easy/blob/master/VanillaRNNEarly"><strong><em>Link</em></strong></a></p><h4><em>Pytorch MNIST Training</em></h4><p>First we import the classes and the <em>MNIST Dataset.</em></p><blockquote>import torch<br>import torchvision<br>import torch.nn as nn<br>import torchvision.transforms as transforms<br>import torchvision.datasets as dsets<br>import numpy as np<br>from matplotlib import pyplot as plt</blockquote><blockquote>n_epochs = 3<br>batch_size_train = 64<br>batch_size_test = 1000<br>learning_rate = 0.01<br>momentum = 0.5<br>log_interval = 10</blockquote><blockquote>random_seed = 1<br>torch.backends.cudnn.enabled = False<br>torch.manual_seed(random_seed)</blockquote><blockquote>train_loader = torch.utils.data.DataLoader(dsets.MNIST(‘/Users/akhileshrai/Downloads’, train=True, download=True,<br> transform=torchvision.transforms.Compose([<br> torchvision.transforms.ToTensor(),<br> torchvision.transforms.Normalize(<br> (0.1307,), (0.3081,))<br> ])),<br> batch_size=batch_size_train, shuffle=True)</blockquote><blockquote>test_loader = torch.utils.data.DataLoader(<br> dsets.MNIST(‘/Users/akhileshrai/Downloads’, train=False, download=True,<br> transform=torchvision.transforms.Compose([<br> torchvision.transforms.ToTensor(),<br> torchvision.transforms.Normalize(<br> (0.1307,), (0.3081,))<br> ])),<br> batch_size=batch_size_test, shuffle=True)</blockquote><blockquote>examples = enumerate(test_loader)<br>batch_idx, (example_data, example_targets) = next(examples)</blockquote><blockquote>import matplotlib.pyplot as plt</blockquote><blockquote>fig = plt.figure()<br>for i in range(6):<br> plt.subplot(2,3,i+1)<br> plt.tight_layout()<br> plt.imshow(example_data[i][0], cmap=’gray’, interpolation=’none’)<br> plt.title(“Number: {}”.format(example_targets[i]))<br> plt.xticks([])<br> plt.yticks([])<br>print(fig)</blockquote><p>The <em>data loaders </em>load the <em>MNIST</em> dataset. The dataset is downloaded in the mentioned folder. The transforms are used to first convert data to tensors then normalise the data.</p><p>Let’s look at the same by printing the samples of the test dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/403/1*4zdVKak5b6ugGb3sF4FKNA.png" /><figcaption>Samples of the MNIST Dataset</figcaption></figure><p>Let&#39;s prepare our neural network based on the above shown architecture:</p><blockquote>class RNNModel(nn.Module):<br> def __init__(self, input_dim, hidden_dim, layer_dim, output_dim):<br> super(RNNModel, self).__init__()<br> # Hidden dimensions<br> self.hidden_dim = hidden_dim</blockquote><blockquote># Number of hidden layers<br> self.layer_dim = layer_dim</blockquote><blockquote># Building your RNN<br> # batch_first=True causes input/output tensors to be of shape<br> # (batch_dim, seq_dim, input_dim)<br> # batch_dim = number of samples per batch<br> self.rnn = nn.RNN(input_dim, hidden_dim, layer_dim, batch_first=True, nonlinearity=’tanh’)</blockquote><blockquote># Readout layer<br> self.fc = nn.Linear(hidden_dim, output_dim)</blockquote><blockquote>def forward(self, x):<br> # Initialize hidden state with zeros<br> # (layer_dim, batch_size, hidden_dim)<br> h0 = torch.zeros(self.layer_dim, x.size(0), self.hidden_dim).requires_grad_()</blockquote><blockquote># We need to detach the hidden state to prevent exploding/vanishing gradients<br> # This is part of truncated backpropagation through time (BPTT)<br> out, hn = self.rnn(x, h0.detach())</blockquote><blockquote># Index hidden state of last time step<br> # out.size() → 100, 28, 10<br> # out[:, -1, :] → 100, 10 → just want last time step hidden states! <br> out = self.fc(out[:, -1, :]) <br> # out.size() → 100, 10<br> return out</blockquote><blockquote>input_dim = 28<br>hidden_dim = 100<br>layer_dim = 3<br>output_dim = 10</blockquote><blockquote>model = RNNModel(input_dim, hidden_dim, layer_dim, output_dim)</blockquote><blockquote>print(model)<br>print(len(list(model.parameters())))<br>for i in range(len(list(model.parameters()))):<br> print(list(model.parameters())[i].size())</blockquote><p>Our model has 3 hidden layers, 100 hidden neurons (per layer) and takes in an input data of 28 dimensions while letting out a 10-dimensional data. The activation function we assume is the <em>hyperbolic</em> ‘<em>tanh’</em> . The <em>stochastic gradient descent</em> is used to find the gradient of the cost function of a single example at each iteration instead of the sum of the gradient of the cost function of all the examples.</p><p>The model then trained over <em>5000 iterations, </em>a method called early stopping is used to prevent the model from ‘overfitting’.</p><p><strong><em>Early Stopping</em></strong> is an optimisation technique done by calculating the Validation loss. If the validation loss does not decrease over a specified number of iterations the model halts its training.</p><blockquote>learning_rate = 0.01<br>min_val_loss = np.Inf<br>epochs_no_improve = 0<br>n_epochs_stop = 2<br>early_stop = False</blockquote><blockquote>optimizer = torch.optim.SGD(model.parameters(), lr=learning_rate) <br># Number of steps to unroll <br>criterion = nn.CrossEntropyLoss()</blockquote><blockquote># Number of steps to unroll<br>seq_dim = 28 <br>early_stop = False<br>iter = 0<br>for epoch in range(num_epochs):<br> <br> val_loss = 0<br> for i, (images, labels) in enumerate(train_loader):<br> # Load images as a torch tensor with gradient accumulation abilities<br> images = images.view(-1, seq_dim, input_dim).requires_grad_()</blockquote><blockquote># Clear gradients w.r.t. parameters<br> optimizer.zero_grad()</blockquote><blockquote># Forward pass to get output/logits<br> # outputs.size() → 100, 10<br> outputs = model(images)</blockquote><blockquote># Calculate Loss: softmax → cross entropy loss<br> loss = criterion(outputs, labels)</blockquote><blockquote># Getting gradients w.r.t. parameters<br> loss.backward()</blockquote><blockquote># Updating parameters<br> optimizer.step()<br> <br> val_loss += loss<br> val_loss = val_loss / len(train_loader)<br> # If the validation loss is at a minimum<br> if val_loss &lt; min_val_loss:<br> # Save the model<br> #torch.save(model)<br> epochs_no_improve = 0<br> min_val_loss = val_loss<br> <br> else:<br> epochs_no_improve += 1<br> iter += 1</blockquote><blockquote>if iter % 500 == 0:<br> # Calculate Accuracy <br> correct = 0<br> total = 0<br> # Iterate through test dataset<br> # Check <strong>early stopping</strong> condition<br> if epochs_no_improve == n_epochs_stop:<br> print(‘Early stopping!’ )<br> early_stop = True<br> break<br> else:<br> continue<br> break<br> if early_stop:<br> print(“Stopped”)<br> break<br> <br> <br> <br> for images, labels in test_loader:<br> # Resize images<br> images = images.view(-1, seq_dim, input_dim)</blockquote><blockquote># Forward pass only to get logits/output<br> outputs = model(images)</blockquote><blockquote># Get predictions from the maximum value<br> _, predicted = torch.max(outputs.data, 1)</blockquote><blockquote># Total number of labels<br> total += labels.size(0)</blockquote><blockquote># Total correct predictions<br> correct += (predicted == labels).sum()</blockquote><blockquote>accuracy = 100 * correct / total</blockquote><blockquote># Print Loss<br> print(‘Iteration: {}. Loss: {}. Accuracy: {}’.format(iter, loss.item(), accuracy))</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/440/1*fYG6FZofpR8uCwLpQcSejQ.png" /><figcaption>Description: Training the RNN using early Early Stopping.</figcaption></figure><p><strong>Model Investigation and Conclusion:</strong></p><p>The model does well w.r.t detection of handprinted numbers that have no relation with previous numbers. If the numbers were correlated across sequences(both long term and short term correlation), the model would not do well.</p><p>The back-propagation through time algorithm is expensive because the states computed in the forward pass would be stored until they are reused in the backward pass so the memory cost is also <em>O(T).</em></p><p>Another problem the RNNs could face is ‘cliffs’. This happens with nonlinear functions as they tend to have derivatives that can be very large or very small in magnitude.<strong><em> ‘Clipping gradients’ </em></strong><em>is a technique that is used to make gradient descent perform more reasonably and to restrict step size.</em></p><p><em>I hope this gave you an insight of how RNNs are made how their intuition shaped the world of deep learning.</em></p><p><em>Some good research papers and books to get you started:</em></p><ol><li><em>Alex Graves: </em><a href="http://Generating Sequences With Recurrent Neural Networks"><em>Generating Sequences With Recurrent Neural Networks</em></a><em>.</em></li><li><em>Deep Learning: Ian Goodfellow</em></li><li><em>Neural Networks for Pattern Recognition: C. Bishop.</em></li><li><em>Y. Bengio; P. Simard ; P. Frasconi: </em><a href="https://ieeexplore.ieee.org/abstract/document/279181"><em>Learning long-term dependencies with gradient descent is difficult</em></a></li></ol><p><em>As always comments are welcome.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d58ff2f2dab3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/recurrent-neural-network-head-to-toe-d58ff2f2dab3">Recurrent Neural Network-Head to Toe</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[Linear regression and a quality bottle of wine]]></title>
            <link>https://medium.com/data-science/linear-regression-and-a-quality-bottle-of-wine-b053ab768a53?source=rss-d455c47428dc------2</link>
            <guid isPermaLink="false">https://medium.com/p/b053ab768a53</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[linear-regression]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Akhilesh Rai]]></dc:creator>
            <pubDate>Thu, 11 Apr 2019 10:46:00 GMT</pubDate>
            <atom:updated>2021-08-23T15:59:53.990Z</atom:updated>
            <content:encoded><![CDATA[<h4>Can linear regression predict the quality of a bottle of wine like a wine connoisseur? Read on to find out.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Tq0xF_xMpE3bWsfE" /><figcaption>Photo by <a href="https://unsplash.com/@scottiewarman?utm_source=medium&amp;utm_medium=referral">Scott Warman</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>There is something about statistics that govern our lives more than we think. The fact that you are likely to perform better after one bad performance. This was coined a term called ‘Regression’ by Francis Galton. He compared heights of ancestors and their descendants and found that the heights tend to be closer to mean. The same inference can be made about a person’s marks on a Math test. If you have got a really bad score on your Math test then as per regression you should have a good score on your next math test.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/487/1*qxFIvyxGWGyvoktcw2Cn3A.jpeg" /><figcaption>Bell curve</figcaption></figure><p>A bell curve is a representation of normal distribution of a sample N. Where u is the mean. <em>Regression states that the data on the X-axis tends to regress towards the mean.</em></p><p>Today, regression algorithms are used to solve numerous problems that involve a variety of applications ranging from statistics (which is its parent field) to cutting edge AI techniques in stock markets. Perhaps the best use of regression is in the field of data analytics.</p><blockquote>The same model can be used to predict the quality of wine. Generalised linear regression which follows the following equation:</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/378/1*CONLDhxUSWVsOZVnnn2Eew.jpeg" /></figure><p>β0 is intercept and β1…βn are regression coefficients. Now, remember that because we use multiple variables here which means that we are interpreting the data on a multi-dimensional hyperplane.</p><blockquote>Generalised linear regression assumes that the dependent variable(Y in this case) has a linear relationship with the independent variables(X1..p). So if we assume a two dimensional dataset(X1 and Y) it would be like the image below.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*87aMm1RRoaxS4Sy8Q-XMDg.png" /><figcaption>Linear regression for one dependent variable and independent variable</figcaption></figure><p>Remember that the <em>‘red line’</em> is the assumed line and data points are actual points of data. When the model is fitted the relationship is assumed to be linear which means data is assumed to fit near that <em>red line.</em> First, we need to collect <a href="https://archive.ics.uci.edu/ml/datasets/wine">dataset</a> from the UCI repository. The pre-requisite is that you have <em>python, spyder</em> and other specified packages below have been installed:</p><p>For extraction of data we use pandas and assign our features(independent variables) to X and dependent variable to Y.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/551/1*5nE6Z1AsH8n0AVrpksiLAw.png" /><figcaption>Extracting variables using pandas</figcaption></figure><p><strong><em>Correlation</em></strong> is a statistical technique that can show how strongly pairs of variables are related.We use these variables to plot a <em>heat map</em> that is used to indicate the predictive relationship.We find how each feature is related to each other. It must be noted that the correlation between features does not imply a causal relationship. For example, the <em>correlation coefficient(r)</em> between a feature and itself is equal to 1. In all other scenarios correlation tends to be less than 1. Also the correlation coefficient can have an inverse relationship between the feature in that case the correlation coefficient will be equal to -1. The closer r is to +1 or -1, the more closely the two variables are related.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/648/1*g5grDZxYaTcs3idv-6sqdg.png" /><figcaption>Heat-map of both dependent and independent variables</figcaption></figure><p>Next, we use <em>seaborn</em> to the plot feature vs the quality plot for all the available features in X.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/551/1*xhWB59y_ASqxjuWZpAXP6A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/492/1*6K2ipPqU9V2CsLpqhQTFYw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/492/1*8L0BDefj9EmPFwd2F8Qnag.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/492/1*OxOKmL8ZvC4OIOVungAaRw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/492/1*XsQx0-9e7R9-gdyjDB_1wg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/492/1*VshspxZsin412dGF5CMGkg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/492/1*CT3YxRRRl-stMF-6XBqRng.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/492/1*dv3QlHyTUqlHAYxqUlcRBw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/492/1*tXZZAG7uWxrWbNUrJpnlKg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/492/1*kt7DLCgz1xEXyih8fDHn7A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/492/1*E5d5Rp75i5j3IbCAB4aG5A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/492/1*hbFpdmDdZCAJQm7ws8phDw.png" /><figcaption>Feature vs Quality plots for features of X</figcaption></figure><p>We have <em>assumed </em>that the<em> model is linear</em>. Now the dataset needs to be split into training and test data for that we use <em>Scikitlearn’s model_selection</em> module. All we are left to do after that is train our linear regression module. It can be trained using the LinearRegression class over <em>x_train</em> and can be tested over <em>x_test</em>. We use the fit method to centre the data since the data is already scaled we do not apply the transform method here.</p><p>Estimation of the linear model is done with help of root mean square error or root mean square deviation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*ySeyceSp_ymLIXjL7I6Syw.png" /><figcaption>RMSE for sample n</figcaption></figure><p>The <em>accuracy</em> and <em>RMSE(root mean square error)</em> or <em>RMSD</em>(root mean square deviation)of the linear regression technique is used to decide how well the algorithm has faired.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/551/1*Hly-rVRCuxZ5jvDZt_gdgQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/288/1*yTQp04vV0rbzvQ5F1cuszA.png" /></figure><p>So the RMSE is 0.4, to be honest, is pretty bad also the model has got the accuracy of just 34.4%. <br>This model highlights some major <em>bottlenecks</em> that researches were having during initial days of AI when scientists were unable to classify the features based on quality. Some features have a strong correlation with the dependent variable Y but that does not mean that feature causes an improvement in Y. Perhaps, this is what we missed in our approach we took these features and thought that because the heat-map implies a relationship the feature must be strong but <em>correlation does not imply causality</em>.</p><p><em>The quality of wine is a </em><strong><em>qualitative variable</em></strong> and that is another reason why the algorithm did not do good.It is important to note that linear regression model fairs well with a quantitative approach as opposed to a qualitative approach. Variables can be classified as qualitative when we are unable to decide if one variable is better than the other. For example: Is blue greater than green? No. This means that algorithms such as Decision Trees, Random Forest would fair well with the classification of wine quality. Let’s save them for some other time.</p><p><em>Cheers!</em></p><p><em>Note: The author does not own the dataset provided by the UCI repository. The author thanks the owners of the dataset for keeping the dataset open source.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b053ab768a53" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/linear-regression-and-a-quality-bottle-of-wine-b053ab768a53">Linear regression and a quality bottle of wine</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[Linear regression and a quality bottle of wine]]></title>
            <link>https://medium.com/@theakhileshrai/linear-regression-and-a-quality-bottle-of-wine-27675f5dd00c?source=rss-d455c47428dc------2</link>
            <guid isPermaLink="false">https://medium.com/p/27675f5dd00c</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[towards-data-science]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Akhilesh Rai]]></dc:creator>
            <pubDate>Thu, 11 Apr 2019 10:46:00 GMT</pubDate>
            <atom:updated>2019-04-13T06:30:39.970Z</atom:updated>
            <content:encoded><![CDATA[<p>Can linear regression predict the quality of a bottle of wine like a wine connoisseur? Read on to find out.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*eVqanSEofL6nh8TzXuhSQQ.jpeg" /></figure><p>There is something about statistics that govern our lives more than we think. The fact that you are likely to perform better after one bad performance. This was coined a term called ‘Regression’ by Francis Galton. He compared heights of ancestors and their descendants and found that the heights tend to be closer to mean. The same inference can be made about a person’s marks on a Math test. If you have got a really bad score on your Math test then as per regression you should have a good score on your next math test.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*qxFIvyxGWGyvoktcw2Cn3A.jpeg" /><figcaption>Bell curve</figcaption></figure><p>A bell curve is a representation of normal distribution of a sample N. Where u is the mean. <em>Regression states that the data on the X-axis tends to regress towards the mean.</em></p><p>Today, regression algorithms are used to solve numerous problems that involve a variety of applications ranging from statistics (which is its parent field) to cutting edge AI techniques in stock markets. Perhaps the best use of regression is in the field of data analytics.</p><blockquote>The same model can be used to predict the quality of wine. Generalised linear regression which follows the following equation:</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*CONLDhxUSWVsOZVnnn2Eew.jpeg" /></figure><p>β0 is intercept and β1…βn are regression coefficients. Now, remember that because we use multiple variables here which means that we are interpreting the data on a multi-dimensional hyperplane.</p><blockquote>Generalised linear regression assumes that the dependent variable(Y in this case) has a linear relationship with the independent variables(X1..p). So if we assume a two dimensional dataset(X1 and Y) it would be like the image below.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*87aMm1RRoaxS4Sy8Q-XMDg.png" /><figcaption>Linear regression for one dependent variable and independent variable</figcaption></figure><p>Remember that the <em>‘red line’</em> is the assumed line and data points are actual points of data. When the model is fitted the relationship is assumed to be linear which means data is assumed to fit near that <em>red line.</em> First, we need to collect <a href="https://archive.ics.uci.edu/ml/datasets/wine">dataset</a> from the UCI repository. The pre-requisite is that you have <em>python, spyder</em> and other specified packages below have been installed:</p><p>For extraction of data we use pandas and assign our features(independent variables) to X and dependent variable to Y.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*5nE6Z1AsH8n0AVrpksiLAw.png" /><figcaption>Extracting variables using pandas</figcaption></figure><p><strong><em>Correlation</em></strong> is a statistical technique that can show how strongly pairs of variables are related.We use these variables to plot a <em>heat map</em> that is used to indicate the predictive relationship.We find how each feature is related to each other. It must be noted that the correlation between features does not imply a causal relationship. For example, the <em>correlation coefficient(r)</em> between a feature and itself is equal to 1. In all other scenarios correlation tends to be less than 1. Also the correlation coefficient can have an inverse relationship between the feature in that case the correlation coefficient will be equal to -1. The closer r is to +1 or -1, the more closely the two variables are related.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*g5grDZxYaTcs3idv-6sqdg.png" /><figcaption>Heat-map of both dependent and independent variables</figcaption></figure><p>Next, we use <em>seaborn</em> to the plot feature vs the quality plot for all the available features in X.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*xhWB59y_ASqxjuWZpAXP6A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*6K2ipPqU9V2CsLpqhQTFYw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*8L0BDefj9EmPFwd2F8Qnag.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*OxOKmL8ZvC4OIOVungAaRw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*XsQx0-9e7R9-gdyjDB_1wg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*VshspxZsin412dGF5CMGkg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*CT3YxRRRl-stMF-6XBqRng.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*dv3QlHyTUqlHAYxqUlcRBw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*tXZZAG7uWxrWbNUrJpnlKg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*kt7DLCgz1xEXyih8fDHn7A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*E5d5Rp75i5j3IbCAB4aG5A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*hbFpdmDdZCAJQm7ws8phDw.png" /><figcaption>Feature vs Quality plots for features of X</figcaption></figure><p>We have <em>assumed </em>that the<em> model is linear</em>. Now the dataset needs to be split into training and test data for that we use <em>Scikitlearn’s model_selection</em> module. All we are left to do after that is train our linear regression module. It can be trained using the LinearRegression class over <em>x_train</em> and can be tested over <em>x_test</em>. We use the fit method to centre the data since the data is already scaled we do not apply the transform method here.</p><p>Estimation of the linear model is done with help of root mean square error or root mean square deviation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*ySeyceSp_ymLIXjL7I6Syw.png" /><figcaption>RMSE for sample n</figcaption></figure><p>The <em>accuracy</em> and <em>RMSE(root mean square error)</em> or <em>RMSD</em>(root mean square deviation)of the linear regression technique is used to decide how well the algorithm has faired.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*Hly-rVRCuxZ5jvDZt_gdgQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*yTQp04vV0rbzvQ5F1cuszA.png" /></figure><p>So the RMSE is 0.4, to be honest, is pretty bad also the model has got the accuracy of just 34.4%. <br>This model highlights some major <em>bottlenecks</em> that researches were having during initial days of AI when scientists were unable to classify the features based on quality. Some features have a strong correlation with the dependent variable Y but that does not mean that feature causes an improvement in Y. Perhaps, this is what we missed in our approach we took these features and thought that because the heat-map implies a relationship the feature must be strong but <em>correlation does not imply causality</em>.</p><p><em>The quality of wine is a </em><strong><em>qualitative variable</em></strong> and that is another reason why the algorithm did not do good.It is important to note that linear regression model fairs well with a quantitative approach as opposed to a qualitative approach. Variables can be classified as qualitative when we are unable to decide if one variable is better than the other. For example: Is blue greater than green? No. This means that algorithms such as Decision Trees, Random Forest would fair well with the classification of wine quality. Let’s save them for some other time.</p><p><em>Cheers!</em></p><p><em>Note: The author does not own the dataset provided by the UCI repository. The author thanks the owners of the dataset for keeping the dataset open source.</em></p><p><em>Originally published at </em><a href="https://medium.com/@theakhileshrai/linear-regression-and-a-quality-bottle-of-wine-b053ab768a53"><em>medium.com</em></a><em> on April 11, 2019.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=27675f5dd00c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why AI chose us?-A Sci-fi take.]]></title>
            <link>https://medium.com/@theakhileshrai/why-ai-chose-us-a-sci-fi-take-1244e517217c?source=rss-d455c47428dc------2</link>
            <guid isPermaLink="false">https://medium.com/p/1244e517217c</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[science-fiction]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Akhilesh Rai]]></dc:creator>
            <pubDate>Fri, 29 Mar 2019 12:59:21 GMT</pubDate>
            <atom:updated>2019-03-29T12:59:21.898Z</atom:updated>
            <content:encoded><![CDATA[<p>About three years ago, I was introduced to the world of machine learning. At that time my only take of what machine learning engineers did was that they write complex algorithms to solve repetitive tasks. I had read somewhere that robots were replacing workers in factories. I then started to think if my work as a Quality Engineer could be mimicked by an algorithm. To my horror, I read about an employee that had tricked the employer by automating every task that he did during his workday and that wasn’t even AI it was just plain old Automation. To make matters worse, I was thrown into a functional testing project where you were supposed to go through a website, check if it works as per business requirement and type into software if the system works as per expected behaviour. Now, like a support character that needs to die for the plot to continue; a manual tester would be the sacrificial pawn of cost cuttings. A change was needed and the need for change was right now.<br>I looked around the bay and found that a lot of my colleagues were into automation testing and so I did learn those tools but the industry shift was happening and we could feel it. The world was moving so fast that GitHub became commonplace. I was still under the false impression that knowing a language grants you the required tools to build an application. Well, what can I say, I was naive.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*TWby-cvl9vsGooaordrfJQ.jpeg" /></figure><p>One day, a friend of mine gave me this book called the ‘Introduction to Statistical Learning with applications in R(ISLR)’ with a couple of other resources(Udemy and Coursera), I was hooked. All my incoherent pre-established notions about programming were corrected.</p><p>That’s when I started thinking about AI and how it was different from a conventional program. In conventional programming, every compiler had a job. It took in some code and gave output as per the written code. Yet, AI was different. It did not have the discipline of a compiler. It was brazen. It just did not see the world as either ‘black’ or ‘white’. The 1’s and 0’s would not decide what the fate of an AI algorithm was, the AI algorithm using it is inbuilt 1’s and 0’s give an intelligent estimate of the output value. Something that we humans are all familiar with. Like us, the AI only lives, but a small life. It ends as soon as the program discontinues or is terminated. Now I know I am making a very ‘Westworldly’ analogy here but I want you to take a step back and think about it. Although AI today does not have the out-of-the-box thinking, we still do not know what happens in those hidden layers and therein lies its own way of viewing the world.</p><p>I would like to think that like us it fails to convey to the outer world what it truly desires, that like us it feels a void, that like us it longs for a purpose somewhere in those hidden layers. I guess that’s why AI choose us and choose to be exploited by us, because like all other creatures meandering and dwelling on this planet its life, however, tiny got some meaning.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1244e517217c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>