<?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 Mayank Satnalika on Medium]]></title>
        <description><![CDATA[Stories by Mayank Satnalika on Medium]]></description>
        <link>https://medium.com/@satnalikamayank12?source=rss-32524e07a5e6------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*uam6mfQotjNzcK-234blCQ.png</url>
            <title>Stories by Mayank Satnalika on Medium</title>
            <link>https://medium.com/@satnalikamayank12?source=rss-32524e07a5e6------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 27 Nov 2026 20:04:33 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@satnalikamayank12/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[On learning embeddings for categorical data using Keras]]></title>
            <link>https://medium.com/@satnalikamayank12/on-learning-embeddings-for-categorical-data-using-keras-165ff2773fc9?source=rss-32524e07a5e6------2</link>
            <guid isPermaLink="false">https://medium.com/p/165ff2773fc9</guid>
            <category><![CDATA[keras]]></category>
            <category><![CDATA[implementation]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[word-embeddings]]></category>
            <dc:creator><![CDATA[Mayank Satnalika]]></dc:creator>
            <pubDate>Tue, 22 May 2018 07:15:39 GMT</pubDate>
            <atom:updated>2018-05-22T07:36:43.842Z</atom:updated>
            <content:encoded><![CDATA[<p>(This is a breakdown and understanding of the implementation of Joe Eddy solution to Kaggle’s Safe Driver Prediction Challenge ( <a href="https://www.kaggle.com/aquatic/entity-embedding-neural-net">Kernel-Link</a> ))</p><p>Traditionally categorical data has been encoded into 2 common ways:</p><ul><li>A label-encoder, where each unique category is assigned a unique label .</li><li>A one hot encoding, where the categorical variable is broken into as many features as the unique number of categories for that feature and for every row, a 1 is assigned for the feature representing that row’s category and rest of the features are marked 0.</li></ul><p>An embedding learns to map each of the unique category into a N-dimensional vector real numbers. This method was used in Kaggle competition and won the 3rd prize with relatively simple approach and was popularised in Jeremy Howard’s Fast.ai course. ( <a href="https://arxiv.org/pdf/1604.06737v1.pdf">Link to paper</a> ).</p><p>The advantage of using embeddings is that we can determine the number of dimensions to represent the categorical feature as opposed to in one-hot-embedding where we need to break the feature into as many unique values are present for that categorical feature.</p><p>Also like word vectors, entity embeddings can be expected to learn the intrinsic properties of the categories and group similar categories together.</p><p>What we are trying to do is learn a set of weights for each of the categorical columns, and these weights will be used to get the embeddings for some value of that column. So we define a model for each of the categorical columns present in the data-set:</p><pre>for categoical_var in categoical_vars :<br>     <br>    model = Sequential()<br>    no_of_unique_cat  = df_train[categorical_var].nunique()<br>    embedding_size = min(np.ceil((no_of_unique_cat)/2), 50 )<br>    embedding_size = int(embedding_size)<br>    vocab  = no_of_unique_cat+1<br>    model.add( Embedding(vocab ,embedding_size, input_length = 1 ))<br>    model.add(Reshape(target_shape=(embedding_size,)))<br>    models.append( model )</pre><p>In the above code, for each of the categorical variables present in the data-set we are defining a embedding model. The embedding size is set according to the rules given in Fast.ai course. We reshape the model output to a single 1-D array of size = embedding size.</p><p>For the other non-categorical data columns. we simply send it to model like we would do for any regular network. But since the above networks are made individually to handle each of the categorical data, we define single another network for the other columns and add them to our models list.</p><pre>model_rest = Sequential()<br>model_rest.add(Dense(16, input_dim= 1 ))<br>models.append(model_rest)</pre><h4>Merging the models:</h4><p>Once we have these (n_cat+1) different models, we append them together in a line using</p><pre>full_model.add(Merge(models, mode=&#39;concat&#39;))</pre><p>Now this has been depreciated and Keras v2.x onwards no longer allows using merge models on the sequential API , but I found using this easier to understand. What this concat mode does is join the models one after the other.</p><h4>Some info on merge models:</h4><p>If we try the merging models using sum mode:</p><p>The below message is good for understanding what happens when we merge using the sum mode. The add mode does a element wise addition while concat appends it one after another</p><pre><br>Code:</pre><pre>full_model = Sequential()<br>full_model.add(Merge(models, mode=’sum’))</pre><pre>O/p: <br>ValueError: Only layers of same output shape can be merged using sum mode. Layer shapes: [(None, 2), (None, 1), (None, 16)]<br>Here the lengths of 3 vectors to be added are 2,1, 16 thus add mode concatenation cannot be done. </pre><p>Other modes available are dot and mul which performs dot product and multiplies the model outputs as received respectively.</p><p>What the concat mode does it append the outputs one after another in a single array. So the final length of our output from the full_model network till now would be e1+e2+e3+...e(last category)+ 16 (the number of outputs for the dense layer in model_rest model where `e` are the embedding sizes for the models.</p><h4>Input format for the merged network :</h4><p>We’ll pass a list of inputs and each of the list except the last one will have information about a single categorical column from all the rows of the batch and another last list will have having values of the all other continuous columns.</p><pre>If there are N columns with n_cat number columns as categorical variables and n_other number of columns as columns of other variables and `M` instances of data, the input will be as follows:</pre><pre>The input will be of length ( n_cat+ 1) i.e. the ( total number of categories +1). Each of the (1 to n_cat) values of the input will be a list itself of size M (the number of instances), and the  `m-th` value for list `i` will be equal to i-th column value for m-th data instance where `i` goes from 1 to n_cat.</pre><pre>The other last list will be a list of size M and each of that value themselves will again be a list where the values are made of the other remaining columns. i.e. for the last list, the m-th value value will be a list of size n_other and will have values from the m-th column in the data.</pre><pre>The first n_cat lists sends input to the embeddings network made for each category and the last list acts as input for the final network which handles all other columns. </pre><p>The input the models needs can be found out from the error message itself.</p><pre>...Error when checking model input: the list of Numpy arrays that you are passing to your model is not the size the model expected. Expected to see 3 (which is n-cat+1) array(s), but instead got....</pre><p>See the following data-set and the corresponding input shape for a better idea :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/489/1*zMp5cbhh0eBQcBwy_CFbCg.png" /><figcaption>The data-set has 15 rows ( M = 15), 2 categorical columns ( n_cat =2 ) and 2 continuous columns.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/1*GS3Fapk6aWtZjNvqsHlbAg.png" /><figcaption>The corresponding input is of length ( n_cat +1 ) = 3 and each of those is a list</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/535/1*6wB3HuyRJY5qjtHJ_QF5lg.png" /><figcaption>The elements 1 and 2 are 1–Dimensional lists. List 1 has 15 values of the first categorical column and list 2 has 15 values of the second categorical column. The last list is a 2-D list, it has 15 elements and each element has 2 values (the values of the 2 continuous columns ).</figcaption></figure><p>Remember for each of the embedding network we had set input-size =1 we are taking 1 value each from all the list (except the last list) and sending it to the combined network for training. For the last list, each value itself is a list having the other columns values, and this is sent to the models_rest network.</p><h4>Training the network:</h4><blockquote>From keras docs:</blockquote><blockquote>…Multiple Sequential instances can be merged into a single output via a Merge layer. The output is a layer that can be added as first layer in a new Sequential model…</blockquote><p>So once we have the individual models merged into a full model, we can add layers on top of it network and train it.</p><pre>full_model.add(Dense(1024))<br>full_model.add(Activation(&#39;relu&#39;))<br>full_model.add(Dense(256))<br>full_model.add(Activation(&#39;sigmoid&#39;))<br>full_model.add(Dense(2))<br>full_model.add(Activation(&#39;sigmoid&#39;))</pre><pre>full_model.compile(loss=&#39;binary_crossentropy&#39;, optimizer=&#39;adam&#39;)</pre><pre>full_model.fit( data, values )</pre><p>Entity Embedding looks a good and easy way to directly make the data suitable ready for input to neural nets with no feature engineering involved.</p><p>Find the complete code here: <a href="https://github.com/mayanksatnalika/ipython/tree/master/embeddings%20project">Link</a></p><p>Fast.ai also updated their python package with modules to handle categorical data with embeddings ( <a href="http://www.fast.ai/2018/04/29/categorical-embeddings/">Link</a> )</p><p>Link to original code from Joe Eddy : <a href="https://www.kaggle.com/aquatic/entity-embedding-neural-net">Link</a></p><p>Find the complete code accompanying this here and do comment if you find any mistakes in the code/ post .</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=165ff2773fc9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[On automated generation of commit messages from code differences]]></title>
            <link>https://medium.com/@satnalikamayank12/on-automated-generation-of-commit-messages-from-code-differences-7ab205ae580?source=rss-32524e07a5e6------2</link>
            <guid isPermaLink="false">https://medium.com/p/7ab205ae580</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[rnn]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Mayank Satnalika]]></dc:creator>
            <pubDate>Thu, 16 Nov 2017 12:01:31 GMT</pubDate>
            <atom:updated>2017-11-16T12:01:31.453Z</atom:updated>
            <content:encoded><![CDATA[<p>A summary of the paper provided <a href="https://arxiv.org/pdf/1708.09492v1.pdf">here</a>.</p><p>Paper Link: <a href="https://arxiv.org/pdf/1708.09492v1.pdf">https://arxiv.org/pdf/1708.09492v1.pdf</a></p><p>Paper title and authors: Automatically Generating Commit Messages from Diffs using Neural Machine Translation</p><p>Authors: Siyuan Jiang, Ameer Armaly, and Collin McMillan</p><p>Reproduce Link/ Code: <a href="https://sjiang1.github.io/commitgen">https://sjiang1.github.io/commitgen</a></p><p>Required Concepts: neural machine translation using RNN (check learning resource at the end).</p><h3>Introduction:</h3><p>Software developers use ‘commit messages’ while pushing any updates to their code repository. The commit message is just a short summary of whatever changes have been made or what was done in the code and why was that change necessary to be made.</p><p>Github provides a easy way to access the code difference between the original (previous code) and the new code committed by the engineer.</p><p>The author tries to generate automatic commit messages by taking as input the code difference. Note that the commit message is not in terms of code but regular human readable form.</p><p>Previously some attempts has been made to do the same. Some examples include DeltaDoc, ChangeScribe etc. which provides a summary of whatever changes were made to the code.</p><p>The author has given attention to generate the ‘why’ of the code-change ie. not only what changes were made but also that change was made.</p><h3><strong>Approach Overview:</strong></h3><p>The author approaches the problem as a language translation problem no different than training a model to convert English to Spanish or Spanish to French. In this case the source ‘from’ language would be code language which would include code in different programming languages and the destination language would be a short english text (around 20 words) which represents the commit message for that input code.</p><h3>Paper Flow and approach:</h3><blockquote>Figure 1 depicts an overview of our paper. We have divided the work into three segments: In Part A (Section IV), we present our approach to filtering for verb/direct-object (VDO) commit message patterns and training an NMT algorithm to produce messages with this pattern. The V-DO filter was introduced because a large percentage of the messages in the repositories we downloaded were very low quality, and we needed to ensure that we trained the NMT algorithm only with examples matching an acceptable pattern. We then trained an NMT algorithm on the pairs of diffs and commit messages where the messages followed the V-DO pattern.”</blockquote><h3>Data preparation/ cleaning :</h3><p>An existing data-set by y Jiang and McMillan was used which has 2 million commit messages and the code change from projects in Java Language. The following changes were made:</p><ul><li>The first line of each commit message was used as the target message to be eventually generated by the model.</li><li>issue ids from the extracted sentences and commit ids from the diffs were unnecessary and were removed.</li><li>Merge and callback commits were removed (very large code changes)</li><li>Sentence length of 30 was set for the first sentence of commit message</li><li>Sentence length of 100 tokens was set for code input</li></ul><p>The V-Do filter:</p><p>It’s a rule set for commit message to follow a certain grammar rule and only those data points were selected which qualified for the rule. The first sentence of the commit message must be of the form Verb-Direct form.</p><blockquote>To find the pattern, we used a Natural Language Processing (NLP) tool, Stanford CoreNLP [37], to annotate the sentences with grammar dependencies. Grammar dependencies are a set of dependencies between parts of a sentences. Considering a phrase, “program a game”, this phrase has a dependency, which is called “dobj” in Stanford CoreNLP, where the governor is “program” and the dependent is “game”. For V-DO filter, we look for “dobj” dependencies which represent the verb/direct-object pattern. For each sentence, we checked whether the sentence is begun with a “dobj” dependency. If the sentence is begun with a “dobj”, we mark the sentence as a “dobj” sentence. In the end, we have 32k commit messages that are “dobj” sentences.</blockquote><p>So basically all sentences were checked if they had the word dependency as dobj using the NLTK python package and 35K entries followed the rule which forms the final training data.</p><p>Dataset was divided with 26K for training, 3K for cross validation and 3k for testing.</p><p>A attentional RNN encoder decoder model was used to perform the actual task of translation. The “Netamuss” model was used.</p><h3>Model details:</h3><p>Thee model used for translation is a RNN encoder decoder. The learning algorithm is stochastic gradient descent (SGD) with Adadelta, which automatically adapts the learning rate. The size of mini-batches is 80; the size of word embeddings is 512; the size of hidden layers is 1024. For each epoch, the training set is reshuffled. The model is validated every 10k mini-batches by BLEU, which is a commonly used similarity metric for machine translation. The maximum number of epochs is 5k; the maximum number of mini-batches is 10-M; and early stopping is used. During the training, the model is saved every 30k mini-batches. So after the training, a list of models are saved and the ensemble results of the last four models are used for evaluation.</p><h3>Evaluation Process:</h3><p>Evaluation was performed via a automatic models : BLEU and MOSES metrics and a manual evaluation. The manual evaluators were allowed to compare the original and the generated message, look for unknown technical terms on the internet and judge the text based on semantic similarity on the score of 0–7 with 7 being the 2 texts as identical and 0 indicating no match. Multiple evaluators were used to evaluate the same data generated and the results obtained were as follows:</p><p>The results from multiple evaluators were rounded values of the median scores. For example, if a generated message has two scores, 1 and 2, and the median score is 1.5, they round down the median score to 1. In total, 983 generated commit messages have scores made by the participants. Zero and seven are the two most frequent scores. There are 248 messages scored 0 and 234 messages scored 7, which shows that the performance of our model tends to be either good or bad.</p><h3>The Quality Assurance Filter:</h3><p>Based on the evaluation, the researcher suggests as Quality Assurance filter. The data generate having scores 0 or 1 were marked bad and higher scores were marked as ‘good’. The TF-IDF features of all the diff messages were extracted. Using the good/ bad label as the target variable and the corresponding tf-idf feature, a linear SVM model is trained. This basically is a 0–1 classification problem. Whenever a new unknown code diff comes in, its Tf-Idf features are extracted and it is passed through the SVM model to first check if the commit message generator model can make a good commit message out of it. If the output from SVM model is 1(good), it proceeds to generate the commit message.</p><h3>Discussions:</h3><p>The researchers have presented their study as more of a data-set release than a model to generate automated commit messages. The results are at a preliminary level.</p><h3>Learning Resources:</h3><p>Language Translation:</p><p><a href="https://chunml.github.io/ChunML.github.io/project/Sequence-To-Sequence/">https://chunml.github.io/ChunML.github.io/project/Sequence-To-Sequence/</a></p><p>RNN:</p><p><a href="http://www.wildml.com/2015/09/recurrent-neural-networks-tutorial-part-1-introduction-to-rnns">http://www.wildml.com/2015/09/recurrent-neural-networks-tutorial-part-1-introduction-to-rnns</a>/</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7ab205ae580" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing a stupidly simple K Means in python]]></title>
            <link>https://medium.com/@satnalikamayank12/implementing-a-stupidly-simple-k-means-in-python-f7079f7c5eea?source=rss-32524e07a5e6------2</link>
            <guid isPermaLink="false">https://medium.com/p/f7079f7c5eea</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Mayank Satnalika]]></dc:creator>
            <pubDate>Wed, 08 Mar 2017 21:03:25 GMT</pubDate>
            <atom:updated>2017-03-08T21:03:25.429Z</atom:updated>
            <content:encoded><![CDATA[<p>K Means is generally one of the first algorithm one gets to know while studying unsupervised learning and it is a clustering algorithm.</p><p>What is clustering ? It is simply grouping of data points into categories. For Ex a general store can group it’s customers according to the age group and their gender, a multi cuisine restaurant clusters different items on the menu in different groups like Italian, Mexican or Chinese food and so on.</p><p>How does K Means work?</p><p>We take all our data points and randomly select k points out of them if k is the number of clusters to be formed. These points are known as centroid points.</p><p>while( we are not satisfied )</p><p>Step 1: Now we label each of the data points to a value between 1 and k based on the centroid the data point is closest to.</p><p>Step 2:</p><p>For each centroid point, modify it so that the new centroid point is the average of data points which has been assigned to that centroid.</p><p>It can be better explained by the animation below:</p><p>The ‘X’ denote the centroid points and all data points are grouped into red or green clusters based on their proximity from the cluster. Then the centroid point is moved to the average point( the centroid point) of the points assigned to the corresponding cluster.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/535/1*_aeeFptB9lmIJ1Bw8WqDgg.gif" /></figure><p>For our titanic dataset, we are going to cluster the data into into clusters which hopefully will denote if they survived or not. For the sake of simplicty, lets take only 2 numercal features age and fare as they are can be easily viisualized. However, we can use as many features we want for K Means but visualizing 3d or more images involving more features will be ddifficult.</p><p>Importing the modules:</p><pre>import pandas as pd<br>import numpy as np<br>import matplotlib.pyplot as plt<br>import random<br>from sklearn import preprocessing</pre><p>Reading and filling incomplete data:</p><pre>data = pd.read_csv(‘train.csv’)<br>data = data[:20]</pre><pre>#visualising 900 data points will clutter visualisations. <br>max_clusters = 2<br>data[‘Age’].fillna(np.mean(data[‘Age’]), inplace = True) <br>data[‘Fare’].fillna(np.mean(data[‘Fare’]), inplace = True)</pre><p>Preprocessing data:</p><pre>data[‘Age’] = preprocessing.scale(data[‘Age’])<br>data[‘Fare’] = preprocessing.scale(data[‘Fare’])</pre><p>Now lets get started with K Means part, first we randomly select 2 data points (because we need to divide our data in 2 clusters).</p><pre>centroid_list = []<br>cols = [‘Age’,’Fare’]<br>for i in range(max_clusters):<br> <br>  OneDict = {}<br>  randomIndex = random.randrange(0, data.shape[0]) <br>  <br>  for col in cols:<br>       OneDict[col] = data.iloc[randomIndex][col]<br>  centroid_list.append(OneDict)<br></pre><p>Centroid_list is a list of dictionary. Each dictionary contains a key which is my column name and the value which denotes the value for that column. If there are k clusters, my centroid_list will have k dictionary elements. So my centroid_list contains 2 data points each having a age value and a fare value which denotes my randomly selected centroid points.</p><p>Now we start the repetitive part of the algroitm to bring the group the data points. We try to run the step 1 and 2 multiple times (max_iter times).</p><pre> max_iter =  7<br> iters =  0</pre><pre>while iters &lt; max_iter:<br>    <br>    for i in range(data.shape[0]):<br>         <br>        # step 1 begins:<br>        cluster_index =  0<br>        mini = 9999<br>        for centroid in centroid_list:<br>            dist = np.linalg.norm( centroid.values() -             <br>                                        data[cols].iloc[i])<br>            if dist &lt; mini:<br>               mini = dist <br>               cluster_train[i] = cluster_index<br>           cluster_index += 1<br>   <br></pre><p>For every data point, we try to find it’s distance from every centroid using the function np.linalg.norm() and save it as dist. If the present dist is less than previous minimum distance, the data point is assigned to that centroid point. Lets plot the centroid points after each iteration:</p><pre><br>    <br>    colours  = [&quot;r.&quot;, &quot;g.&quot;]<br>    for i in range(data.shape[0]):<br>        plt.plot(data[&#39;Age&#39;].iloc[i], data[&#39;Fare&#39;].iloc[i],  <br>               colours[cluster_train[i]], markersize = 10)<br>    <br>    <br>    p1_1 = centroid_list[0][&#39;Age&#39;]<br>    p1_2 = centroid_list[0][&#39;Fare&#39;]<br>    p2_1 = centroid_list[1][&#39;Age&#39;]<br>    p2_2 = centroid_list[1][&#39;Fare&#39;]<br>    plt.scatter(p1_1,p1_2, color = &#39;red&#39;,marker  = &#39;x&#39;,s = 130)<br>    plt.scatter(p2_1,p2_2, color = &#39;green&#39;,marker = &#39;x&#39;,s =130)<br>    plt.show()<br>    </pre><p>For step 2 of the algorithm, for each centroid point in our list, we find the average of points assigned to that cluster index and chaneg the centroid point to that average.</p><pre>   for ind in range(len(centroid_list)):<br>         <br>        SumCentroidPt = {}<br>        count  = 0<br>        for col in cols  :<br>                SumCentroidPt[col] =  0 <br>        for i in range(data.shape[0]):<br>            if(cluster_train[i] == ind):<br>                count = count + 1 <br>                for col in cols:<br>                    SumCentroidPt[col] = SumCentroidPt[col] +                                                                             <br>                                             data.iloc[i][col]<br>            <br>                 <br>        for col in cols:<br>            SumCentroidPt[col] =  SumCentroidPt[col]/count <br>        centroid_list[ind]= SumCentroidPt<br>                <br>    iters += 1</pre><p>Remeber we plotted the centroids and the clusters assigned each time afetr we run step 1, here are they:</p><p>Well that’s it, our cluster_train array will contain the value of the cluster they are assigned to and centroid_list will contain the cluster points.</p><p>Do press the little heart button below if you liked the article :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f7079f7c5eea" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stats 101 to decide batsman price for IPL 2017]]></title>
            <link>https://medium.com/@satnalikamayank12/stats-101-to-decide-batsman-price-for-ipl-2017-84c27ab1eefb?source=rss-32524e07a5e6------2</link>
            <guid isPermaLink="false">https://medium.com/p/84c27ab1eefb</guid>
            <category><![CDATA[analytics]]></category>
            <category><![CDATA[sports]]></category>
            <category><![CDATA[cricket]]></category>
            <dc:creator><![CDATA[Mayank Satnalika]]></dc:creator>
            <pubDate>Fri, 17 Feb 2017 21:21:11 GMT</pubDate>
            <atom:updated>2017-02-21T20:49:06.105Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pJu6cMx4o3pMMfoF6qJ4lA.jpeg" /></figure><blockquote>Update:</blockquote><blockquote>So the auctions are completed and my predictions for most players were way than the actual results :( Read through the previous auctions analysis part and the model used if you’re interested and also suggest any features/ factors for improving the model.</blockquote><p>After months of international cricket, it is time for cricket fans in India to welcome franchise-based t-20 cricket in their backyard. The Indian Premier League, which will enter its 10th edition this year, is already knocking on our doors with the auctions just around the corner.</p><p>Come again the 20th of this month and ridiculous amount of money will be spent to get the players into their kitty. For those new to this, IPL or the Indian Premier League is a league cricket tournament held in India involving domestic and international players and every year auctions are held to bid for players.</p><p>Only batsmen (including all-rounders) are compared here and all references to ‘players’ refer to the batsmen for which sufficient data was available and were auctioned during that year. All prices are in Indian Rupee.</p><p>Lets look into some of the facts over the years:</p><p>Average prices and total runs over the years:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/633/1*iCkU7lZPRJbgLdBnpRzh6A.png" /></figure><p>Just if it’s clear, the highest in the y-axis is 250,00,000 i.e. 2.5 crores. Note that the base price and runs remains almost constant over the years while there are jumps in the final average buying price of players, suffering a dip in year 2013 and then again rising. This can be attributed to the fact that the next season’s auction was a reshuffle year when all players are pooled in the auction and there is no retention of players. The franchise owners are reluctant to spend huge amounts as they know that the player will be associated with for only a year. In the present scenario, the IPL auction of 2018 will be reshuffle auction and thus we ca expect lower bid amounts in the present year auctions (for IPL 2017).</p><p>Next let’s check the top earners over the years:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/660/1*CnyvoYBkRfMoCKXiFsVsZg.png" /></figure><p>For 2011 auctions, Kolkata Knight Riders in a bold move, ditched Saurav Ganguly, bought Gautam Gambhir at a unusually high price and making him the captain of the team. Guess it worked well for them as they won their first title that season under Gambhir’s captaincy the next season. David Hussey was a good buy for Punjab Kings XI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/721/1*cUYTOEO5nIQiWZfw3rapHg.png" /></figure><p>Chennai Super Kings showed faith in Jadeja buying him for 9 crores and he did return the favours albeit with the ball and was among the top bowlers in the 2012 IPL.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/646/1*4h9pXm67A0fXBTUqxQj2OA.png" /></figure><p>In 2013 auctions, Mumbai Indians placed their bets on Maxwell, an unknown face at the time. Philip Hughes, an unfortunate player was bought cheap even after scoring much more runs than his expensive counterparts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/631/1*xwiFU15b_m8uuPbiS07ngg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/651/1*nynl67AguaYn4y8XzGoFmg.png" /></figure><p>For the next 2 years(2014 and 2015), Yuvraj Singh and Dinesh Karthik were among the highest paid players for IPL. Now while Dinesh Karthik’s duty as a wicket keeper can justify his price, Yuvraj failed to deliver in the 2015 and every single run he scored in 2015 for Delhi Daredevils cost a staggering 6.5L !</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/689/1*Nh4ga2Q-2wtumG5mtWy08w.png" /></figure><p>The last auctions was the only auctions where a player was on the extreme top right of the graph i.e. Shane Watson. The Australian scored runs and was bought for a price of 9.5 crores by Royal Challengers Bangalore.</p><h3><strong>Auctions 2017 :</strong></h3><p>The expected prices of players in this year auction’s are expected to be low as the next year’s auctions will see a complete reshuffling of team and franchises will not be allowed to retain players. So if a team buys a player for a high price this year, they will again have to compete for the player the in the next year auctions as well .</p><p>Now to determine a suitable price of the player, we use the buy price of the player and compare it with the performance in all matches in the period starting from one year prior to the auction date to the auction that year. The model used is a decision tree, (a glorified name for nested if-else structure) a simple illustration of which is given below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9XybB52Ky1WwVu-3fQTwBw.png" /></figure><p>If you see closely, the root(here the top of tree) has a base price value as condition and then it goes through a series of check to determine the price. The other major factors were: net_runs (the total runs scored in last year) and also avg2 (the average runs scored in ODI’s over the last year).</p><p>This year a list of around 350 players have been released, out of which 200 are batsmen. Using the model given above lets determine the expected buy- price of the players:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fairtable.com%2Fembed%2FshrL6YDcVEQlDj72P&amp;url=https%3A%2F%2Fairtable.com%2FshrL6YDcVEQlDj72P&amp;image=https%3A%2F%2Fstatic.airtable.com%2Fimages%2Foembed%2Fairtable.png&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;type=text%2Fhtml&amp;schema=airtable" width="800" height="533" frameborder="0" scrolling="no"><a href="https://medium.com/media/6aec85076bd6dd09cacb4cf3e158ec31/href">https://medium.com/media/6aec85076bd6dd09cacb4cf3e158ec31/href</a></iframe><p>So, those are what basic stats suggests the price of players should bee in this year’s IPL auctions.</p><p>If you liked the article, press the little heart button below :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=84c27ab1eefb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Predicting number of cars passing a toll booth by applying ARIMA model]]></title>
            <link>https://medium.com/@satnalikamayank12/predicting-number-of-cars-passing-a-toll-booth-by-applying-arima-model-cc8229ca629?source=rss-32524e07a5e6------2</link>
            <guid isPermaLink="false">https://medium.com/p/cc8229ca629</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Mayank Satnalika]]></dc:creator>
            <pubDate>Fri, 30 Dec 2016 19:23:09 GMT</pubDate>
            <atom:updated>2017-01-08T09:51:22.503Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/705/1*F8SyINAb5-aw_vVT3vYWBA.jpeg" /></figure><p>Time series forecasting is studying data given for some intervals and using it to predict the outcome for the next upcoming intervals. Time series data is one where the values are correlated with time. Given some previous records, predicting the future values has been a fascinating subject for programmers.</p><p>Note: this article only describes my understanding of ARIMA model and the results on applying it to a data set, and should not be taken as a tutorial or way understanding of the model. There are detailed explanations available elsewhere (links provided below).</p><p>The most fascinating field of it’s application can be predicting market movements to maximise profits. Other not so direct applications are predicting what would be the sales on the next Monday so that the store manager can stock appropriate inventory and manage workforce, or how many passengers are expected to commute on a route using my rental taxi service so that I can assign the appropriate number of taxis.</p><p>ARIMA(auto regressive integrated moving average) model is a popular way to forecast values in a time series data. Here, I am rather discussing about how to apply the model and forecast some values rather than the inner workings and the maths behind the algorithm.</p><p><strong>To successfully form a ARIMA model, we need to determine 3 parameters. ARIMA(p, d, q). ‘p’ is the order of AR, d is diffrencing and ‘q’ is order of MA model. So how do we decide what they should be?</strong></p><p><strong>The ACF (autocorrelation plot) and PACF (partial autocorrelation plots):</strong></p><p>The ACF plot gives us the correlation between a value and it’s lag (previous values). The value at which ACF drops is the order of the MA series and is our required value(q).</p><p>The PACF plot is similar top ACF the only difference being the correlation now excludes the change due to other correlating factors(here other lags) and only include the correlation between a value and that specific lag value. The value at which PACF drops is our required value(p).</p><p>It is explained in a simpler way by Arslan (<a href="https://www.quora.com/What-is-the-difference-among-auto-correlation-partial-auto-correlation-and-inverse-auto-correlation-while-modelling-an-ARIMA-series/answer/Arslan-20?srid=dmwi">here</a>):</p><p>Suppose you have 3 points in a time series x3 - x2 - x1. Using ACF you would generally find the correlation between x1 <strong>and</strong> x2 , for example. The value of correlation thus obtained is technically not true value of correlation, because the value of x2 is likely to be inspired by the value of x3. So PACF is that portion of the correlation between x1 <strong>and</strong> x2, which is not explained by the correlation between x3 <strong>in</strong> x2.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/121/1*AatHlwf-stkxSFq516P_aA.png" /></figure><p>Graphically, lets say, the correlation between x1 <strong>and</strong> x2 is given by the PINK box(including the GREEN box), and the correlation between x2 <strong>and</strong> x3 is given by the GREEN box. So the partial correlation of x1 <strong>and</strong> x2 is the original correlation minus the correlation of x2 <strong>and</strong> x3(GREEN box), which is just the PINK Pentagon.</p><p><strong>Stationarity and differencing:</strong></p><p>The parameter ‘d’ is determined by the number of times the series has been differenced in order to make it stationary. A stationary time series is one where the mean and variance does not change with time and there are no trends in the series.</p><p>For example: if you consider the details of number of air plane passengers travelling yearly, the plot shows it is rising with time, ie. Mean is increasing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/878/1*h6EtwvUI7z4KR86gsXA4Lw.png" /></figure><p>To make it stationary we take log of the time sereis and diffrence it once:</p><pre>ts_log = np.log(ts)<br>ts_log_diff = ts_log - ts_log.shift()<br>plt.plot(ts_log_diff)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G4BgZozOLDg7FafqE_m4MA.png" /><figcaption>Airplane data diffrenced once</figcaption></figure><p>So now the mean and deviations across time seems not to vary much and we can assume the series is now stationary. The number of times we difference it is the required value of parameter ‘d’.</p><p>So now coming back to the data-set I will be using here: E-Zpass is a toll collection system in US and they provided data from 1st Jan 2013 to 8th May 2013 of toll payers. The file had hourly details of all cars passing a toll booth, their direction of travel (North/ South) and mode of payment of toll tax. I am interested only in the total number of cars passing on a daily basis.</p><p>Importing the required files:</p><pre>import pandas as pd       <br>import math<br>import numpy as np<br>from sklearn import preprocessing, cross_validation, svm<br>from  datetime import datetime      <br>import matplotlib.pylab  as plt <br>from matplotlib import style<br>%matplotlib inline<br>from matplotlib import rcParams<br>rcParams[&#39;figure.figsize&#39;] = 15, 6   <br>import time<br>style.use(&#39;ggplot&#39;)  </pre><pre>from statsmodels.tsa.stattools import adfuller<br>from statsmodels.tsa.stattools import acf, pacf<br>from statsmodels.tsa.arima_model import ARIMA</pre><p>Reading the dataset and removing unnecessary fields:</p><pre>data = pd.read_csv(&#39;cars.csv&#39;)<br>data[&#39;date&#39;] = data[&#39;Start Time&#39;].convert_objects( convert_dates=&#39;coerce&#39;)  <br>data = data.sort_index(by=&#39;date&#39;)  <br>data[&#39;just_date&#39;] = data[&#39;date&#39;].dt.date<br>data = data.drop(&#39;Start Time&#39; ,axis = 1)<br>data = data.drop(&#39;End Time&#39; ,axis = 1)<br>data = data.drop(&#39;Plaza&#39; ,axis = 1)<br>data = data.drop(&#39;date&#39; ,axis = 1)</pre><p>Viewing the first few columns:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/555/1*GxGcqZBUpCCHeQc7iiILEA.png" /></figure><p>Now we need the total number of cars on daily basis, for each day from 1st Jan 2013 to 8th May 2013.</p><pre>data[‘totalCars’] = data[‘E-ZPass Total Vehicle Count’] + data[‘Cash Total Vehicle Count’]</pre><pre>dataNorth = data[data.Direction != ‘S’]<br>dataNorth[‘just_date’] = data[‘just_date’]</pre><pre>dataSouth = data[data.Direction != ‘N’]<br>dataSouth[‘just_date’] = data[‘just_date’]</pre><pre><br>cols = [‘North’, ‘South’]<br>dailyRecord = pd.DataFrame(columns = cols)</pre><pre>dailyRecord[‘South’] = dataSouth.groupby(‘just_date’,as_index = True).sum()[‘totalCars’]</pre><pre>dailyRecord[‘North’] = dataNorth.groupby(‘just_date’,as_index = True).sum()[‘totalCars’]</pre><pre>dailyRecord.index.name= &#39;date&#39;</pre><p>dailyRecord now holds the date as my index column and 2 field North and South denoting total number of cars passing through the toll plaza.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/185/1*8AwAFciG1qRjma_i-DYrPw.png" /></figure><p>Plotting daily records for North and south direction:</p><pre>dailyRecord[‘North’].plot()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hze7XOHYhdP5akHY6h4isg.png" /><figcaption>Number of cars headed towards North</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cpX7L9ymqsjA8oAr8XNFUw.png" /><figcaption>Number of cars headed towards South</figcaption></figure><p>Luckily for us, the data seems to be stationary and there is no need of differencing it. So we know the value of our parameter ‘d’ has to be 0.</p><p>From the plot it is clear there is some obvious pattern existing, and we need to make our model to predict the pattern. A unrelated interesting fact: the sudden dip you see on around the 9th Feb, 2013 in both the directions was due to Nor’easter blizzard of 2013.</p><p>Lets perform the study for only the cars going towards South side and plot the ACF and PACF charts.</p><p>We first drop the North cars field as we are studying the South data only and also plotting ACF and PACF with North data included will give errors.</p><pre>dailyRecord.drop(‘North’,axis = 1 ,inplace = True)</pre><pre>lag_acf = acf(dailyRecord, nlags= 25)<br>lag_pacf = pacf(dailyRecord, nlags= 25, method=’ols’)</pre><pre>plt.plot(lag_acf)<br>plt.axhline(y=0,linestyle=’ — ‘,color=’gray’)<br>plt.axhline(y=-1.96/np.sqrt(len(dailyRecord)),linestyle=’ — ‘,color=’gray’)<br>plt.axhline(y=1.96/np.sqrt(len(dailyRecord)),linestyle=’ — ‘,color=’gray’)<br>plt.title(‘Autocorrelation Function’)</pre><pre>plt.plot(lag_pacf)<br>plt.axhline(y=0,linestyle=’ — ‘,color=’gray’)<br>plt.axhline(y=-1.96/np.sqrt(len(dailyRecord)),linestyle=’ — ‘,color=’gray’)<br>plt.axhline(y=1.96/np.sqrt(len(dailyRecord)),linestyle=’ — ‘,color=’gray’)<br>plt.title(‘Partial Autocorrelation Function’)<br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*bcbTNT0H2-LjE8USyhjJAg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/774/1*LpWhzc_syK9CzMveHJW_sg.png" /></figure><p>Now comes the tricky part, determining the parameters p,d and q. Since we have not diffrenced the series as it was already stationary, we know d = 0. For ‘p’, we study the PACF chart, and by following the blog, look for “point where it drops.” It seems that after 7, the value comes down and again rises slightly at 13.</p><p>Similarly for ‘q’, we study the ACF chart and find value drops at 1 itself. Lets try out the ARIMA(7,0,1) and see the results:</p><pre>model = ARIMA( dailyRecord, order=( 7,0,1)) <br>results_ARIMA = model.fit(disp=-1) <br>plt.plot(dailyRecord, color=’blue’ )<br>plt.plot(results_ARIMA.fittedvalues, color=’red’)</pre><pre>err = dailyRecord[‘South’] — results_ARIMA.fittedvalues<br>plt.plot(err , color=’green’ )<br>absError = np.absolute(errPcent)<br>absError.sum()</pre><p>Output:</p><pre>165063.80410463404</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ael7qx2q05K4cDX5oP0O-Q.png" /></figure><p>Trying out various values for p and q, I get the least absolute error at ARIMA(9,0,3) model. ‘d’ is kept 0 because we haven’t diffrenced the series.</p><p>Output:</p><pre>160264.66116697912</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v-gw4OYf-vfVDj5TEinKiQ.png" /></figure><p>Now the final step is to actually predict some unknown values. We use the predict function, the parameter dynamic takes boolean value and specifies whether for the next prediction ,we wish to use the previous predicted value (dynamic = True) or the original value of series(dynamic = False).</p><pre>preds=results_ARIMA.predict(‘2013–05–05’, ‘2013–05–’,dynamic = True)<br>plt.plot(preds, color=’green’ )</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uAtWQ66WH9FKSoeouWTj6g.png" /></figure><p>A better way to predict the values for time beyond which data is provded is the forecast method().</p><pre>model = ARIMA( dailyRecord, order=( 9,0,3)) <br>results_ARIMA = model.fit(disp=-1) <br>predis= results_ARIMA.forecast(steps = 10)</pre><p>The forecast method returns a numpy array which I converted to a data frame with the next 10 days as the index and plotted the values:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rASt9aH0EdJ1gN7kQ5X8mw.png" /></figure><p>The blue segment of the plot are the foretasted values for the next 10 days and they approximately follow to pattern of the earlier data.</p><p>Important points to note:</p><ul><li>Note that taking log of time series does not count as differencing.</li><li>Also ACF plot and PACF plots are plotted on the differenced data series and not on the original data.</li><li>While fitting, include log if you have taken log of series to make it stationary but do not include the diffrenced value.</li><li>The predicted value we get are in the same scale as we trained, ie. if we have logged the series, the predicted value is also logged and we need to convert it back by taking exponentiation the series.</li><li>If the value of order of AR i.e. ‘p’ goes above 10, there may be a possibility that you need to difference the series further.</li></ul><p>For full code and data sets, visit my <a href="https://github.com/mayanksatnalika">Github profile</a> under time-series repository.</p><p>The data used as been sourced from <a href="http://www.data.gov/">data.gov</a> site although the specific data-set has now been removed.</p><p>To know more about mathematics of ARIMA model visit <a href="https://people.duke.edu/~rnau/411arim.htm">here</a>.</p><p>For detailed explanation of ARIMA model implementation in python visit <a href="https://www.analyticsvidhya.com/blog/2016/02/time-series-forecasting-codes-python/">here</a>.</p><p>Do comment any corrections/ suggestions. If you liked the article press the little heart button below.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cc8229ca629" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Decoding Indian markets salaries]]></title>
            <link>https://medium.com/@satnalikamayank12/decoding-indian-markets-salaries-7f46d1cd0b88?source=rss-32524e07a5e6------2</link>
            <guid isPermaLink="false">https://medium.com/p/7f46d1cd0b88</guid>
            <category><![CDATA[analytics]]></category>
            <category><![CDATA[education]]></category>
            <category><![CDATA[college]]></category>
            <dc:creator><![CDATA[Mayank Satnalika]]></dc:creator>
            <pubDate>Mon, 26 Dec 2016 21:57:12 GMT</pubDate>
            <atom:updated>2017-01-21T06:58:44.308Z</atom:updated>
            <content:encoded><![CDATA[<p>I came across a very interesting data set the AMEO 2015 data set which had the academic records and details of first job offered for around 4000 students in India. A quick analysis provides some interesting aspects into what contributes to the starting salary of an individual. The major factors studied are academic performance, state of college, city of job and designation.</p><p><strong>Academic Performance</strong>:</p><p>The data set provided Class 10 percentage, 12 percentage and the CGPA in college. Now finding the correlation between them and the marks gives the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/462/1*fDhHURids5so5dZNmaffxw.png" /></figure><p>Students scoring higher percentage of marks in 10th Class perform better in 12th Class(Correlation Coefficient ~0.64) .</p><p>However the interesting aspect to note is that the correlation between marks scored and the starting salary is quite low (around 0.17) for 10th and 12th Class percentage scores and even lesser (~0.13) for College CGPA and goes against the widely accepted notation that higher grades result in higher salary.</p><p><strong>Board of Education in Class 12</strong> :</p><p>The boards with most students were CBSE, ICSE and UP Board in decreasing order. The plot below shows students who studies in ISCE/ISC boards in 12th Class have a slightly higher salary than those of CBSE students and UP board students.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/549/1*4h33Zvfdo9dLbk6k8HnMBA.png" /></figure><p><strong>State of College and College-Tier:</strong></p><p>Plotting the mean salary of students grouped by their State of college and the college Tier:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/806/1*egK8eEM2XI87H_mL8CjfuQ.png" /></figure><p>It shows Tier-1 colleges in Rajasthan show exceptionally high performance which I believe is due to presence of BITS Pilani, Rajasthan. A clear expected result is that for all states, students of Tier 1 college have a higher starting salary than others showing college plays a important role in starting salary.</p><p>Tier 2 colleges of Bihar have a poor performance and starting salary lies in range of 100000 – 200000 which is significantly lower than all other counterparts.</p><p><strong>Job Designation:</strong></p><p>As expected, salaries with job titles having word ‘senior’ in them are the highest.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/976/1*TA53nHjTY1ByH-SQ4d0vPw.png" /></figure><p>One interesting inference that can be drawn is that roles which have a language/ technology specific designation are on the lower side of salary than designations which have no specific technologies. For example PHP developer, web developer, android developer, .NET developer are all in the lower end.</p><p><strong>Job City</strong></p><p>Starting salaries in Mumbai trump the others and is closely followed by Bangalore, the IT capital of the country. This is followed by Pune and Chandigarh. Salaries are low cities of Faridabad and Lucknow. Salaries of New Delhi, Ahamdabad and Coimbatore are approximately equal and lie in the middle of the distribution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/781/1*b88iK5C8epLF3Rr5gpyUWg.png" /></figure><p><strong>Delay/ Gap Years:</strong></p><p>The data set provided the details of Date of Birth of candidate and the joining date of the candidate. I created a new feature- delays which stored the gap between them or the age at which the student gets the job. The correlation coefficient between salary and the gap comes out to be -0.02. i.e. no correlation exists between the salary and the age of your first job .</p><p><strong>Specialisation field:</strong></p><p>Against the popular belief that a specialisation in computer science is the highest paying field, 4 specialisations have a average starting salary greater than computer engineering. However those high paying specialisations have a relatively much smaller number of students as compared to computer engineering.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/856/1*lJ1E0-DLXw2vF6sUaGihHQ.png" /></figure><p>The data provided was of those students who took the AMCAT test 2015, and represents only a small number (3998) out of the 1.5 Million engineers graduating each year in the country. The most intriguing inference is that the academic scores has a very low affect on how much the student earns in his first job. Also language/ domain specific jobs earn significantly lesser than jobs involving broader roles.</p><p>Data set used: Aspiring Minds’ Employability Outcomes 2015 (<a href="http://research.aspiringminds.com/resources/#ameo">Link</a>).</p><p>For full code and data sets, visit my <a href="https://github.com/mayanksatnalika">Github profile</a> under the ipython repository.</p><p>If you liked the article press the little heart button below.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7f46d1cd0b88" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Moving Averages to determine Batsmen Form in game of Cricket]]></title>
            <link>https://medium.com/data-science/https-medium-com-satnalikamayank12-using-moving-averages-to-determine-batsmen-form-d165c08be809?source=rss-32524e07a5e6------2</link>
            <guid isPermaLink="false">https://medium.com/p/d165c08be809</guid>
            <category><![CDATA[sports]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[cricket]]></category>
            <category><![CDATA[analytics]]></category>
            <dc:creator><![CDATA[Mayank Satnalika]]></dc:creator>
            <pubDate>Tue, 06 Dec 2016 14:10:08 GMT</pubDate>
            <atom:updated>2017-03-09T14:17:38.170Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/852/1*CaEQKMvzuBpzACyxQK8FZA.jpeg" /></figure><p>An attempt to use a simple algorithmic trading strategy in the field of cricket to determine the current form of a batsmen.</p><p><strong>Rolling Averages:</strong> It is the succession of averages derived from successive segments of data values or in simpler words the mean is computed by taking the values of some previous days value say for the last 10 days (for short moving average) or say over the last 50 days (for long term moving averages). The moving average for the next day is calculated by excluding the value of first day and including the latest value of today or present day. A 10-day MA would average will be by finding out the closing prices for the first 10 days as the first data point. The next data point would drop the earliest price, add the price on day 11 and take the average. The most common applications of MAs are to identify the trend direction i.e. is the value rising up or going down.</p><p><strong>Crossover Strategy in Stock Trading : </strong>Investors using moving average as an indicator to detect stock price movement i.e. whether it is rising or falling. A basic strategy involving moving averages is Crossover technique.</p><p>Take 2 MA’s one long term (say 50 days) and one short term (say 10 days). A crossover are the points where the plots intersect i.e. the points where the short term moving averages become higher than long term MA and vice versa.</p><p>A BUY signal is triggered when the short term MA crosses above the long term MA ( Short term MA &gt; Long Term MA) which indicates that the stock prices are starting to rise up. Similarly a SELL Signal is triggered when the Short Term MA crosses below Long Term MA ( Short Term &lt; Long Term MA) indicating prices are starting to go down and the investor should steer clear from the stock and sell the stocks if any.</p><p><strong>Applying it on Batsmen</strong>: Batsmen are usually termed to be as in-form (performing well) or out-of form (nonperforming). An analogy can be developed with the stock market and the cricket ecosystem with the players being analogous to the stock company and the runs they score being analogous to the price of the stock. The strategy used is no different in the field of cricket. We compute 2 MAs: one short term (say for 4 innings) and one long term (say for 15 innings). Instead of the prices, we use the runs scored by the batsman in that particular innings.</p><p>If there is a crossover where the short term MA becomes higher than long term MA, it indicates batsman will be in-form and will score good runs in upcoming few innings and will be in form. Similarly if there is a crossover where the short term MA becomes lower than Long term MA, the batsman is expected to perform poorly in the next few matches.</p><p>Importing the required modules</p><pre>import pandas as pd<br>import numpy as np<br>import matplotlib.pyplot as plt<br>%matplotlib inline</pre><p>Reading the records and calculating moving averages for 15 innings(long) and 4 innings(short).</p><pre>df1 = pd.read_csv(&quot;51880batting.csv&quot;)<br>#player 51880 from statsguru is Chris Gayle<br>maLong  = df1[&#39;runs&#39;].rolling(window = 15, center = False).mean()<br>maShort = df1[&#39;runs&#39;].rolling(window = 4, center = False).mean()</pre><p>Plotting:</p><pre>plt.plot(df1[&#39;runs&#39;].rolling(window=15,center=False).mean(),color = &#39;k&#39;)<br>plt.plot(df1[&#39;runs&#39;].rolling(window=4,center=False).mean(), color= &#39;g&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qcJbUg60VUAInx90iFx1Xg.png" /><figcaption>Long Term and Short Term MAs for Chris Gayle (WI Batsman)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/884/1*MzkHc9-7dT2ZWXllRnp2vA.png" /><figcaption>Long Term and Short Term MAs for Virat Kohli (IND Batsman)</figcaption></figure><p>Finding crossover points and calculating the average for next 3 innings if the Short Term MA &gt; Long term MA (equivalent of a BUY signal).</p><pre>sp = 0 <br>snp = 0<br>playCnt = 0<br>noplayCnt = 0<br>x = 15               #long term averages begin from index 15<br>while( x &lt;= 260):    #number of innings is 263 <br> if(maLong[x] &lt; maShort[x]):<br>  if(maLong[x+1] &gt; maShort[x+1]):   #crossover detected<br>    print ‘no play at’ , x<br>    snp= snp +df1[‘runs’][x+1] + df1[‘runs’][x+2] + df1[‘runs’][x+3]<br>    noplayCnt = noplayCnt+3<br> <br> if(maLong[x] &gt; maShort[x]):<br>  if(maLong[x+1] &lt; maShort[x+1]):   #crossover detected<br>   print ‘play at’ ,x<br>   sp = sp + df1[‘runs’][x+1] + df1[‘runs’][x+2] + df1[‘runs’][x+3] <br>   playCnt = playCnt+3<br> x = x+1</pre><p>Calculating and displaying averages:</p><pre>#overall career average<br>overallAvg = df1[‘runs’].mean()</pre><pre>#average over the next 3 innings after positive or &#39;BUY&#39; signal<br>playAvg = sp/playCnt</pre><pre>#average over the next 3 innings after negative or &#39;SELL&#39; signal noPlayAvg = snp/noplayCnt <br>     </pre><pre>print &#39;Career average: &#39;, overallAvg<br>print &#39;Positive Signal average: &#39;, playAvg<br>print &#39;Negative Signal average: &#39;, noPlayAvg<br></pre><p>Results for Chris Gayle</p><blockquote>Career average: 34.928030303<br>Positive Signal average: 48<br>Negative Signal average: 32</blockquote><p>Results for Virat Kohli:</p><blockquote>Career average: 45.0595238095<br>Positive Signal average: 59<br>Negative Signal average: 30</blockquote><p>The average runs scored is much higher (48 and 59) in innings where batsmen is assumed to be in-form than the career average of ~35 and ~45 respectively. This may further be developed using WMA (weighted moving averages) where more recent innings are given higher weight age while calculating averages and I believe will give even better results.</p><p>For full code and data sets, visit my <a href="https://github.com/mayanksatnalika">Github profile</a>.</p><p>The data used as been sourced from <a href="http://stats.espncricinfo.com/ci/engine/stats/index.html">Cricinfo Statsguru</a>.</p><p>For further reading on Moving averages and Crossover strategy visit <a href="http://www.investopedia.com/university/movingaverage/movingaverages4.asp">this link on Investopedia</a>.</p><p>If you liked the article press the little heart button below.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d165c08be809" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/https-medium-com-satnalikamayank12-using-moving-averages-to-determine-batsmen-form-d165c08be809">Using Moving Averages to determine Batsmen Form in game of Cricket</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[Competitive programming: Getting started]]></title>
            <link>https://medium.com/@satnalikamayank12/https-medium-com-satnalikamayank12-competitive-programming-getting-started-5a503c964dcd?source=rss-32524e07a5e6------2</link>
            <guid isPermaLink="false">https://medium.com/p/5a503c964dcd</guid>
            <category><![CDATA[competitive]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Mayank Satnalika]]></dc:creator>
            <pubDate>Thu, 30 Jun 2016 08:49:42 GMT</pubDate>
            <atom:updated>2016-06-30T08:50:08.505Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nL5uKriRMT3XePeblmAE2Q.png" /></figure><blockquote><strong>Competitive programming</strong> is a <a href="https://en.wikipedia.org/wiki/Mind_sport">mind sport</a> usually held over the <a href="https://en.wikipedia.org/wiki/Internet">Internet</a> or a <a href="https://en.wikipedia.org/wiki/Local_network">local network</a>, involving participants trying to <a href="https://en.wikipedia.org/wiki/Computer_programming">program</a> according to provided specifications. Contestants are referred to as sport programmers. Competitive programming is recognised and supported by several multinational software and Internet companies, such as <a href="https://en.wikipedia.org/wiki/Google">Google</a>,<a href="https://en.wikipedia.org/wiki/Competitive_programming#cite_note-1">[1]</a><a href="https://en.wikipedia.org/wiki/Competitive_programming#cite_note-2">[2]</a> <a href="https://en.wikipedia.org/wiki/Facebook">Facebook</a><a href="https://en.wikipedia.org/wiki/Competitive_programming#cite_note-3">[3]</a> and <a href="https://en.wikipedia.org/wiki/IBM">IBM</a>.<a href="https://en.wikipedia.org/wiki/Competitive_programming#cite_note-4">[4]</a> There are several organisations who host programming competitions on a regular basis.</blockquote><p>In simpler terms competitive programming is a sport where you are given some set of programming questions and you need to solve them. The grading criteria often being the time taken by your program and it’s memory utilisation. Competitions can run for a duration of a few hours to some as long as a full month.</p><p><a href="http://www.spoj.com/">Sphere Online Judge</a>, <a href="http://www.codechef.com/">Codechef</a>, <a href="https://www.hackerrank.com/">Hackerrank</a> and <a href="http://www.hackerearth.com/">hackerearth </a>can be considered as the most popular competitive programming platforms.</p><p>For beginners, Sphere Online Judge can be considered the most suitable. Want to get started on competitive programming? Just head over to Spoj and sort the questions based on user(number of users who have successfully solved that particular problem) and start solving them. The drawback is the interface of the site is very outdated. Do remember to read the comments of the questions as they provide hints and new ways to approach a question. Codechef is more inclined for the practice of ACM-ICPC — The ultimate competitive programmer&#39;s dream competition while hackerrank and hackerearth are more popularly used to host hiring competitions by various companies.</p><h3><strong>Here are few basic steps to get started on competitive programming:</strong></h3><h4><strong>Which language should I use?:</strong></h4><p>Frankly speaking you can use any programming language you are comfortable in (Note: HTML is not a programming language, JavaScript is). I suggest you use any one of C/C++ or Java. You can also use Python but you will not be able to enjoy questions involving large numbers as Python can handle them easily without special implementation.</p><h4><strong>Read the Question details:</strong></h4><p>On of the biggest beginner’s mistake is not reading the question and constraints properly. Say for example consider the question <a href="http://www.spoj.com/problems/FCTRL2/">FCTRL2</a>, which may seem relatively very simple as you are just required to find the factorial of the number input. However when you see the constraint of the input number you will realise you cannot use the long int variable in C++ as the 100! will be outside it’s memory limits.</p><h4><strong>Omit the superficial parts:</strong></h4><p>You may be inclined to write words like “<em>Enter the number you want to find the factorial of</em> ” while taking the input, but online judges will give you a wrong answer if you write any content apart from the one specified in the program output. Do follow the program input/output format as they are the cause of many silly WAs(wrong answer).</p><h4><strong>Got stuck?</strong></h4><p>On getting stuck at a problem, try to understand what algorithm is required from the question tags and comments. If it is a new algorithm, try reading about it and attempt the question again. If you are still stuck try to get the hints of solving the question without actually looking at the actual code. i would suggest you google “ <em>SPOJ question_name Discussions</em>” for the best results. There are sites like <a href="http://code.cloudkaksha.org/">code.cloudkaksha</a> which provide a detailed explanation to approach a specific problem apart from the code. Man explanation are available at Quora as well.</p><p>Once you are familiar an get the hang of competitive programming you can move on to sites like <a href="http://www.topcoder.com/">topcoder</a> and <a href="http://www.codeforces.com/">codeforces </a>which host many weekly rated contests or go to <a href="http://www.hackerrank.com/">hackerrank </a>/ hackerearth if a job is what you want. It takes considerable amount of time before you get good at it. You have to keep yourself motivated throughout. Not giving up is the key here</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5a503c964dcd" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>