<?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 Manish Sharma on Medium]]></title>
        <description><![CDATA[Stories by Manish Sharma on Medium]]></description>
        <link>https://medium.com/@manishthemanu?source=rss-7c5de1a10636------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*wgndjo6mpVf40aWH4MOQQQ.jpeg</url>
            <title>Stories by Manish Sharma on Medium</title>
            <link>https://medium.com/@manishthemanu?source=rss-7c5de1a10636------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 05:57:14 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@manishthemanu/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[Support Vector Machine (SVM)]]></title>
            <link>https://medium.com/data-science/support-vector-machine-svm-719e530a725f?source=rss-7c5de1a10636------2</link>
            <guid isPermaLink="false">https://medium.com/p/719e530a725f</guid>
            <category><![CDATA[linear-svm]]></category>
            <category><![CDATA[support-vector-machine]]></category>
            <category><![CDATA[svm]]></category>
            <category><![CDATA[kernel]]></category>
            <dc:creator><![CDATA[Manish Sharma]]></dc:creator>
            <pubDate>Sun, 16 May 2021 22:32:54 GMT</pubDate>
            <atom:updated>2021-05-16T22:32:54.645Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5stif7Jjmmdclx7-qTDBgQ.jpeg" /><figcaption>Source: Unsplash.com</figcaption></figure><h4>All about Support Vector Machines (SVM) from derivation to interview preparation</h4><p>Recently I got an opportunity to prepare a lecture on SVM for a group that had a mix of freshers and experienced people in data science. I prepared a lecture that involves basics and even an intuition for the derivation of SVM (vector method) and also some questions along with answers in the discussion section. I hope the lecture can benefit a larger audience. Do let me know in the comment section what more would you expect in a lecture on an ML algorithm in the future.</p><h3><strong>Background of SVM</strong></h3><p>SVM is</p><ul><li>Supervised Machine Learning Algorithm</li><li>Used for <strong>Classification</strong> and Regression</li></ul><p>The real strength of SVM lies in the classification and to be the specific classification of vectors with high dimensionality (data points with a large number of features). Although the support vector regressor (SVR) also uses the same intuition and concept as of support vector classifier but for regression linear or random forest regressor are also strong competitors to SVR. We would focus on classification using a support vector classifier and not on regression.</p><h3>Optimization of SVM</h3><p>Optimization depends upon the <strong>dot product of the pairs of vectors</strong></p><ul><li>Derivation (proof of the fact that optimization in SVM classifier depends only on the product of pairs of vectors).</li></ul><p>Assume a binary classification problem as shown in figure 1, in order to separate the two classes in 2D a decision boundary needs to be decided. If the boundary separating the classes is linear the classes are said to be linearly separable. Figure 1 shows the vectors (data points) for two different classes + and negative.</p><figure><img alt="Vectors belonging to two different classes" src="https://cdn-images-1.medium.com/max/662/1*ICbtAl_QhIFY9bC4Owrf4w.jpeg" /><figcaption>Figure 1</figcaption></figure><p>Multiple lines can act as the decision boundary which separates the two classes (look at figure 2). Any of the blue, yellow or green line may act as a decision boundary as all three of them separates the data. How shall we decide which of these boundaries separates the data best? This decision would give us a condition using which we can reject all but one decision boundary among all the possibilities.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/662/1*5alNhw37i0Axn3KjYlnijA.jpeg" /><figcaption>Figure 2</figcaption></figure><p>To define the best decision boundary we use the principle of maximum margin. The boundary which is at the maximum distance from the nearest members of both the class is selected as the best boundary. In figure 3, shown below the hashed lines are the lines passing through the nearest points of the + and — class. Distance from the yellow line to the hashed line is defined as the margin. Given that among all the possible lines separating the two classes if the yellow line has the widest separation between the margins then the yellow line is the best decision boundary. The points of both the classes through which the hashed yellow line passes is/are known as support vector(s). There can be a single support vector (as for + class) or there can be multiple support vectors (as for — class), the slope of the hashed line would be the same as the decision boundary.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/809/1*Od3UZ7MerG8iOgoC_fX9cg.jpeg" /><figcaption>Figure 3</figcaption></figure><p>In order to maximize the margins or distance between two hashed lines, we need to create an expression and take a derivative of it to find the optimum (extremum) value. Assume a vector ‘w’ which is normal to the decision boundary and an unknown vector ‘u’, as shown below in figure 4. To decide whether the unknown vector u lies on the side of — ive or + ive class we measure the length of the projection of u on w if it is greater than a certain length it is in +ive class or else it belongs to -ive class (or lies on the margin).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uG4lM1wu_vLih7WlqlEpNA.jpeg" /><figcaption>Figure 4</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/428/1*z9amQrhEZtTandRJLXgA3g.jpeg" /></figure><p>To differentiate between + and — class we assume that if the unknown vector is a vector from + class (x+ ) it should give a value greater than one or if it is a vector from — class (x− ) it should give a value less than -1. +1 and -1 value is decided to bring in the clear separation between both the classes. So mathematically the condition is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/407/1*NRffDKbRDzkRZ_rjM_EX7Q.jpeg" /></figure><p>For mathematical convenience let’s introduce a variable yi such that yi = 1 for + samples and yi = -1 for — samples. Multiplying yi with the equations above we get:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/339/1*Q-solScVefiqUlA_4G3XWg.jpeg" /></figure><p>The support vector from + class (x+sv) and — class (x−sv) lies on the margin itself. So the projection of the vector (x+sv−x−sv) ⋅w/|w| on normal w is the distance between the margins. This distance should be maximized with the constraints given above.</p><ul><li>Maximize:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/368/1*Ep_MPn2S6M2aWG32MDEDxw.jpeg" /></figure><p>From the above equations we can decipher:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/308/1*vnXG8t5jQII9L7r_4hXCiw.jpeg" /></figure><p>thus the maximization condition becomes maximum of 2/|w| or we can say minimum of:</p><ul><li><strong>minimize:</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/251/1*20J8kDO9DG8spbEHELaLLg.jpeg" /></figure><ul><li><strong>constraint:</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/383/1*XMQlne3NGMWwJH68rjvtYQ.jpeg" /></figure><p>To find extremum along with a constraint we use Langrangian,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/541/1*2UYJkI5fUHnyn04yGVh-cw.jpeg" /></figure><p>The minimum of Lagrangian is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/550/1*KklpyrEVSua5ltWr-4r5Ug.jpeg" /></figure><p>Here in the above expression, you can observe that the minimum value (our optimization) depends upon the dot product of pair of two vectors (data points).</p><h3>If classes are linearly non-separable</h3><p>In such cases adding extra features and transforming the vectors to higher dimensions might help in separating the vectors by a plane (hyper plane). For example, assume two classes c1(blue) and c2(orange) shown in figure 5 below. <strong>There seems to be no linear decision boundary for the two classes. What if a new dimension is added to the data x_2 = (x1)²</strong>.</p><p>Non linearly separable data:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/672/1*zX0Mf6GSoqEbB0t-ry6vag.jpeg" /><figcaption>Figure 5</figcaption></figure><p>Transformed data which is now linearly separable (shown in figure 6):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/663/1*Cav6_UaRwAU_2qNayl0Qwg.jpeg" /><figcaption>Figure 6</figcaption></figure><p>Similarly, with 2-dimensional data containing x1 and x2 dimension new dimensions like <strong>(x1)², (x2)², (x1)3</strong> e.t.c can be created and data can be transformed to a higher dimension to separate the classes.</p><p>We have some functions which can help to transform the data to higher dimensions. These functions are known as kernels.</p><h3>Some popular Kernels in SVM</h3><ul><li><strong>Linear</strong></li><li>Polynomial</li><li>Gaussian</li><li>Radial Basis Function (RBF)</li><li>Hyperbolic</li><li>Sigmoid</li></ul><h3>Discussion (Interview QnA)</h3><ol><li><strong>Generic question for any algorithm: ADA? (Advantages, Disadvantages and Assumptions)</strong></li></ol><p><strong>Advantages:</strong></p><ul><li>Turnkey algorithm, very few parameters to optimize.</li><li>Optimization is in convex space so a global minimum is reached unlike neural network it doesn’t suffer with problem of stucking at local minima.</li><li>Memory efficient</li><li>Linear SVM is more effective than other algorithm if the number of features are highe (&gt;1000)</li></ul><p><strong>Disadvantages:</strong></p><ul><li>Feature scaling</li><li>Tends to get slower as number of examples increases</li><li>Hard margin leads to overfitting</li></ul><p><strong>Assumptions:</strong></p><ul><li>None</li></ul><p><strong>2. Explain hard and soft margin in context with SVM.</strong></p><ul><li><strong>Hard Margin</strong> Does not allow any error</li><li><strong>Soft Margin</strong> Allow error, it reduces the chance of overfitting</li></ul><p><strong>3. Why does SVM gets slower when the number of examples increases?</strong></p><p>The computation cost depends upon the selection of pair of vectors (nC2, as derived in the optimization section).</p><p>4. <strong>What are the hyperparameters associated with SVM?</strong></p><ul><li>Kernel</li><li>C: Number of permitted errors. Large C gives a narrow margin and vice versa.</li></ul><p><strong>5. Why the SVM algorithm is known to be memory efficient?</strong></p><p>Not all the data points are required to make the decision, once the support vectors are decided only the support vectors and equation of the hyperplane is required to make the decision.</p><p><strong>6</strong>. <strong>State the statement is True or False: ‘SVM decision boundary is perpendicular bisector to the line joining the closest point of convex hull of the two classes’.</strong></p><p>True statement. Geometrical explanation: make the convex hull of each of the classes, try to join the convex hulls using the closest point and the classification boundary will be the perpendicular bisector.</p><p><strong>7.</strong> <strong>Give a typical example where SVM will be used over RandomForest.</strong></p><p>Text classification: SVM is an algorithm of choice for higher-dimensional space when the number of features is large.</p><p><strong>8.</strong> <strong>What is regularization? How is an SVM algorithm regularized? Is it L1 or L2 regularization in nature?</strong></p><p>‘C parameter’ is actually the <strong>regularization parameter</strong>. The C parameter is multiplied by the sum of errors thus the regularization, in general, is L1 in nature. But if the cost function is modified in such a way that the cost of SVM is C multiplied by the sum of squares of the error the regularization becomes L2 in nature.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/653/1*5_YWJEdDZ5yEc7Ipyu4gSg.jpeg" /></figure><h3>Recommended Readings</h3><ul><li>Do look for other methods of derivation (linear algebra method)</li><li>Mercer’s Theorem</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=719e530a725f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/support-vector-machine-svm-719e530a725f">Support Vector Machine (SVM)</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[Sentiment Analysis (Introduction to Naive Bayes Algorithm)]]></title>
            <link>https://medium.com/data-science/sentiment-analysis-introduction-to-naive-bayes-algorithm-96831d77ac91?source=rss-7c5de1a10636------2</link>
            <guid isPermaLink="false">https://medium.com/p/96831d77ac91</guid>
            <category><![CDATA[tf-idf-vectorizer]]></category>
            <category><![CDATA[text-analysis]]></category>
            <category><![CDATA[sentiment-analysis]]></category>
            <category><![CDATA[naive-bayes-classifier]]></category>
            <category><![CDATA[count-vectorizer]]></category>
            <dc:creator><![CDATA[Manish Sharma]]></dc:creator>
            <pubDate>Sun, 10 May 2020 17:36:52 GMT</pubDate>
            <atom:updated>2020-05-11T15:46:17.956Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*doy-O2kRpEJw6WJzALB6Uw.jpeg" /><figcaption>Source: stocksnap.io</figcaption></figure><h3>Sentiment Analysis: An Introduction to Naive Bayes Algorithm</h3><p>DataSet: <a href="https://www.kaggle.com/c/sentiment-analysis-on-movie-reviews/data">https://www.kaggle.com/c/sentiment-analysis-on-movie-reviews/data</a></p><p>This tutorial assumes a reader to be utterly naive about the Bayes theorem and text analysis. You just need to follow the tutorial and everything is explained for a fresher to AI/ML. In case you are a pro user and wish to quickly revise the concept <strong>you may access the code on </strong><a href="https://github.com/DrManishSharma/NLP.git"><strong>my github repository</strong></a><strong> (Senti_Analysis.ipynb)</strong>.</p><p>Given any kind of data science project very first thing you need to do is to load the data and play with it. I prefer (also most of the data scientist I know) to used Pandas for downloading the data (figure 1). The given data is in *.tsv format (tab-separated variables). I have converted it to *.csv using excel while one can work with *.tsv format too. While I loaded the data I encountered a small problem due to special characters being used in some rows ( around 4 row contains \/, division and backslash). I had to manually delete these characters before loading the data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/607/1*7Nj9Fc_L6Z4drTK2ttatOg.jpeg" /><figcaption>Figure 1: Loading the data</figcaption></figure><p>I highly encourage new users to use basic pandas command to play with the days. You may use: dataset.info() to get the summary of different columns, if any column contains any row with NAN data(if yes, then how many?). Use dataset.head(), dataset.tail(), dataset.describe(), dataset[‘$ColumnName’] e.t.c to gain more insight into the dataset. For example (figure 2) uses dataset.$ColumnName.value_counts() to give the count of each kind of sentiment(let 0 be single star review, 4 be five star review). From here we can guess that on an average this movie seems to be a three-star rating movie.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*EKBC_SwCz7jXchu6R2aBrw.jpeg" /><figcaption>Figure 2: Use of basic pandas commands</figcaption></figure><p>To proceed further with the sentiment analysis we need to do text classification. We can use ‘bag of words (BOW)’ model for the analysis. In laymen terms, BOW model converts text in the form of numbers which can then be used in an algorithm for analysis.</p><p>Specifically, BOW model is used for feature extraction in text data. It returns a vector with all the words and the number of times each word is repeated. It is known as BOW because it is only concerned with the number of times a word is repeated rather than the order of words. Let’s take an example to understand it better (assume each document contains a sentence only):</p><p>Doc1: Switzerland is a beautiful country. <br>Doc2: India is a country of smart IT professionals. <br>Doc3: USA is a country of opportunities.</p><p>The table below is known as the document term matrix (DTM). <br> — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — <br>| Words -&gt; Swzld is a beautiful country India of smart IT prof USA opport <br>| Doc 1 Vector -&gt; 1 1 1 1 1 0 0 0 0 0 0 0 <br>| Doc 2 Vector -&gt; 0 1 1 0 1 1 1 1 1 1 0 0 <br>| Doc 3 Vector -&gt; 0 1 1 0 1 0 1 0 0 0 1 1 <br>| Cumulative -&gt; 1 3 3 1 3 1 2 1 1 1 1 1 <br> — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — <br>The model shown above is a monogram model. If two words are taken at a time (for ex: Switzerland is, is a, a beautiful, beautiful country, … ) then it is known as the bi-gram model similarly for N-words at a time it will be N-gram model. A higher gram model tends to work better than the monogram model.</p><p>More the content in each document lengthier would be the length of each vector (will contain a lot of zeros). Doc vectors would be a sparse vector if documents are too large. Sparse vectors need a lot of memory for storage and due to length, even computation becomes slow. To reduce the length of the sparse vectors, one may use the technique like stemming, lemmatization, converting to lower case or ignoring stop-words e.t.c.</p><p>Now, we will generate DTM using CountVectorizer module of sci-kit-learn (figure 3). To read more about the arguments of CountVectorizer you may visit <a href="https://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.text.CountVectorizer.html"><strong>here</strong></a>. As discussed above we will use:</p><ul><li>tokenizer = Overrides the string tokenization step, we generate tokenizer from NLTK’s Regex tokenizer (by default: None)</li><li>lowercase = True (no need to use, as it is set True by default)</li><li>stop_words = ‘english’ (by default None is used, to improve the result we can provide a custom made list of stop words)</li><li>ngram_range = (1,1) (by default its (1,1) i.e strictly monograms will be used, (2,2) only bigrams while (1,2) uses both)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MxC2AvW8JLQVTmOkEafQfQ.jpeg" /><figcaption>Figure 3: Using CountVectorizer to prepare the ‘bag of words’</figcaption></figure><p>We will now split the data for training and testing to check how well our model has performed (figure 3). Also, we will randomize the data in case our data includes all the positive first and then all negative or some other kind of bias. We will use: scikit_learn’s <a href="https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.train_test_split.html"><strong>train_test_split()</strong></a> for splitting the text_count (which contains our X) and dataset[‘Sentiment’] (this contains Y).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GBvl2GEEyndwB4E0Uex9pg.jpeg" /><figcaption>Figure 4: Using train_test_split to divide the data into training and testing datasets.</figcaption></figure><p>Now we have the training and testing data. We should start the analysis. Our analysis (as most of the ML analysis) will be in 5 steps(a mnemonic to remember them is <strong>DC-FEM</strong> remember as District of Columbia Fire and Emergency Medical service):</p><ol><li>Defining the model</li><li>Compiling the model</li><li>Fitting the model</li><li>Evaluating the model</li><li>Making predictions with the model</li></ol><h3>1. Defining the model</h3><p>We will use one of the <a href="https://scikit-learn.org/stable/modules/naive_bayes.html"><strong>Naive Bayes (NB)</strong></a> classifier for defining the model. Specifically, we will use <a href="https://scikit-learn.org/stable/modules/naive_bayes.html"><strong>MultinomialNB classifier</strong></a>. As a fresher to ML one can use cheat sheet given by sklearn <a href="https://scikit-learn.org/stable/tutorial/machine_learning_map/index.html"><strong>here</strong></a> to determine the best model to use for a particular problem. It tells us to use NB classifier. Let us take a detour to learn more about the NB model.</p><h4>Naive Bayes Model</h4><p>This model applies Bayes theorem with a Naive assumption of no relationship between different features. According to Bayes theorem:</p><p>Posterior = likelihood * proposition/evidence</p><p>or</p><p>P(A|B) = P(B|A) * P(A)/P(B)</p><p><strong>For ex: In a deck of playing cards, a card is chosen. What is the probability of a card being queen given the card is a face card?</strong><br>This can be solved using Bayes theorem.<br>P(Queen given Face card) = P(Queen|Face)<br>P(Face given Queen) = P(Face|Queen) = 1<br>P(Queen) = 4/52 = 1/13 P(Face) = 3/13 From Bayes theore:<br>P(Queen|Face) = P(Face|Queen) P(Queen)/P(Face) = 1/3</p><p>For an input with several variables:<br>P(y|x1, x2, … xn) = P(x1, x2, … xn|y)* P(y)/P(x1,x2, …xn)<br>with Naive Bayes we assume x1, x2 … xn are independent of each other, i.e:<br>P(x1, x2, … xn|y) = P(x1|y) * P(x2|y) … * P(xn|y)<br>The assumption in distribution of P(xi|y) give rise to different NBM. For example assuming Gaussian distribution will give rise to Gaussian Naive Bayes (GNB) or multinomial distribusion will give Multinomial Naive Bayes (MNB).</p><p>Naive Bayes Model works particularly well with text classification and spam filtering. <strong>Advantages</strong> of working with NB algorithm are:</p><ul><li>Requires a small amount of training data to learn the parameters</li><li>Can be trained relatively fast compared to sophisticated models</li></ul><p><strong>The main disadvantage</strong> of NB Algorithm is:</p><ul><li>It’s a decent classifier but a bad estimator</li><li>It works well with discrete values but won’t work with continuous values (can’t be used in a regression)</li></ul><h4>The dilemma of NB Algorithm</h4><p>A challenging question which can be asked regarding NB algorithm is: although the conditional independence assumption in NB algorithm is hardly true in real life then how come NB Algorithm work so well as a classifier? I won’t discuss the solution here, rather will direct you towards the resource which contains the solution (<a href="https://www.cs.unb.ca/~hzhang/publications/FLAIRS04ZhangH.pdf"><strong>here</strong></a>). In short, the answer lies in the distribution of dependencies rather than dependency, somehow due to distribution, the effect of dependencies cancels out.</p><h4>The loss function for NB classification</h4><p>NB classification uses a zero-one loss function. In this function error = number of incorrect classifications. Here accuracy of probability estimation is not taken into account by error function given that class with the highest probability is predicted right. For example, let’s say there are two classes A and B, and different attributes (x1, x2, … xn) are given. P(A|all attributes) = 0.95 and P(B|all attributes)=0.05 but NB might estimates P(A|all attributes) = 0.7 and P(B|all attributes) = 0.3. Here although estimates are far from accurate but classification is correct.</p><p>Let’s move back to our analysis. The first two steps of defining and compiling the model are reduced to identifying and importing the model from sklearn (as sklearn gives as precompiled models).</p><h3>2. Compiling the model</h3><p>Since we are using sklearn’s modules and classes we just need to import the precompiled classes. Sklearn gives information about all the classes <a href="https://scikit-learn.org/stable/modules/classes.html"><strong>here</strong></a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/584/1*BbBMyoAGEbBHB8YTWUxy_A.jpeg" /><figcaption>Figure 5: Importing Multinomial Naive Bayes model from sklearn library</figcaption></figure><h3>3. Fitting the model</h3><p>In this step, we generate our model-fitting our dataset in the MultinomialNB. In order to look for the arguments which can be passed while fitting the model, it&#39;s advised to check the sklearn webpage of the module underuse. For MNB it can be checked <a href="https://scikit-learn.org/stable/modules/generated/sklearn.naive_bayes.MultinomialNB.html#sklearn.naive_bayes.MultinomialNB"><strong>here</strong></a><strong> .</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/724/1*SLsItIqTydxKws3faACkew.jpeg" /><figcaption>Figure 6: Fitting the data in Multinomial Naive Bayes.</figcaption></figure><h3>4. Evaluating the model</h3><p>Here we quantify the quality of our model. We use <a href="https://scikit-learn.org/stable/modules/model_evaluation.html#model-evaluation"><strong>metrics</strong></a> module from the sklearn library to evaluate the predictions (figure 7).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/1*OSRVLhtIT6STDMJxU8qIig.jpeg" /><figcaption>Figure 7: Using sklearn’s metrics to evaluate the model</figcaption></figure><h3>Tweaking the model</h3><p>We have observed the accuracy of our model is over 60%. We can now play with our model to increase its’ accuracy.</p><h4>Trying different n-grams</h4><p>Details are in figure 8 (bigram) and figure 9 (trigram).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SKvL3R4ZgkSNIxro0ph99Q.jpeg" /><figcaption>Figure 8: Bigram model of vectorizing the text.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lOK3yfRdZHHgUE6Wtf2BYw.jpeg" /><figcaption>Figure 9: Trigram model of vectorizing the text.</figcaption></figure><h4>Trying different Naive Bayes Algorithms</h4><p>Refer to figure 10 (Complement NB), figure 11(Gaussian NB) and figure 12 (Bernoulli NB).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n4X2xDj9b3HyMIAPnbAiIQ.jpeg" /><figcaption>Figure 10: Using Complement Naive Bayes Model for sentiment analysis</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/1*ofSguFBllZV31_EkOHwQKw.jpeg" /><figcaption>Figure 11: Using Gaussian Naive Bayes Model for sentiment analysis</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/899/1*opgWH1BPL3r9WjVODlifFg.jpeg" /><figcaption>Figure 12: Using Bernoulli Naive Bayes Model for sentiment analysis</figcaption></figure><h3>Improving the accuracy</h3><p>We have tried using different n-grams and different Naive Bayes models but maximum accuracy lingers around 60%. In order to improve our model let’s try to change the way, the BOW is created. Currently, we created BOW with CountVectorizer which counts the occurrence of the word in the text. More number of time a word occurs it becomes more important for classification.</p><h3>Term Frequency-Inverse Document Frequency</h3><p>Let’s use TF-IDF, which takes in account the product of term frequency and inverse document frequency. Term frequency is how frequently a term has appeared in a document. Let’s say a term appears ‘f’ times in a document with ‘d’ words.<br>Term Frequency = f/d<br>IDF is ‘Inverse Document Frequency’. If a corpus contains N documents and the term of our interest appears only in D documents then IDF is:<br>IDF = log(N/D) TF-IDF is product of Term Frequency and Inverse Document Frequency. <strong>TF-IDF shows the rarity of a word in the corpus.</strong> If a word is rare then probably its a signature word for a particular sentiment/information.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k1Ofa4vdvQsR_4Wu24kiiA.jpeg" /><figcaption>Figure 13: TfidfVectorizer in use</figcaption></figure><h3>Trying non-Bayesian algorithms</h3><p>Even the Tfidf vectorizer i.e creating a different BOW didn’t help in improving the accuracy of the model. Rather than naive Bayes algorithm we can also opt for stochastic gradient descent classifier or linear support vector classifier. Both of these are known to work well with the text data classification. Let’s try to use these:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FQVEpBimtRrgnIWdNjrLRA.jpeg" /><figcaption>Figure 14: Trying different algorithms for text classification</figcaption></figure><h3>Inference</h3><p>We have observed that linear support vector classifier with TF-IDF created BOW gives the best result with accuracy reaching 63.88%. Although the accuracy is still low, the model still needs to be worked upon to give better results.</p><p>Congratulation to you all for completing the tutorials. You should have received an idea about working with different classifier, a fairly detailed idea about Naive Bayes theorem and different algorithms linked with it. I have shared a broad strategy about building and evaluating a model (DC-FEM). Also discussed the challenges related to Naive Bayes algorithms. We discussed ‘bag of words’ (BOW) model and two different ways of creating BOW using CountVectorizer and TfidfVetorizer.</p><p><strong>Suggested Readings</strong>:</p><p>Access the full code at <a href="https://github.com/DrManishSharma/NLP.git">my github repository</a>.</p><p><a href="https://towardsdatascience.com/unfolding-na%C3%AFve-bayes-from-scratch-2e86dcae4b01">Unfolding Naive Bayes From Scratch</a>, by Aisha Javed</p><p><a href="https://www.datacamp.com/community/tutorials/text-analytics-beginners-nltk">Text Analytics for beginners using NLTK</a> by A. Navlani</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=96831d77ac91" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/sentiment-analysis-introduction-to-naive-bayes-algorithm-96831d77ac91">Sentiment Analysis (Introduction to Naive Bayes Algorithm)</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[Object detection using YOLOv3 on colab]]></title>
            <link>https://medium.com/data-science/object-detection-using-yolov3-on-colab-5d7d9eef02b3?source=rss-7c5de1a10636------2</link>
            <guid isPermaLink="false">https://medium.com/p/5d7d9eef02b3</guid>
            <category><![CDATA[darknet-53]]></category>
            <category><![CDATA[object-detection]]></category>
            <category><![CDATA[yolo]]></category>
            <category><![CDATA[yolov3-project]]></category>
            <category><![CDATA[colab]]></category>
            <dc:creator><![CDATA[Manish Sharma]]></dc:creator>
            <pubDate>Mon, 27 Apr 2020 17:07:26 GMT</pubDate>
            <atom:updated>2021-05-22T21:40:00.155Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yr4pGlx36YtG2jtySKuMrg.png" /><figcaption>Source: By Mike Gruber from Unsplash.com</figcaption></figure><h3>Object Detection Using YOLOv3 on Colab with questions for interview preparation</h3><h4>Train a model to identify different objects in images captured by you.</h4><p>This blog will help you to train a model which can identify different objects in an image. It’s fun and exciting to observe how the model can behave better than humans in certain conditions. It can differentiate between car and pickup truck even if the rear of the truck is not clear in an image, personally, I wasn’t able to make that difference. In case you have already used YOLO as a black box this blog will help you to understand the model and its nuances. Finally, there are some questions that can help you to gauge your understanding of the model. Try to answer the questions in the comment section and don’t hesitate to ask me if you need an answer.</p><p><em>Requirements</em>: A pc with an internet connection and a Google account.</p><p><em>Learnings</em>: An hands-on experience of object detection using YOLOv3 to deepen the understanding of YOLO algorithm.</p><p><em>Setup:</em><strong><em> </em></strong>Set up a Colab notebook account through your google drive (My Drive &gt; New &gt; More &gt; Connect More apps &gt; Colab). To perform the object detection on images in your pc install ‘Drive Backup and Sync’. Allow one folder on your pc to sync on google drive. The files (images or videos) from this folder will be accessed by Colab (via google drive).</p><p><strong>Object detection</strong></p><p>The object detection part is divided into 9 easy steps. It will allow you to apply object detection on the images clicked by you. So let’s begin the object detection first and later on I will explain the algorithm (YOLO) behind it.</p><p><strong>STEP1</strong>: Connect your Colab notebook with google drive. Once you import and mount the drive, you need to click on the link which appears below your code. You need to allow the Colab to access the drive by permitting it.</p><pre>from google.colab import drive</pre><pre>drive.mount(&#39;/content.gdrive&#39;)</pre><p><strong>Step2</strong>: Change the hardware accelerator to GPU (Runtime &gt; Change Runtime type &gt; Hardware accelerator = GPU). To make sure you are connected to GPU, type !nvidia-smi, if you are connected you should get the details of GPU you are connected (as shown below).</p><pre>!nvidia-smi</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*871qQacaHK1gJ7a0m7QcTQ.jpeg" /><figcaption>Checking the connection with GPU</figcaption></figure><p><strong>Step3: </strong>Darknet is an open-source neural network written by Joseph Redmon. It is written in C and CUDA. It supports both CPU and GPU computation. The official implementation of the darknet is available at: <a href="https://pjreddie.com/darknet/">https://pjreddie.com/darknet/</a> . We will use a slightly modified version of the darknet available at AlexyAB/darknet. This neural network framework can be used for object detection using YOLO.</p><pre>#clone darknet repository</pre><pre>import os</pre><pre>os.environ[&#39;PATH&#39;] += &#39;:/usr/local/cuda/bin&#39;</pre><pre>!rm -fr darknet</pre><pre>!git clone https://github.com/AlexeyAB/darknet</pre><p><strong>Step4: </strong>Check the current directory using !pwd. We should be in /content/darknet folder. Or else change to darknet folder (%cd /darknet). Once in this folder, we using stream editor (sed) to edit the make files of GPU and OpenCV (in, in-place mode, i.e, sed -i). We change all the instances of GPU=0 to GPU =1, to enable GPU and OpenCV.</p><pre>#go to the darknet folder, edit and remake Makefiles of GPU and OPENCV</pre><pre>!sed -i &#39;s/GPU=0/GPU=1/g&#39; Makefile</pre><pre>!sed -i &#39;s/OPENCV=0/OPENCV=1/g&#39; Makefile</pre><pre>!make</pre><p><strong>Step5:</strong> Loading the pre-trained weights for YOLO object detection. We get the pre-trained weights for YOLOv3 from pjreddie.com. This website belongs to Joseph Redmon the man behind YOLO and darknet.</p><pre># get yolov3 weights</pre><pre>!wget https://pjreddie.com/media/files/yolov3.weights</pre><pre>!chmod a+x ./darknet</pre><p><strong>Step6:</strong> Make sure that you are in the correct directory (/content/darknet) using !pwd. If yes, then install the required packages. For the complete list, I will encourage you to have a look at <a href="https://github.com/DrManishSharma/YOLO_Obj_Detection/blob/master/Yolo_Obj_Detection_Using_Colab.ipynb">my jupyter file on github</a>.</p><pre>!apt install ffmpeg libopencv-dev libgtk-3-dev python-numpy python3-numpy libdc1394-22 libdc1394-22-dev libjpeg-dev libtiff5-dev libavcodec-dev libavformat-dev libswscale-dev libxine2-dev libgstreamer1.0-dev libgstreamer-plugins-base1.0-dev libv4l-dev libtbb-dev qtbase5-dev libfaac-dev libmp3lame-dev libopencore-amrnb-dev libopencore-amrwb-dev libtheora-dev libvorbis-dev libxvidcore-dev x264 v4l-utils unzip</pre><p><strong>Step7:</strong> Loading the image from your drive to Colab and running YOLO on it. You can transfer any image from your pc to the folder you shared with google drive in step 1. That image will appear in the same folder in the drive. In my case, I named the folder ‘darknet’ and the name of the image is ‘test2.jpg’. The address of the folder will be: /content.gdrive/My Drive/darknet/test2.jpg but since space is not allowed in the address path you can use: /content.gdrive/My\ Drive/darknet/test2.jpg.</p><pre>!./darknet detect cfg/yolov3.cfg yolov3.weights /content.gdrive/My\ Drive/darknet/test2.jpg</pre><p><strong>Step8: </strong>You need OpenCV and matplotlib to view your result. If you are on this step first of all congratulations that you have run your very first YOLO object detection using your image.</p><pre>import cv2</pre><pre>import matplotlib.pyplot as plt</pre><pre>import os.path</pre><pre>fig,ax = plt.subplots()</pre><pre>ax.tick_params(labelbottom=&quot;off&quot;,bottom=&quot;off&quot;)</pre><pre>ax.tick_params(labelleft=&quot;off&quot;,left=&quot;off&quot;)</pre><pre>ax.set_xticklabels([])</pre><pre>ax.axis(&#39;off&#39;)</pre><pre>file = &#39;./predictions.jpg&#39;</pre><pre>if os.path.exists(file):</pre><pre>img = cv2.imread(file)</pre><pre>show_img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)</pre><pre>#show_img(show_img)</pre><pre>plt.imshow(show_img)</pre><pre>plt.show()</pre><pre>#cv2.imshow(img)</pre><p><strong>Step9:</strong> Result analysis. Here you can see that algorithm can correctly detect a baby as a person, cell phone, and hairbrush (as a toothbrush). While several other items (hairdryer, small purse, makeup items)can’t be detected. Can you guess the reason? Maybe you should check the weights we used were trained on which all objects.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/544/1*n20cROT-rowBmv1nt_PzGQ.jpeg" /><figcaption>Result Analysis (Source: Photo by the Author)</figcaption></figure><p>Here I have presented an exercise to help new users to start object detection by just using their pc. Moreover, users can use their images so it will further add to their fun. Once you are done with this fun part it will be intriguing to know how YOLO can detect the objects.</p><h3><strong>Info about YOLOv3</strong></h3><p>Let’s try to learn how does the algorithm works.</p><p>YOLO (<a href="https://pjreddie.com/media/files/papers/YOLOv3.pdf">link to original paper</a> ): <em>You Only Look Once</em> is an object detection network. It localizes and classifies an object. It does both these tasks in a single step. The backbone of YOLO in the darknet-53 neural network, there are 53 convolutional layers in the network for feature extraction.</p><p>YOLO divides the input image in m x m grid. Each cell of the grid contains some (B) anchor boxes to localize the object. For an object, the cell in which the center of the object lies is responsible for detecting the object.</p><p>Let’s try to understand the output vector which will give insights into different aspects of this algorithm. The output vector will consist of B * (5 + C) elements. B is the number of anchor boxes that are present in each cell. Each box will give a probability element showing what’s the probability of an object being present in the cell, 4 elements describing the bounding box (2 for center coordinates bx, by and other two to describe height and width of the box bh and bw). C is the number of classes. If there are 6 classes then there will be 11 elements per box, and if there are 3 boxes then in totality there will be 33 elements in the output.</p><p>YOLOv3 is among the fastest object detection algorithm currently present. The speed comes at the cost of accuracy. It makes a high error in object localization compared to fast R-CNN but still, it makes less background error compared to later.</p><p>To detect multiple objects per cell, it makes use of multiple anchor boxes per cell. Of course, these anchors would be of a different dimension. Let’s say one is a wider rectangle (lengthwise) other being a longer rectangle (width-wise). One other aspect to mention is to get rid of multiple bounding boxes per object it uses standard non-max suppression.</p><h3>Interview Questions</h3><p>You may comment on your answers in the comment section or ask me in case you want me to answer any of these. I will highly appreciate it if you could answer the questions for which you know the answers, other readers will definitely get benefitted because of your comments.</p><p>Q1. An n x n image convolved with a filter of size f x f, padding of p and stride of s, what will be the size of output? Do check what happens if there is no padding and f &amp; s both are equal to 2.</p><p>Q2. Why are fully connected layers required in an object detection neural network?</p><p>Q3. List down the strategy/methods for data augmentation.</p><p>Q4. What is the difference between the anchor box and the bounding box in YOLO?</p><p>Q5. How is mean average precision calculated?</p><p>Q6. Explain the concept of NMS or non-max suppression?</p><p>Q7. What are the different components of the loss function in YOLO?</p><p>To access the complete jupyter file: <a href="https://github.com/DrManishSharma/YOLO_Obj_Detection/blob/master/Yolo_Obj_Detection_Using_Colab.ipynb">click here</a>.</p><p>I hope this blog gives you comprehensive hands-on practice on YOLO and would help you start with your journey in object detection. In case you wish to discuss more feel free to comment.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5d7d9eef02b3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/object-detection-using-yolov3-on-colab-5d7d9eef02b3">Object detection using YOLOv3 on colab</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Linear Regression and its Assumptions]]></title>
            <link>https://medium.com/data-science/linear-regression-and-its-assumptions-ef6e8db4904d?source=rss-7c5de1a10636------2</link>
            <guid isPermaLink="false">https://medium.com/p/ef6e8db4904d</guid>
            <category><![CDATA[qq-plot]]></category>
            <category><![CDATA[linear-regression]]></category>
            <category><![CDATA[vif]]></category>
            <category><![CDATA[heatmap]]></category>
            <category><![CDATA[regression-assumptions]]></category>
            <dc:creator><![CDATA[Manish Sharma]]></dc:creator>
            <pubDate>Fri, 24 Jan 2020 14:10:40 GMT</pubDate>
            <atom:updated>2020-01-24T14:14:32.977Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*btTIPVcQGCINIk_ItuCLTw.jpeg" /><figcaption>Source: stocksnap.io</figcaption></figure><h3>Linear Regression and its assumptions</h3><h4>Assumptions of linear regression like Collinearity, Multivariate Normality, Autocorrelation, Homoscedacity are explained with examples</h4><p>Last week, I was helping my friend to prepare for an interview for a data scientist position. I searched over the internet for the relevant questions and found that the question “<strong>What are the assumptions involved in Data Science ?</strong>” occurred very frequently in my searches. Although most of the blogs provided the answer to this question, still, details were missing. I researched the basic assumptions and would like to share my findings with you. First, I will tell you the assumptions in short and then will dive in with an example.</p><p>The <strong>basic assumptions</strong> for the linear regression model are the following:</p><ul><li>A <strong>linear relationship</strong> exists between the independent variable (X) and dependent variable (y)</li><li>Little or <strong>no multicollinearity</strong> between the different features</li><li>Residuals should be normally distributed (<strong>multi-variate normality</strong>)</li><li>Little or <strong>no autocorrelation</strong> among residues</li><li><strong>Homoscedasticity</strong> of the errors</li></ul><p>Now let’s see how to verify an assumption and what to do in case an assumption is not true. Let us focus on each of these points one by one. We will take a dataset with different features of wine. This dataset has been used in several examples by fellow data scientists and is made publicly available by the UCI machine learning repository ( <a href="https://archive.ics.uci.edu/ml/datasets/Wine+Quality">Wine_quality data</a> or the CSV file from <a href="https://drive.google.com/file/d/195gkZ5cTZL11L308MHc7EyBbAoiB4xqf/view">here</a>) another dataset I will use is temperature dataset (available <a href="https://drive.google.com/file/d/1fiHg5DyvQeRC4SyhsVnje5dhJNyVWpO1/view">here</a>). I came across these datasets in an article by <a href="https://towardsdatascience.com/a-beginners-guide-to-linear-regression-in-python-with-scikit-learn-83a8f7ae2b4f">Nagesh Singh Chauhan</a>. I will advise you to download the data and play with it to find the number of rows, columns, whether there are rows with NaN values, etc. <strong>Pandas</strong> is a really good tool to read CSV and play with the data. If you are new to Pandas try reading the file using:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*GmENtYICfY13Uo7OyqIDJA.png" /></figure><p>Now you can play with data using, dataset.head()/dataset.tail()/dataset.describe, etc.</p><ol><li><strong>Linear Relationship</strong></li></ol><p>A linear relationship should exist between the independent variable and the dependent variable. This could easily be verified using scatter plots. I will use the temperature dataset to show the linear relationship. You may plot Tmax vrs T_min (or T_avg vrs T_min) as shown in figure 1. If you have played with the data you might have observed that there is a month column thus we can even label (colour code) the scatter markers according to months just to see if there is a clear distinction of temperature according to month (figure 1b).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/627/1*-zh3t_u7ywzDbcwWh_FcGg.png" /></figure><p>the output should look like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sSAxRJdAJjNzpfsvb60HzA.png" /><figcaption>Figure 1</figcaption></figure><p>Here you can observe that T_max and T_min follows a linear trend. You can imagine a straight line passing through the data. Thus we have made sure that our data follows the first assumption.</p><p><strong>What if data wasn’t linear?</strong></p><ul><li>Maybe it’s a <strong>wrong idea to fit that data in a linear model</strong>. It might be more suitable for a polynomial model (nonlinear regression).</li><li><strong>Data transformation</strong>, if y seems exponential to x how about plotting a curve between y and log(x) (or y vs x squared). Now you can do linear regression on this data. But why would you want to do that? Because you (and me too) know more about linear regression than non-linear regression. We have so many tools built for linear regression, hypothesis validation, etc which may not be readily available for non-linear regression. Moreover, once you have fitted the linear regression between y and transformed x it is not difficult to unwind to the original relationship y vs x.</li></ul><p><strong>2. No Multicollinearity among different features</strong></p><p><strong>Why ‘no multicollinearity’</strong>?</p><p>When we are performing linear regression analysis we are looking for a solution of type y = mx + c, where c is intercept and m is the slope. The value of ‘m’ determines how much y would change while changing x by unity. For a multivariate linear regression same relationship holds for the following equation: y = m1x1 +m2x2 +m3x3 … + c. Ideally, m1 denotes how much y would change on changing x1 but what if a change in x1 changes x2 or x3. In such a case the relationship between y and m1 (or m2, m3, etc) would be very complex.</p><p><strong>How to check ‘multicollinearity’</strong>?</p><p>Seaborn provides a pairplot function which plots attributes of a variable among themselves. These plots scatter plots and we need to look if any of these attributes are showing a linear relationship. This is the easiest tool to visualize and feel the linear relationship of different attributes but it is good only if the number of features involved is limited to 10–12 features. In the next section, we will discuss what to do if more features are involved. Let’s first draw our pairplot. For this, I will use Wine_quality data as it has features that are highly correlated (figure 2).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/485/1*tGlgsjUtMMvP4X0B7rUFjw.png" /></figure><p>the output should be an 11x11 figure like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*oijJUQA_g-YtxBG6skIzHA.png" /><figcaption>Figure 2</figcaption></figure><p>If you observe feature like <em>pH</em> and <em>fixed acidity</em> show a linear dependence (with negative covariance). If you observe the complete plot you will find that</p><ul><li><em>fixed acidity</em> is correlated with <em>citric acid</em>, <em>density</em>, and <em>acidity</em></li><li><em>volatile acidity</em> is correlated with <em>citric acid</em></li></ul><p>I leave on you to find other colinearity relationships. Let’s <strong>take a detour to understand the reason for this colinearity</strong>. If you remember your high school chemistry, the pH is defined as</p><blockquote>pH =- log [H+] = — log(concentration of acid)</blockquote><p>thus it is very intuitive that pH and citric acid or volatile acidity are negatively correlated.</p><p>This exercise also serves an example of <strong>how domain knowledge about the data helps to work with data more efficiently</strong>. Probably this is the reason that data science is open for scientists from all the fields of science.</p><p><strong>How collinear are the different features?</strong></p><p>In the previous section, we plotted the different features to check if they are collinear or not. In this section, we will answer what is the measure of there collinearity?</p><p>We can measure correlation (<strong>note ‘correlation’ </strong>not<strong> ‘collinearity’</strong>), if the absolute correlation is high between two features we can say these two features are collinear. To measure the correlation between different features, we use the correlation matrix/heatmap. To plot the heatmap, we can use seaborn’s heatmap function (figure 3).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/515/1*G8UGXY_-gNlksanx7UAnjQ.png" /></figure><p>the output should be a colour-coded matrix with correlation annotated in the grid:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/752/1*sIuJzVeZ06r2jILi183hgQ.png" /><figcaption>Figure 3</figcaption></figure><p>Now depending upon your knowledge of statistics you can decide a threshold like 0.4 or 0.5 if the correlation is greater than this threshold than it is considered a problem. Rather than giving a clear answer here, I will pose a question to you. <strong>What should be an ideal value of this correlation threshold</strong>? Now let’s say your dataset contains 10, 000 examples (or rows) would you change your answer if dataset contained 100,000 or just 1000 examples. Maybe you can give your answers in comments.</p><p><strong>What to do if the correlation is high</strong>?</p><p>Let’s say you have made the list of the colinear relationships between different features. Now what? The first thing to think is if a feature can be removed. If two features are directly related for example amount of acid and pH, I wouldn’t hesitate to remove one. As pH is nothing but the negative log of the amount of acid. It is like having the same information in two different scales. But bigger questions are:</p><ul><li>which feature to remove pH or amount of acid?</li><li>which feature should be removed next?</li></ul><p>I don’t have a clear answer to this. What I have learnt is to calculate the variance inflation factor VIF. It is defined as the inverse of tolerance, while tolerance is 1- R2. While I will discuss the VIF but in general there are following methods available for treating the colinearity:</p><p>a) Greedy elimination</p><p>b) Recursive feature elimination</p><p>c) Lasso regularization (L1 regularization)</p><p>d) Principle component analysis (PCA)</p><p>We will use VIF values to find which feature should be eliminated first. And then we will recalculate the VIF to check if any other features need to be eliminated. If we work on correlation scale the correlation among different variables before and after an elimination doesn’t change. The VIF give this advantage to measure the effect of elimination. We use statsmodels, oulier_influence module to calculate VIF. This model requires us to add a constant variable in the model to calculate VIF thus in the code we use ‘add_constant(X)’, where X is our dataset which contains all the features (the quality column is removed as it contains the target value).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/688/1*BhdjbDRR_OeP1gINxHf6-w.png" /></figure><p>The method I follow is to eliminate a feature with the highest VIF and then recalculate the VIF. If VIF value is/are greater than 10 then remove the feature with next highest VIF or else we are done with dealing the multicollinearity.</p><p>For checking other assumptions we need to perform linear regression. I have used the scikit learn linear regression module to do the same. We split the model in test and train model and fit the model using train data and do predictions using the test data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*cVc1NuesCWm9BPg9XWtS2g.png" /></figure><p><strong>3.</strong> <strong>Multivariate Normality</strong></p><p>The residuals should be normally distributed. This can be easily checked by plotting QQ plot. We will use statsmodels, qqplot for plotting it. We first import the qqplot attribute and then feed it with residue values. We get the Q-Q plot as figure 4.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/457/1*9D-2aJl8k35hQ8zciedZsw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/553/1*UXF61Om9-JrFQIETcXW3EA.png" /><figcaption>Figure 4</figcaption></figure><p>Ideally, it should have been a straight line. This pattern shows that there is something seriously wrong with our model. We can not rely on this regression model. Let’s check if other assumption holds true or not.</p><p><strong>4. No autocorrelation</strong></p><p>Durbin Watson’s test of the d-test could help us analyze if there is any autocorrelation between the residues. Since there is a lot of material on the internet about this test, I will provide you with another way. In figure 5 show the plot of residues with respect to each attribute to check if residues show any correlation. In the code below dataset2 is the pandas data frame of X_test.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/460/1*JWwfHCOsQyy-jncVtZQ8KA.png" /></figure><p>the output will be a series of plots (1 plot/column of test dataset)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*vosYaJO8DPNNSZifrQsAig.png" /><figcaption>Figure 5</figcaption></figure><p>Figure 5 shows how the data is well distributed without any specific pattern thus verifying no autocorrelation of the residues. We need to verify this in all the plots (X axis is the feature, so there will be as many plots as there are features).</p><p><strong>5. Homoscedacity</strong></p><p>Plotting the scatter plots of the errors with the fit line will show if residues are forming any pattern with the line. If yes then data is not homoscedastic or the data is heteroscedastic. While if the scatter plot doesn’t form any pattern and is randomly distributed around the fit line than the residues are homoscedastic.</p><p>To plot residuals (y_test — y_pred) with respect to fitted line one can write the equation of the fitted line (by using *.coeff_ and *.intercept). Use this equation to get y values but plot these y values on the x-axis as we want to plot the residuals with respect to the fit line (X-axis should be the fit line). Now the pattern of residues can be observed. Below is the code for same:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/591/1*tqsS7GjFMWCJxU1lQYXyLQ.png" /></figure><p>If you are new to python and wish to stay away from writing your code you may perform the same task by using ‘Redidualsplot’ module of <em>yellowbrick regressor</em>. Here you just need to fit in test and training data and rest will be done by the model itself. Here I am using LinearRegression() model of scikit learn you may choose to use a different one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/413/1*9uel_STn5PXhTpeW9U09Gg.png" /></figure><p>Anyhow, use any of the above methods you will end up getting the same result, which is shown below in figure 6.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/629/1*o_ZB56AEOJV0JqptPrOF-g.png" /></figure><p>Here the residues show a clear pattern, indicating something wrong with our model.</p><p>Thus our model fails to hold on multivariate normality and homoscedasticity assumptions(figure 4 and figure 6 respectively). Here it suggests that either the data is not suitable for linear regression or the given features can’t really predict the quality of wine based on given features. But this was a good exercise to show the basic assumptions of linear regression. In case you have a better solution for the problem let me know.</p><p>Constructive criticism/suggestions are welcome.</p><p>Other good reads for this topic:</p><ol><li>How to check the quality of your linear regression model on python. <a href="https://github.com/tirthajyoti/Machine-Learning-with-Python/blob/master/Regression/Regression_Diagnostics.ipynb">Link</a></li><li>Assumptions of Linear Regression Algorithm. <a href="https://towardsdatascience.com/assumptions-of-linear-regression-algorithm-ed9ea32224e1">Link</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ef6e8db4904d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/linear-regression-and-its-assumptions-ef6e8db4904d">Linear Regression and its Assumptions</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>
    </channel>
</rss>