<?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 Tapas Mahanta on Medium]]></title>
        <description><![CDATA[Stories by Tapas Mahanta on Medium]]></description>
        <link>https://medium.com/@mahanta-tapas?source=rss-23fe29d8dcec------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*DwSZ2tVEnvPOh-hn6zoJ6g.jpeg</url>
            <title>Stories by Tapas Mahanta on Medium</title>
            <link>https://medium.com/@mahanta-tapas?source=rss-23fe29d8dcec------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 23:12:26 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mahanta-tapas/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[NLP The Bigger Picture]]></title>
            <link>https://mahanta-tapas.medium.com/nlp-the-bigger-picture-840e29ee9a6d?source=rss-23fe29d8dcec------2</link>
            <guid isPermaLink="false">https://medium.com/p/840e29ee9a6d</guid>
            <dc:creator><![CDATA[Tapas Mahanta]]></dc:creator>
            <pubDate>Wed, 30 Dec 2020 04:39:23 GMT</pubDate>
            <atom:updated>2020-12-30T04:39:23.573Z</atom:updated>
            <content:encoded><![CDATA[<p>The idea behind any Natural Language Processing(NLP) algorithm is that to convert words/texts into a form that machines(mathematical models) can understand. For this, we often map the texts to either matrix, arrays, or vectors of numbers. This is known as word/document embedding, the fundamental of Natural Language Processing. There are a number of embedding techniques, we will discuss a few of them and get to know few of them in detail. But more importantly, we will see how these algorithms approach embedding differently.</p><p><a href="https://www.analyticsvidhya.com/blog/2020/02/quick-introduction-bag-of-words-bow-tf-idf/"><strong>Bag of Words:</strong></a> it’s a vector/dictionary with a corpus as rows and words as columns. Where the values can be either.</p><p>a) count/frequency of words: The reason behind using this approach is that keyword roughly represent a context. So the number of occurrences represents the importance of the word and more frequency means more importance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VQxqDAHpxxsTcCtDMAZsnA.png" /></figure><p>But one can clearly see the limitation of this approach, as frequently used vocabulary such as prepositions and helping verbs, will dominate; “of”, “in”, “is”, “are” etc. The next approach tries to get rid of this bias by normalizing words</p><p>b) tf-idf</p><p>The idea behind tf-idf is if a term/word appears in one document more frequently it’s weight will increase(because of the tf term), but simultaneously if the term appears more frequently in other documents as well, then it’s the importance decreases.(because of the idf term).</p><p>so the tf * idf term creates a good balance which gives importance to less frequent words.</p><p><a href="https://towardsdatascience.com/3-basic-approaches-in-bag-of-words-which-are-better-than-word-embeddings-c2cbc7398016">limitations of bag-of-words</a> include large feature dimension, sparse representation, etc. when we have a large corpus(texts) we will need a very high dimensional matrix to be able to represent each word and many entries might be empty as not all words will be present in all documents.</p><p><strong>Bag of n-grams: </strong>Same as a bag of words but instead of one word, n-words are considered one unit.</p><p><strong>Aggregation of bag-of-words: </strong><a href="https://stats.stackexchange.com/questions/312206/can-i-apply-word2vec-to-find-document-similarity">Does it help?</a></p><p>Bag-of-words vector can be summed, averaged to produce document vectors form word vectors, but does this approach give good results?</p><p>Aggregating word vectors using the <a href="https://stats.stackexchange.com/questions/221715/apply-word-embeddings-to-entire-document-to-get-a-feature-vector">coordinate-wise mean</a>, min, or max seemed to give better results.</p><p>An important thing to notice is that, Bag-of-words based word embedding do not retain the order of the words in the original text. In bag-of-words based models stopwords(is, are, they etc.) and name words should be removed as without any order/grammar they do not have any significance.</p><p><strong>LDA:</strong> LDA is another bag-of-words based probabilistic model. We can also say the above Bag-of-words model is a generalization/simplification of LDA.</p><p>At a high level, the model assumes that <strong>each document will contain several topics</strong>, so that there is <strong>topic overlap within a document</strong>. The words in each document contribute to these topics. The topics may not be known a priori, and needn’t even be specified, but the <strong>number</strong> of topics must be specified a priori. Finally, there can be words overlap between topics, so several topics may share the same words.</p><p>The model generates to <strong>latent</strong> (hidden) variables :</p><ul><li>A distribution over topics for each document <strong>(1)</strong></li><li>A distribution over words for each topics <strong>(2)</strong></li></ul><p>After training, <strong>each document will have a discrete distribution over all topics</strong>, and <strong>each topic will have a discrete distribution over all words</strong>.</p><p>The former approach can be thought of as a simplistic probabilistic model of documents as distributions over words. The bag-of-words vector then represents the best approximation we have for the unnormalized distribution-of-words in each document; but document here is the basic probabilistic unit, each a single sample of its unique distribution.</p><p>The crux of the matter, then, is to move from this simple probabilistic model of documents as distributions over words to a more complex one by adding a latent (hidden) intermediate layer of <em>K</em> topics.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oZs1sequ5CQWTZpYBBE9tw.png" /></figure><p>Topics are now characterized by distributions over words, while documents are distributions over topics. This probabilistic model of a document corresponds to a generative model of documents; To generate a set of <em>M</em> documents of lengths <em>{Nᵢ}</em>, assuming a predetermined number of <em>K</em> topics, where <em>Dir()</em> denotes a <a href="https://en.wikipedia.org/wiki/Dirichlet_distribution">Dirichlet distribution</a>:</p><ol><li>For each topic <em>v</em>, sample a word distribution φᵥ~<em>Dir(β)</em>.</li><li>For each document <em>i</em>, sample a topic distribution (or mixture) θᵢ~<em>Dir(</em>α<em>)</em>.</li><li>To generate document <em>i</em> of length <em>Nᵢ</em>, for each word <em>j</em>:<br>3.1. Sample a topic zᵢⱼ ~<em>Multinomial(θᵢ) </em>for word <em>j</em>.<em><br></em>3.2. Sample word <em>j</em>~<em>Multinomial(zᵢⱼ)</em>.</li></ol><p><a href="https://medium.com/voice-tech-podcast/topic-modeling-with-lsa-plsa-lda-and-word-embedding-51bc2540b78d"><strong>Prediction Based Embedding</strong></a>( CBOW, Skip-gram)</p><p>Also Known as Encode-Decode based embedding. ( Encode text and decode pattern and vice-versa)</p><p>CBOW — We predict(or <a href="https://towardsdatascience.com/nlp-101-word2vec-skip-gram-and-cbow-93512ee24314">rather learn</a>) a word based on context.</p><p>Skip-Gram — We predict context based on a word.</p><p>the crux of these models, after all, is that word representations learned while learning to predict the context of a word from the word itself (or vice versa) represent a vector space capturing deep semantic and syntactic concepts and phenomena.</p><p><strong>Aggregation/Average of Word Embeddings For Sentence Embeddings in Word2Vec:</strong></p><ol><li>A possibility is to use a fixed (unlearnable) operator for vector summarization — e.g. averaging — and learn word embeddings in a preceding layer, using a learning target that is aimed at producing rich document embeddings</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QJNEAxCwRtWVnPWr3I9mdQ.png" /></figure><p>Thus the main advantage here is that word embeddings are optimized in the neural network for averaging into document representations, and we are not taking the mean of the result.</p><p>2. A modification of this approach is to use the smooth inverse frequency weighting scheme, and (2) removing the common discourse component from word vectors; this component is found using PCA, and it is used as a correction term for the most frequent discourse, presumably related to syntax.</p><p><strong>Sent2Vec: </strong>Extending Word2vec to include n-grams (sentiment) and optimized the word(n-gram) embedding for the purpose to yield document vectors.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dWafHdlKzSc_rhqR3Q907Q.png" /></figure><p>This can also be seen as an unsupervised version of fasttext.</p><p><strong>doc2vec (Paragraph Vectors): </strong>Generalization of <em>word2vec</em> to work with word sequences. Two variants “<em>Distributed Memory</em> and <em>Distributed Bag-of-Words”</em></p><p>Distributed Memory: The training task here is quite similar to that of CBOW; a single word is to be predicted from its context. In this case, the context words are the preceding words, not the surrounding words, as is the paragraph.</p><p>Distributed Bag of Words: The second variant of <em>paragraph vectors</em>, despite its name, is perhaps the parallel of <em>word2vec</em>’s <em>skip-gram</em> architecture.</p><p>Doc2VecC — A hybrid Approach of the above two approaches.</p><p><strong>Skip-Thought:</strong> Another Generalization of Word2Vec</p><p>It extends <em>word2vec</em> — specifically the <em>skip-gram</em> architecture — in another intuitive way: the base unit is now “sentences”, and an encoded sentence is used to predict the sentences around it. it uses an RNN encoder with GRU activations and RNN decoders with a conditional GRU.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x47dX7QVZ5fidJB8XjLzOQ.png" /></figure><p>FastSent is a significantly simpler variation on the <em>skip-thoughts</em> model; <em>FastSent</em> is a simple additive (log-bilinear) sentence model designed to exploit the same signal but at a much lower computational expense. Given a BOW representation of some context sentence, the model simply predicts adjacent sentences (also represented as BOW).</p><h3>Sentence-BERT (SBERT)</h3><p>Doc2Vec:</p><p><em>The algorithm then runs through the sentences iterator twice: once to build the vocab, and once to train the model on the input data, </em><strong><em>learning a vector representation for each word and for each label</em></strong><em> in the dataset.(</em><a href="https://rare-technologies.com/doc2vec-tutorial/">https://rare-technologies.com/doc2vec-tutorial/</a>)</p><p><em>Helper functions like </em>model.most_similar()<em>, </em>model.doesnt_match()<em> and </em>model.similarity()<em> also exist. The raw words and label vectors are also accessible either individually via </em>model[&#39;word&#39;]<em>, or all at once via </em>model.syn0<em>.</em></p><p><strong>Different methods of calculating similarity.(</strong><a href="https://groups.google.com/forum/#!topic/gensim/Fujja7aOH6E">https://groups.google.com/forum/#!topic/gensim/Fujja7aOH6E</a>)</p><p>Each of the `most_similar()` methods (and some of the others) take raw vectors as well as (string/int) lookup keys.</p><p>So, just as you can do:</p><p>d2v_model.most_similar(‘longevity’)</p><p>…an equivalent call (still just looking among words) is…</p><p>d2v_model.most_similar( [ d2v_model[‘longevity’] ] ) # currently must be a list, assumed ‘positive’ examples</p><p>This points the way to using a word-vector to find similar doc-vectors:</p><p>d2v_model.docvecs.most_similar( [ d2v_model[‘longevity’] ] )</p><p>…or using a doc-vector to find similar word-vectors:</p><p>d2v_model.most_similar( [ d2v_model.docvecs[‘DNA repair’] ] )</p><p>model.docvecs — contains the document vector for trained tags</p><p>model.docvecs.doctag_syn0 is the paragraph matrix containing all the document vectors (essentially D of the paper)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pj7-_Ea0Jg93dh1Z1DLE8Q.png" /></figure><p>model.docvecs.doctags has all the tags used in training.</p><p>model.docvecs.most_similar — use this to find similar document vectors</p><p>model.most_similar — use this to find similar tags</p><p>model.wv.most_similar(target_word, topn=10) — gives words similar to a word according to the model.</p><p><a href="https://radimrehurek.com/gensim/auto_examples/howtos/run_doc2vec_imdb.html">https://radimrehurek.com/gensim/auto_examples/howtos/run_doc2vec_imdb.html</a></p><p>Do the DBOW words look meaningless? That’s because the gensim DBOW model doesn’t train word vectors — they remain at their random initialized values — unless you ask with the dbow_words=1 initialization parameter.</p><p>model = Doc2Vec.load(fname)</p><p>After loading the model :-</p><p># you can continue training with the loaded model!<br>#If you’re finished training a model (=no more updates, only querying, reduce memory usage), you can do:<br> <br>model.delete_temporary_training_data(keep_doctags_vectors=True, keep_inference=True)</p><p>(<a href="https://ai.intelligentonlinetools.com/ml/text-clustering-doc2vec-word-embedding-machine-learning/">https://ai.intelligentonlinetools.com/ml/text-clustering-doc2vec-word-embedding-machine-learning/</a>)</p><h3>Using Pretrained doc2vec Model</h3><p>References</p><p><a href="https://towardsdatascience.com/3-basic-approaches-in-bag-of-words-which-are-better-than-word-embeddings-c2cbc7398016">3 basic approaches in Bag of Words which are better than Word Embeddings</a></p><p>1. Text Q, Huilgol P. BoW Model, and TF-IDF For Creating Feature From Text. Analytics Vidhya. <a href="https://www.analyticsvidhya.com/blog/2020/02/quick-introduction-bag-of-words-bow-tf-idf/">https://www.analyticsvidhya.com/blog/2020/02/quick-introduction-bag-of-words-bow-tf-idf/.</a> Published in 2020. Accessed August 19, 2020.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=840e29ee9a6d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Choosing  your Regression Model : Inference vs Prediction]]></title>
            <link>https://mahanta-tapas.medium.com/choosing-your-regression-model-inference-vs-prediction-dab5fa2ae71c?source=rss-23fe29d8dcec------2</link>
            <guid isPermaLink="false">https://medium.com/p/dab5fa2ae71c</guid>
            <category><![CDATA[r-square]]></category>
            <category><![CDATA[linear-regression]]></category>
            <category><![CDATA[predictions]]></category>
            <category><![CDATA[model-selection]]></category>
            <category><![CDATA[inference]]></category>
            <dc:creator><![CDATA[Tapas Mahanta]]></dc:creator>
            <pubDate>Tue, 13 Oct 2020 23:45:38 GMT</pubDate>
            <atom:updated>2020-10-16T03:19:08.479Z</atom:updated>
            <content:encoded><![CDATA[<h3>Choosing your Regression Model Inference vs Prediction</h3><p>I first got to know about linear regression back in 2013 during my undergrad Machine Learning class. Since then I have been exposed to many powerful and complex machine learning algorithms. But over these years I had underestimated its capabilities until I read about it again during my Masters albeit through a very different approach.</p><p>Coming from a computer science background I’ve always understood linear regression as another way of prediction. Only when I took a class in Econometrics, I get to know the Economist&#39;s point of view of regression: How linear models are used to hypothesize and establish causality. And when I used SAS for modeling I realized the power and simplicity linear regression provides a robust benchmark for most of industry’s problems. In this article, I will provide my perscpective on how to do choose your model for different tasks i.e. Inference(Causality) vs Prediction.</p><p>There are different metrics available to evaluate a linear regression model such as Mean Square Error(MSE),R-Square, Adjusted R-Square, Cp-Value, AIC, BIC, , etc. And how to choose between different metrics depends on the problem we are trying to solve or the purpose.</p><p><strong>Inference:</strong></p><p>Let’s first understand these approaches. If the goal is to understand the relationship between the dependent variable(Y) and the Independent variables(Xs), We care more about accurately estimating the co-efficient of the Independent variables as accurate estimates help to make inferences and establish causality. For example how confidently can we say parent’s education has an effect on a person’s income? if yes, can we quantify it?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iG_u4FbJZlgT2-2MFH8BcQ.png" /></figure><p>For example, if we look at the above equation, in the case of inference we want to know what is the effect of education(if any) on wage or Estimating <em>B1 </em>accurately. And for this reason, we want the model to be simpler and easy to interpret.</p><p><strong>Prediction:</strong></p><p>But for prediction, all we care about is getting an accurate prediction of wage given education, years of experience, etc. The reason why the Economist approach focus on causality is because they are often required to make social or monetary policies, where causality is key. Is there an effect of gun control law on crime rates for example. While in the computer science approach it is usually linked with key business decisions such as amount of sales generated from advertising, in this case we need a predicted value as accurate as possible. One thing that is common in both approaches is accurately identifying the true model or relationship.</p><p><strong>Goals and Expectations:</strong></p><p>Another different aspect of the “Inference vs Prediction” question is how we use the model once they are estimated. In the case of prediction, we care about how accurately the model predicts for unseen data. And to simulate this we split the dataset into train and test. Where we train our model on a portion of the data and use the rest to evaluate it.<strong> Our expectation from prediction model is to get the most accurate prediction.</strong></p><p>While for inference, We use the complete available dataset to study the relationship between the variable of “interest”(parent’s education) and the dependent variable(income). <strong>Our expectation from the Inference model is to get the most accurate estimation of the variable co-efficient.</strong></p><p><strong>Same same but different:</strong></p><p>if we examine closely both these expectations, we will realize that both our problems will be solved if we can estimate the true model correctly. But unfortunately that isn’t the case always. And while for Inference we tend to prefer a simpler model(ess no of predictors, fewer polynomial terms etc.), for prediction we prefer a model with the best prediction, which usually makes the model complex. This also follows the classical machine learning dilemma of bias vs variance. We can see how both approaches are in a conflict,</p><p><em>Another way to look at it is, less number of variables in an equation makes the estimation of our interest variable more confident.(less variables in the model less variance in estimation). This is good for Inference, but bad for prediction as we can get better prediction by adding more no of variables.</em></p><p>To solve this classical machine learning dilemma and estimate better models to our “need”, we need to know how to use different model evaluation criteria effectively.</p><p><strong>Modle Selection Criteria : MSE and R-Square</strong></p><p>The first choice that comes to our mind is Mean Square Error(MSE). But it turns out model selection by minimizing MSE is not a very good idea. When we use MSE every model is too “optimistic” about how it will actually predict or in other words it underestimates it’s true expected squared error. And minimizing the in-sample MSE completely ignores the bias from this optimism, so it is guaranteed to pick models which are too large and predict poorly out of sample.</p><p><strong>R-square</strong> is often seen as a good measure of inference exercise. But one major issue with this is that there are ways to improve R-square which not necessarily are good for us. For example, With every additional variable(relevant or irrelevant) into the model, R square will improve. And if you look closely at the formula for calculating R-square, you’ll realize <strong>Picking a model by maximizing R-sqaure is thus equivalent to picking a model by minimizing MSE. </strong>Therefore selecting a model by mAximizing R-square acroos models will have the same disadvantages as minimizing MSE.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AkfHzfZkznn-hx0gPXAP9A.png" /></figure><p>From a prediction point of view, it might lead to overfitting — it learns the training pattern(noise) too closely and failing to generalize. And from an Inference point of view nonlinear parameters complicate the model and make it difficult to interpret.</p><p>So to summarize we want a model (set of predictors) that doesn’t complicate the model or make it prone to overfitting. Since R-square do not allow us to do that we need different criteria to evaluate our models. But since it is easy to interpret ( R-square of 0.97 means model captures 97% of the variance in the dependent variable), we will see methods closely related to it, will be useful to us.</p><p><strong>Modle Selection Criteria : <em>Cp</em>, AIC, BIC, or adjusted <em>R</em>2, CV</strong></p><p>The criterias we will discuss for model evaluation can be categorized in two classes based on how they function.</p><ol><li>Adjust Training Error: <em>Cp</em>, AIC, BIC, or adjusted <em>R</em>2</li></ol><p>2. Estimating Test Error : K fold Cross Validation</p><p>Mallow’s <em>Cp</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sDb2w8A1kR_fDg3eBnVCDw.png" /></figure><p><strong>AIC(Akaike Information Criterion)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NEgA6wLfCU8dn29rGEk54Q.png" /></figure><p>Notice the formula for Cp, AIC , and BIC are in the form of “MSE(RSS) + penalty ”. Also notice that the penalty term consists of number variables and the estimation of the error variance. We can see it as the cost we’re imposing on models for having extra parameters. Every new parameter has got to pay that cost by reducing the MSE by at least a certain amount; if it doesn’t, the extra parameter isn’t worth it.</p><p><strong>BIC(Bayesian Information Criterion)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k8NzckusrQ54R2qNFTpjsw.png" /></figure><p><strong>Adjusted R-Square</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NMq93p-yA_WoSkuvWgyaAQ.png" /></figure><p>Without going too much into the mathematics of these methods <strong>Cp, AIC and BIC become extremely similar in the way that they pick the same model</strong>. BIC being a bit more conservative than the other two, and Adjusted R-square is only half as good as others, therefore not a very good choice for model selection. We will see it’s usefulness as a scoring metric due to it’s closeness in interpretability to R-Square and the ability to penalize complex models.</p><p><strong>CV: K Fold Cross Validation</strong></p><p>Another variation of minimization of MSE that has been effective is, when it’s used in the K-fold Cross validation method, where we split the data into K(usually 5 to 10) folds.And Then keeping each fold as test and rest of the folds as train, estimate the model on the training set and calculate the MSE over the test fold. We then Average the test MSE over all the folds to get MSE-test. This also gives a result very similar to the “MSE(RSS) + penalty” methods.</p><p>Now that we know all the relevant the terms and concepts, let’s talk about model selection in detail.</p><p><strong>Summary:</strong></p><p>When we have n predictors and we are trying to estimate the relationship between the predictors(Xi) and the dependent variable(Y), there can be a range of possible models based on : adding or dropping a variable, polynomial terms(Xi²), and interaction(X1 * X2) between variables etc. The question is how to choose between these possible models, or more precisely which criteria to use?</p><p>For model selection we need two things</p><h3><strong>1.Subset Selection method</strong></h3><p><strong>1.a Best Subset Selection</strong>: Based on a criteion test all 2^p<em> </em>models for <em>p </em>predictors, pick the one with best value for criterion. Computationally burdensome.</p><p><strong>1.b Stepwise Selection : Does not test all possible models.</strong></p><p><strong>1.b.i Forward</strong> :It involves starting with no variables in the model, testing the addition of each variable using a chosen model fit criterion, adding the variable (if any) whose inclusion gives the most statistically significant improvement of the fit, and repeating this process until none improves the model to a statistically significant extent.</p><p><strong>1.b.ii Backward</strong> : Consider possible predictors, start by deleting each coefficient in turn, and pick the sub-model with the best value of the criterion.</p><p><strong>1.b.iii Hybrid: </strong>A<strong> </strong>combination of the above, testing at each step for variables to be included or excluded.</p><h3>2.<strong>Model selection Criteria</strong></h3><p>And each of these above methods need a criteria to compare models. And that can be done broadly in two ways.</p><p><strong>2.a</strong> Adjusting Training Error (Cp, AIC, BIC, Adjusted R-Squared)</p><p><strong>2.b</strong> Estimating Test Error (K fold Cross Validation)</p><p><strong>So to a model selection tool/algorithm we need to provide two inputs: which subset selection method to use? and which criteria to use ?For example We could say Use “forward elimination” with Cp to select the our model.</strong></p><p>For model selection we use forward,backward and hybrid model selection method using Cp or CV as criteria. Then we list and score them based on a scoring method (Adjusted R-square or MSE test) to pick the best model</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/676/1*IpehVJPP-QakbrLpOaa37w.png" /></figure><p>The best model here is subjective here and we come back again to our debate or Inference vs Prediction. For example once we have the top n models we score and rank them based on their adjusted R-square and MSE-test. And now if we have to choose the best model for inference, we chose the one with highest Adjusted R square as it tends to give us a simples and more explainable model. On the other hand if our goal is prediction, we choose the model with lowest MSE-test because it has the potential to generalize well on unseen data.</p><p>References: <a href="http://www.stat.cmu.edu/~cshalizi/mreg/15/lectures/21/lecture-21.pdf">http://www.stat.cmu.edu/~cshalizi/mreg/15/lectures/21/lecture-21.pdf</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dab5fa2ae71c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[NLP: Analyzing Political Bias in American Media]]></title>
            <link>https://mahanta-tapas.medium.com/nlp-analyzing-political-bias-in-american-media-d61a9e793aa9?source=rss-23fe29d8dcec------2</link>
            <guid isPermaLink="false">https://medium.com/p/d61a9e793aa9</guid>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[word2vec]]></category>
            <category><![CDATA[news]]></category>
            <category><![CDATA[doc2vec]]></category>
            <category><![CDATA[lda]]></category>
            <dc:creator><![CDATA[Tapas Mahanta]]></dc:creator>
            <pubDate>Fri, 17 Jul 2020 02:28:51 GMT</pubDate>
            <atom:updated>2020-10-14T01:07:17.339Z</atom:updated>
            <content:encoded><![CDATA[<h3>NLP: Political Bias in American Media using Document Embedding.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WC3VPaYPqIFzi9PF" /><figcaption>source: <a href="https://www.scmp.com/comment/insight-opinion/article/3008397/besides-fake-news-bias-and-fewer-readers-us-media-has">https://www.scmp.com/comment/insight-opinion/article/3008397/besides-fake-news-bias-and-fewer-readers-us-media-has</a></figcaption></figure><p>While issues such as fake news are very relevant, the bias in news media often goes unexamined, unless analyzed actively. These days almost each and every issue is politicized and this is making people reinforce their already existing beliefs through search engine suggestions. As a result, there is very little room for a change in the opinion polarizing our country and society further every day.</p><p>And unfortunately, mainstream media outlets are not helping in reducing these barriers. Though we have some idea about the political alignment of media outlets(left, right, or center), we are not actively analyzing the information for political bias when we read. I being a news junkie, saw this regularly where political agenda has become a priority rather than news reporting, which frustrated me.</p><p>So I decided to analyze for myself and see how biased mainstream news outlets are. I chose three news sources (<strong>washingtonpost.com, usatoday.com, FoxNews.com</strong>); representing liberal, conservative, and center-aligned outlets or topics that are usually controversial such as <strong>mail-in-voting, Obamacare, abortion,</strong> and unfortunately <strong>masks and healthcare</strong>, etc.</p><p>I used <a href="https://newsapi.org/"><strong>news API</strong></a>, which is an easy to use free API to collect news articles given a date range, and list of topics. I used selenium to then scrap the content from those links using a pre-existing <a href="https://github.com/mattlisiv/newsapi-python">wrapper</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lFTRapx1HMP9ovhvgUlh2w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0JeVcIbTNr6slWVoHeAvlQ.png" /></figure><p>The idea is to classify news articles into <strong>left, right,</strong> and <strong>center</strong>. The labeling of articles is done based on the title (sometimes in content when it’s unclear from the title). There are few issues in doing so. firstly it’s difficult in case of few articles to judge if there is a political bias present in the content. And secondly, all the labeling was done by myself, so there might be an inherent bias in the labeling. If something was not clear from the title, I tried to skim through the content to see if it will help me decide on a label for the article. It will be helpful to get opinions from outsiders to reduce personal bias in labeling. If you want to contribute to creating better labels, I’ll leave a link to the excel file at the end, where you can label articles based on titles.</p><p>I scraped about 500 news articles from washingtonpost.com, usatoday.com, and FoxNews.com, which I tagged on topic, sentiment, and bias(left, right, and center). Out of those, I have filtered <strong>114 articles covering 13 topics </strong>for training and testing and 55 articles of a different topic (not seen by model).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y9cdp3FJ_ZZGh6q99d6vEg.png" /><figcaption>Sample of the final data</figcaption></figure><h3>LDA:</h3><p>First let’s use a topic labeling method called LDA (Latent Dirichlet Allocation) to see if we can learn the underlined bias in the news articles.</p><p>At a high level, the LDA model assumes that <strong>each document will contain several topics</strong> so that there is a <strong>topic overlap within a document</strong>. The words in each document contribute to these topics. The topics may not be known a priori, and needn’t even be specified, but the <strong>number</strong> of topics must be specified a priori. Finally, there can be words overlap between topics, so several topics may share the same words.</p><p><a href="https://towardsdatascience.com/document-embedding-techniques-fed3e7a6a25d#e586">LDA is a bag-of-words based model( bag-words is a generalized version of LDA)</a>. While in bag of words documents are simplistic probabilistic distribution over words( frequency), while LDA adds one more layer (topics) between words and documents. Basically, it builds a topic per document model and words per topic model, modeled as Dirichlet distributions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oZs1sequ5CQWTZpYBBE9tw.png" /><figcaption>source: <a href="https://towardsdatascience.com/document-embedding-techniques-fed3e7a6a25d#e586">https://towardsdatascience.com/document-embedding-techniques-fed3e7a6a25d#e586</a></figcaption></figure><p>I visualized the latent topics learned from my LDA model, which pretty much looks like topics are formed based on issues, but on carefully looking at topics 0 and 1, we can notice some keywords that can be associated with political bias.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HMt6i6MBCPVVK1P4MP03kw.png" /><figcaption>Topic Modelling using LDA</figcaption></figure><p>For example, it looks like topic 1 has captured some left-wing political bias through keywords “trump”, “voting”, “election”, “voting”, “health” etc., keywords representing issues that are important to liberals.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bkzm2Xgi4sTvcetOveidPA.png" /></figure><p>While topic 0 seems like it has captured right-wing political bias to some extent through keywords “police”, “abortion”, “law” etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Dn1cjq3kdq6sYNj2MRl0XA.png" /></figure><p>Though LDA has captured some bias, the topics are mostly formed along with issues. Also, LDA performs poorly on sentiment analysis classification tasks. We will explore another document embedding method, called Doc2Vec</p><h3><strong>Doc2Vec:</strong></h3><p>Doc2Vec(Paragraph Vectors) is a generalization of the Word2vec model. The model in Doc2Vec learns vectors/embeddings(numerical representation of texts) for <strong>documents(</strong>the<strong> </strong>document can be a sentence, paragraph, or page<strong>)</strong> along with <strong>words</strong>. It is based on the <em>distributional hypothesis,</em> which assumes that words that appear in the same context, probably have a similar meaning.</p><p>Two variants “<em>Distributed Memory (PV-DM) </em>and <em>Distributed Bag-of-Words(PV-DBOW)” which are analogous to the methods in word2vec.</em></p><p>In <a href="https://towardsdatascience.com/nlp-101-word2vec-skip-gram-and-cbow-93512ee24314">word2vec</a> given a word, we try to predict its neighboring words(defined by a window size) or vice-versa. But we are not really interested in the input or output words, rather we are interested in the weights, which is a vector representation learned by the model during the process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6tkYGFl3iNJtubqnrjUaxg.png" /><figcaption>source:<a href="https://towardsdatascience.com/nlp-101-word2vec-skip-gram-and-cbow-93512ee24314">https://towardsdatascience.com/nlp-101-word2vec-skip-gram-and-cbow-93512ee24314</a></figcaption></figure><p>With Doc2Vec, we learn the embedding(vector) for each paragraph along with the words. (in PV-BOW there is only paragraph id).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*X5s5qs9BB_cbkJV3uiUS3Q.png" /></figure><p>Similar to the CBOW model of Word2Vec, the model learns to predict a center word based on the context. For example, given a sentence “The cat sat on sofa”, the CBOW model would learn to predict the word “sat” given the context words — the, cat, on, and sofa. Similarly, in PV-DM, the central idea is: randomly sample consecutive words from a paragraph and <strong><em>predict a center word</em></strong> from the randomly sampled set of words by taking as <strong><em>input — the context words and a paragraph id</em></strong>. In a paragraph matrix, each column represents the vector of a paragraph. By Average/Concatenate, it means whether the word vectors and paragraph vector are averaged or concatenated</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*DZaOrd4wDQVQbhXXcCuY_Q.png" /></figure><p>The distributed Bag Of Words (DBOW) model is slightly different from the PVDM model. The DBOW model “ignores the context words in the input, but forces the model to predict words randomly sampled from the paragraph in the output.” For the above example, let’s say that the model is learning by predicting 2 sampled words. So, in order to learn the document vector, two words are sampled from { the, cat, sat, on, the, sofa}, as shown in the diagram.</p><p>We will try both the variants discussed in the original paper. the PV-DBOW model and the PV-DM model( with average and concatenation of context words and paragraph id)</p><p>For performance measure, We will choose the F-beta score(with beta=0.5) as our focus to reduce false positives, i.e. We do not want the model to identify something as biased(right/left), when it is not biased(center-aligned or factual reporting). I am okay with my model identifying a few biased articles as not biased, as I have generously assigned bias to articles while labeling. So my focus is to give more importance to false-positive while not completely ignoring false negatives; i.e. More weight is given to precision than recall.</p><p>We will train each article as a document and learn their representation and afterward classify each document using the Logistic Regression classifier.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Dl9J5aQWMSWQJZNDd3fvEg.png" /><figcaption>beta = 0.5 gives recall half the importance of that of precision.</figcaption></figure><p>Among all three The PV-DBOW(Distributed Bag of Words) model had the best result, followed by PV-DM with concatenation and PV-DM with mean the poorest.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xyMkYjLmEs4I2VKb0jkrWA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aoNxBpNgL5LqY6CiOmNoGg.png" /></figure><p>The results are satisfactory as they are leaning more towards the “center” class, some moderately left or right-wing articles are also being labeled as “center”. But it’s performing well when finding similarities between texts. i.e. given a sufficiently biased article, it returns articles of similar bias from the corpus.</p><p>For example: Given the following article (tag- 9), which has a visible right-wing bias, it returns documents with similar biases.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H8laWPBHWqihUBjAdEA11A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ltseOwPf1z1xgG-5lWu2Tg.png" /></figure><p>Similarly Given an article (tag- 65) with left-wing bias, it returns documents with similar biases.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MvMesTKuXO3oDXl9YewVwA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*istKsDSlaHDly5ljx0L1-g.png" /></figure><p>But the issue here is that the model is learning document embedding based on keywords, i.e. in this case though the first two vectors are of similar bias and of the same issue/topic(abortion, Russian bounty), So when We look at the third most similar vector, it belongs to the same topic but of opposite political alignment. i.e. for tag 9 in the previous example, third and fourth similar vectors are of the same topic but different political bias.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*28Dz8lzCfa9cGJlRK2n1Ow.png" /></figure><p><strong>This suggests the model is learning the topic (presumably on keywords) but has failed to capture the underline bias through semantics.</strong></p><p>By closely studying few article contents i noticed that the biases (or the sentence that form bias) are used more with negative nouns and adjectives. Usually strong opinions or criticism use negative sentiment to grab the reader’s attention. (or that’s what newspapers intend to do). Below I have taken some examples of how strong(rather negative) words are used to emphasize a bias.</p><p><strong><em>Example 1</em></strong><em>: McEnany on Monday insisted that the intelligence wouldn’t be brought to Trump until it was verified, a claim that runs </em><strong><em>contrary</em></strong><em> to common sense (given the outsize risks that </em><strong><em>ignoring</em></strong><em> an unverified </em><strong><em>threat</em></strong><em> might pose) and reports suggesting that it in fact had been brought to the president’s attention.</em></p><p><strong><em>Example 2</em></strong><em>: Democrats would </em><strong><em>strip</em></strong><em> all of that away. The potential for </em><strong><em>fraud</em></strong><em> in such a system is obvious. But the liberal media keep telling you we have nothing to </em><strong><em>worry</em></strong><em> about, repeating over and over again that “there is no evidence voting by mail leads to voter fraud.”</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cEUAt15y0wezKRyD1X_-mA.png" /><figcaption>source: <a href="https://www.featurepics.com/online/Criticism-Words-2984120.aspx">https://www.featurepics.com/online/Criticism-Words-2984120.aspx</a></figcaption></figure><p>We will pick only sentences that contain negative words from a particular article for our training on all three models. This reduced the corpus size by half on average. Now we have a smaller but more relevant corpus for our task.</p><p>This though resulted in lower accuracy, now model doesn&#39;t directly learn from topic keywords, but <strong>it learns the underlined bias</strong> better than it did from the previous approach.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ncUzZPONemblj8IsRCWGpg.png" /><figcaption>Positive Similarity Results for PV-DM model with concatenation</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yg4hdXYHDxQSLrnNBIBufg.png" /><figcaption>Negative Similarity Results for PV-DM model with concatenation</figcaption></figure><p>You can find more illustrations in the <a href="https://github.com/mahanta-tapas/Political_Bias_American_Media/blob/master/Neutral_News_GridSearch.ipynb">Jupyter notebook</a>.</p><p>We see that the top two similar articles have the same political bias (left-wing) that of the test vector. But more importantly, they belong to<strong> different topics </strong>(Russian bounty, DACA). This tells us that model learning the underline bias which lacked in the previous approach. The flip side of this approach(keeping only negative word sentences) vs the previous approach (all text) is that the latter model has higher accuracy when classifying the documents using Logistic regression. Below are the CV score and best hyper-parameter found from GridSearch from all three variants.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/770/1*_tcBtCBC21cUZuN4yKTz2g.png" /></figure><p>Through all models have a lower CV scores, they perform considerably well for never-before-seen articles. Almost 20 percentage point improvement in accuracy for unseen articles compared to the majority prediction classifier ( majority vote of all 3 predictions)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kvygtYzw6Nd5PPXEcQnq2w.png" /><figcaption>Trained topic results</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*45WK7AQ1FIBK4ru43k2RXQ.png" /><figcaption>Never before seen topic results</figcaption></figure><p>Similar documents no longer belong to the same topic. Of course, the accuracy reduced. but now all the documents of similar bias are nearer to each other irrespective of topics. We can see this by plotting the t-sne vectors of the documents on Tableau and creating clusters.</p><p><strong>t-SNE</strong>(t-Distributed Stochastic Neighbor Embedding) plots of document vectors learned by the model. it’s a technique primarily used to<strong> </strong>visualize high-level representations learned by an artificial neural network. In simpler terms, t-SNE gives you a feel or intuition of how the data is arranged in a high-dimensional space</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9U95Gaec7GZU-Dc4GHJm7A.png" /><figcaption>tsne plots of document vectors learned by the model.</figcaption></figure><p>We see that for the most part documents of similar political bias are closer together inside a cluster. We can achieve good results with any distance-based clustering algorithm.</p><p>To understand more about what keyword or pattern the model has learned from the data, which it is using to classify news articles, we plot the popular keywords from articles the model predicted as left, right, or center.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N2O7ZrmLuu9Xm4wzoN-jBQ.png" /><figcaption>Most Popular keywords on left-wing articles</figcaption></figure><p>We can see the issues, persons, or organizations that are the point of focus or criticism for liberals and conservatives.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PeTNmyAU1wDVAMtKtfN8Gw.png" /><figcaption>Most Popular keywords on rightwing articles</figcaption></figure><p>We also see the topics which are least politicized that include schools, students, police, etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6ODL6B14niyx4B7uOd2EIQ.png" /></figure><p>Political bias can often fall in the grey area and is subjective. Therefore there is always scope for improvement. The Next improvements that can be done on to improve are:</p><ol><li>As I have mentioned above, the labeling of articles was done by me, you can contribute by labeling the data. I have posted a <a href="https://drive.google.com/file/d/1Rg6zXtQh9X0_oeFfO9p6SNyqz6TuuEM9/view?usp=sharing">link</a> to a shared spreadsheet, feel free to update the bias(Alignment column) in the data, this will help make the solution more robust.</li><li>We can try other classifiers other than Logistic regression.</li><li>Distance-based clustering algorithms such as KNN with varying n to provide majority prediction should perform well based on what we have seen in the tableau representations of t-sne vectors we saw before.</li><li>PV-BOW was able to recognize only left bias, while PV-DMM was able to recognize only the right bias. This can be tweaked further for better results.</li></ol><p>You can find all the code for scraping the data and modeling <a href="https://github.com/mahanta-tapas/Political_Bias_American_Media">here</a>.</p><h3><strong>Bonus :</strong></h3><p>Also when we cluster the document vectors, the model seemed to have differentiated the articles both based on source and bias. From the t-sne graph, we see that the top-left quadrant has a majority of articles from the Washingtonpost and the majority of FOXNews articles are on the bottom right quadrant while USAToday articles lie on the third (bottom left quadrant).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ptlV8NnOvl8XlViiO_Fr9g.png" /></figure><p>Putting the same articles on a political bias(alignment) tag, we can see though a similar division exists (left-wing articles on top-left and right on bottom-right), a lot of articles on both left and right quadrant become center aligned.</p><p>This suggests though there exists a clear division in writing styles of both the newspapers, division based on political bias is not directly proportional to the news source. We can see a few articles from all sources showing the center align.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*htC8eHFWCfLlp5WSC5uoYg.png" /></figure><h3>References:</h3><blockquote><a href="https://towardsdatascience.com/document-embedding-techniques-fed3e7a6a25d">https://towardsdatascience.com/document-embedding-techniques-fed3e7a6a25d</a></blockquote><blockquote><a href="https://towardsdatascience.com/nlp-101-word2vec-skip-gram-and-cbow-93512ee24314">https://towardsdatascience.com/nlp-101-word2vec-skip-gram-and-cbow-93512ee24314</a></blockquote><blockquote><a href="https://medium.com/swlh/a-text-classification-approach-using-vector-space-modelling-doc2vec-pca-74fb6fd73760">https://medium.com/swlh/a-text-classification-approach-using-vector-space-modelling-doc2vec-pca-74fb6fd73760</a></blockquote><blockquote><a href="https://medium.com/@amarbudhiraja/understanding-document-embeddings-of-doc2vec-bfe7237a26da">https://medium.com/@amarbudhiraja/understanding-document-embeddings-of-doc2vec-bfe7237a26da</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d61a9e793aa9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Linear Probability, Logistic and Choice Model]]></title>
            <link>https://mahanta-tapas.medium.com/linear-probability-logistic-and-choice-model-b29ca3cd4b7a?source=rss-23fe29d8dcec------2</link>
            <guid isPermaLink="false">https://medium.com/p/b29ca3cd4b7a</guid>
            <category><![CDATA[probit]]></category>
            <category><![CDATA[logistic-regression]]></category>
            <category><![CDATA[regression]]></category>
            <dc:creator><![CDATA[Tapas Mahanta]]></dc:creator>
            <pubDate>Fri, 24 Apr 2020 23:08:45 GMT</pubDate>
            <atom:updated>2020-04-24T23:08:45.647Z</atom:updated>
            <content:encoded><![CDATA[<p>The dependent variable is binary and assumes the probability of the dependent variable is a linear function of regressors.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SWlxeDQeicurgpAjWXMYiw.png" /></figure><p>As we model probability using a linear model(straight line), there is a possibility that we can have predictions of greater than 1 or less than zero has for probability (homoscedasticity), which is meaningless. But sometimes the linear probability model is preferred as it is easy to interpret.</p><p>To avoid predicting probabilities of &gt;1 and &lt;0, we need a non-linear (sigmoid) model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vco5_QiiMrjIBUjQsTr7aQ.png" /></figure><p>So Now our desired Y/Outcome variable stays between 0 and 1, but we lose the simplicity of linear models.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A6GsfR-KO8lhZvRDUlLXqg.png" /></figure><p>With basic mathematical transformations, we can interpret the Logistic Regression in terms of probability ratios instead of just one probability, using either Equation 1 or 2.</p><p>NOTE: Probability ratios can be interpreted as odds.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lATIi8HH821PuZF-s7CYMg.png" /></figure><p><strong>Interpretation</strong></p><p>SAS Provides these two interpretations by default.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dIkxYyJOhB187IBs__SFZQ.png" /></figure><p>exp(<em>Bj) </em>is always positive. it is greater than 1 if Bj is positive and less than 1 if Bj is negative. i.e. if the co-efficient Bj is positive, the ratio of odds will increase by a factor greater than 1, therefore there is a higher probability that “Event 1” occurs. And if Bj is negative, the ratio of odds will increase by a factor less than 1, therefore there is less probability that “Event 1” will occur.</p><p>No longer OLS is a valid method for estimation of coefficients. Most systems use the maximum likelihood method.</p><h3>Latent Utility Theory/Choice Model</h3><p>For a multinomial dependent variable(with more than two qualitative values), we prefer a more generalized version of the Logistic model, and to study this we need to define the “choice/benefit/utility” of a consumer.</p><p>Utility: Consumers chose the product with the highest utility/benefit.</p><p>So we say customer choosing an option J, means she gets maximum utility/benefit from buying J out of all other choices, based on this we try to predict the utilities of different brands(or maximum utility) for a new customer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F8-PsIwfRyMPZjlGwAp6og.png" /></figure><p>NOTE: Utility is a relative term and defined within the choices given.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0K70KD-x6aOHN6G0FV_pDg.png" /></figure><p>Now that we have defined the <strong>Utility</strong>(probability of purchasing a brand), we can extend the logistic model to handle more than two choices/brands.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T35Xtl0Ys3yrhCEDIzOmcA.png" /></figure><p>Multinomial Logistic Model is a generalization of the logistic model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xNFLznlKRo3DaQ7t9otfJg.png" /></figure><h3><strong>Interpretation of the Choice Model</strong></h3><p>Because Utility is a relative term, we need to fix a reference by setting the intercept to 0 for comparison between them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hZi3JSd4ZuUP0A-p-CZTJw.png" /></figure><p>Brand Equity Effect: When everything else is the same, what is the preference of the user, is given by intercept.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ym_EMxU7hlcquV6n8ULNmw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EzLPhRMXsW-93FXPRXpZOA.png" /></figure><p>Because everything is a low priced product and we do not think price will be a great differentiator. So we chose the same co-efficient for the price for all three brands.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_TeZ3XsyUewNeMRE2rwqBg.png" /></figure><h3>Limitations of the Choice Model</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DFTiwWs-UQlgfZfPllUhPA.png" /></figure><p><strong>Example</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iRQbEE6xMhpMd3UECD7VoQ.png" /></figure><p>With the introduction of the new Blue Bus company, we would expect the market share of Red Bus to reduce by half to 25% and the market share of the train to remain the same. But the model suggests each market share will be equal at 33.33%.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b29ca3cd4b7a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Time Series Part 2]]></title>
            <link>https://mahanta-tapas.medium.com/time-series-part-2-383883c6490?source=rss-23fe29d8dcec------2</link>
            <guid isPermaLink="false">https://medium.com/p/383883c6490</guid>
            <category><![CDATA[time-series-analysis]]></category>
            <dc:creator><![CDATA[Tapas Mahanta]]></dc:creator>
            <pubDate>Sat, 28 Mar 2020 00:12:18 GMT</pubDate>
            <atom:updated>2020-03-28T00:12:18.705Z</atom:updated>
            <content:encoded><![CDATA[<p>ARIMA</p><p>Auto-Regressive Integrated Moving Average</p><p>Seasonal and Non-Seasonal</p><p>Non-Seasonal (p,d,q)</p><p>(AR)p- no of time previous time periods used to forecast.</p><p>(I)d- No of differencing/transformations used to convert time-series to stationary.</p><p>Stationary Time-series is when Mean and Variance are constant over time. We tend to underestimate the mean and variance in a non-stationary time-series, that is why it should be converted to stationary time series.</p><p>(MA)q- lags of the error component.</p><p>Auto-Correlation — How Co-related a time-series is with it’s past values.</p><p>Auto- Correlation usually decreases with first, second differences of the time series.</p><p>AR</p><p>MA</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eZAc6_RmfYgtktmnZbdUVQ.png" /></figure><p>The ACF(Auto Correlation) plot helps us decide between choosing AR or MA components.</p><p>Analyzing the plot above, we have a suggestion of an AR(1) model because after we stationarized the dataset through differencing, there was positive autocorrelation at lag-1 and then the autocorrelation cuts off to zero.</p><p>If the Stationarized series has +ve Auto-Correlation at lag 1, use AR terms, if it has -ve Auto-Correlation at lag 1 at lag 1 then MA terms are better.</p><p>The decay/cut-off will give us hints towards what terms to use as well as spikes decaying towards 0.</p><p>When to use AR or MA terms.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CZCzOstZYzhQ5GfaTTBy0w.png" /></figure><p>Partial Auto-Correlation</p><p>Auto-Correlation between a current period and a lag period(lag2) , while controlling for the value of another lag(lag 1) is called Partial auto-correlation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JcLA0kMTulNJx17_GeAMiQ.png" /></figure><p>In Linear Regression terms, the more AR terms you use the more previous terms in the forecast.</p><p>ACF and PCF graphs help us determine how many AR terms we need to account for the Auto-Correlation in the series.</p><p>Auto-Regression is to account for Auto-Correlation???</p><p>Non-Seasonal vs Seasonal ARIMA</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l8M84W7RRb5IRGWV_OXxIA.png" /></figure><p>m — no of periods in the season</p><p>(P, D, Q) — Auto-Regressive, differencing and Moving Average for the seasonal part of the ARIMA model.</p><p>Non-Seasonal differencing and Seasonal differencing are combined to staionaraize the series.</p><p>The seasonal component in seasonal ARIMA is the same as regular component except the lag is 1 season (12 months, or 365 days).</p><p>Hold out period should be at least as long as test period.</p><p>Residual Plots: Residuals should be uncorrelated.</p><p>They should have a mean close to zero and very few auto-correlation.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=383883c6490" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Time Series Part 1]]></title>
            <link>https://mahanta-tapas.medium.com/time-series-part-1-5be612067342?source=rss-23fe29d8dcec------2</link>
            <guid isPermaLink="false">https://medium.com/p/5be612067342</guid>
            <category><![CDATA[time-series-analysis]]></category>
            <dc:creator><![CDATA[Tapas Mahanta]]></dc:creator>
            <pubDate>Fri, 27 Mar 2020 21:46:12 GMT</pubDate>
            <atom:updated>2020-03-27T21:46:12.351Z</atom:updated>
            <content:encoded><![CDATA[<p>Methodology Map</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kvZGGF4brnZXUU-WfKuhyw.png" /></figure><p>Simple Forecasting Methods</p><p>Average Method</p><p>Moving Average over a time period</p><p>Naive Method — Use the previous observation value.</p><p>Seasonal Naive — Use the observation in same season last year?</p><p>Components of a Time Series</p><p>Trend: Gradual shift to higher or lower values over a long period of time.</p><p>Up trend, Down trend or Stationary</p><p>Example of an upward trend</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TtHG6Hk2r_2g6JTPACw2IQ.png" /></figure><p>Seasonality</p><p>Regular occurring fluctuations in the same calendar year</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/954/1*vNz7A_YQVgcKOzHGLUeb9Q.png" /></figure><p>Cyclic pattern</p><p>Data exhibit rise and fall(Fluctuations) that are not in a fixed period</p><p>Stock market bull and bear cycles. Business cycles etc.</p><p>These are very hard to predict</p><p>Exponential Smoothing Models</p><p>ETS Time Series Forecasting</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CyVjqpTQhhpizpTTv88FLA.png" /></figure><p>Each of these terms Error, Trend and Seasonality can be either added additively, multiplicatively or left out for smoothing method calculations.</p><p>Time Series Decomposition</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J0yFy2eBFfkqBw4Q0tsoBg.png" /></figure><p>Seasonal Patterns with increasing seasonal values.</p><p>Upward trend. (calculated by moving average, also called deseasonalized)</p><p>Error term: Difference between Observed valued and trend line estimates. It is the remainder that is not accounted for by combining seasonality and trend.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FJvY_l-PeNeEwZbe-KDkUQ.png" /></figure><p>Additive Seasonality (Sales up by 50 Units every January) show linear behavior, while multiplicative Seasonality(bookings increased 1.5 times every April)show exponential behavior.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F2YMt_6KPA6ENv09ltqo4g.png" /></figure><p>We will explore different ETS Models that help us forecast different time series scenarios.</p><p>Simple Exponential smoothing vs Moving Average</p><p>Exponential smoothing get rids of new data faster through weights, but more sensitive to sudden large and small values.</p><p>The <strong>simple exponential smoothing</strong> method does not account for any trend or seasonal components, rather, it only uses the decreasing weights to forecast future results. This makes the method <strong>suitable only for time series without trend and seasonality.</strong></p><p>Double exponential smoothing or Holt’s Linear Trend Method (Accounts for Trend and seasonality not</p><p>Damped Trend Methods</p><p>Holt-Winters Seasonal Method</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5be612067342" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stochastic, Batch and Mini Batch Gradient Descent]]></title>
            <link>https://mahanta-tapas.medium.com/stochastic-batch-and-mini-batch-gradient-descent-b16e50863f?source=rss-23fe29d8dcec------2</link>
            <guid isPermaLink="false">https://medium.com/p/b16e50863f</guid>
            <category><![CDATA[linear-regression]]></category>
            <category><![CDATA[gradient-descent]]></category>
            <dc:creator><![CDATA[Tapas Mahanta]]></dc:creator>
            <pubDate>Sun, 22 Mar 2020 23:12:21 GMT</pubDate>
            <atom:updated>2020-03-22T23:12:21.133Z</atom:updated>
            <content:encoded><![CDATA[<p>Linear regression cost function</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Yjqe5bNW0MZ-1Lr3.png" /></figure><p>Stochastic, Batch and Mini Batch Gradient Descent</p><p><strong>Batch Gradient Descent</strong></p><p>In Batch Gradient Descent, all the training data is taken into consideration to take a single step. We take the average of the gradients of all the training examples and then use that mean gradient to update our parameters. So that’s just one step of gradient descent in one epoch/iteration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VY-_SYpvY_Zlaf83.png" /></figure><p>Because Batch gradient descent computes the gradient using the whole dataset. This is great for convex or relatively smooth error functions. In this case, we move somewhat directly towards an optimum solution, either local or global.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/588/0*uccb1MHRgulllG2l.png" /><figcaption>Cost vs Epochs (Source: <a href="https://www.bogotobogo.com/python/scikit-learn/scikit-learn_batch-gradient-descent-versus-stochastic-gradient-descent.php">https://www.bogotobogo.com/python/scikit-learn/scikit-learn_batch-gradient-descent-versus-stochastic-gradient-descent.php</a>)</figcaption></figure><p>The graph of cost vs epochs is also quite smooth because we are averaging over all the gradients of training data for a single step. The cost keeps on decreasing over the epochs.</p><p><strong>Stochastic Gradient Descent</strong></p><p>we consider just one example at a time to take a single step. We do the following steps in <strong>one epoch</strong> for SGD:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UkYzOld-OMa9yliV.png" /></figure><p>Because single samples are really noisy, in SGD cost will fluctuate over the training examples and it will <strong>not </strong>necessarily decrease. In the long run, it will eventually decrease but as the cost is so fluctuating, it will never reach the minima but it will keep dancing around it.</p><p>SGD works better than batch gradient descent for error functions that have lots of local maxima/minima as the somewhat noisier gradient tends to jerk the model out of local minima into a region that hopefully is more optimal.</p><p>The amount of jerk is reduced when using mini-batches. A good balance is struck when the minibatch size is small enough to avoid some of the poor local minima but large enough that it doesn’t avoid the global minima.</p><p><strong>Batch Gradient Descent can be used for smoother curves. SGD can be used when the dataset is large</strong></p><p>Mini Batch gradient descent</p><p>Neither we use all the dataset all at once nor we use a single example at a time. We use a batch of a fixed number of training examples which is less than the actual dataset and call it a mini-batch. Doing this helps us achieve the advantages of both the former variants we saw.</p><p>Mini-batch gradient descent uses <strong>n</strong> data points (instead of <strong>1</strong> sample in SGD) at each iteration.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b16e50863f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>