<p><div><div><div><div data-show-faces="false" data-height="21" data-width="100" data-layout="button_count" data-send="true" data-href="https://www.r-bloggers.com/15-types-of-regression-you-should-know/"></div></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="http://www.listendata.com/2018/03/regression-analysis.html"> ListenData</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<div dir="ltr">
<div>Regression techniques are one of the most popular statistical techniques used for predictive modeling and data mining tasks. On average, analytics professionals know only 2-3 types of regression which are commonly used in real world. They are linear and logistic regression. But the fact is there are more than 10 types of regression algorithms designed for various types of analysis. Each type has its own significance. Every analyst must know which form of regression to use depending on type of data and distribution.</div>
<p><b><span>Table of Contents</span></b></p>
<div></div>
<ol>
<li>What is Regression Analysis?</li>
<li>Terminologies related to Regression</li>
<li>Types of Regressions</li>
<ul>
<li>Linear Regression</li>
<li>Polynomial Regression</li>
<li>Logistic Regression</li>
<li>Quantile Regression</li>
<li>Ridge Regression</li>
<li>Lasso Regression</li>
<li>ElasticNet Regression</li>
<li>Principal Component Regression</li>
<li>Partial Least Square Regression</li>
<li>Support Vector Regression</li>
<li>Ordinal Regression</li>
<li>Poisson Regression</li>
<li>Negative Binomial Regression</li>
<li>Quasi-Poisson Regression</li>
<li>Cox Regression</li>
</ul>
<li>How to choose the correct Regression Model?</li>
</ol>
<table cellspacing="0" align="center" cellpadding="0">
<tbody>
<tr>
<td><a rel="nofollow" href="https://i1.wp.com/2.bp.blogspot.com/-4EMj8azhdRI/WrfvScVzCVI/AAAAAAAAHJY/7l3J-uX2wFA49_Nkif7Wjm5SP713amRrgCLcBGAs/s1600/regression.PNG?ssl=1" target="_blank"><img border="0" data-original-height="224" src="https://i1.wp.com/2.bp.blogspot.com/-4EMj8azhdRI/WrfvScVzCVI/AAAAAAAAHJY/7l3J-uX2wFA49_Nkif7Wjm5SP713amRrgCLcBGAs/s1600/regression.PNG?resize=450%2C224&ssl=1" data-recalc-dims="1" data-original-width="450"></a></td>
</tr>
<tr>
<td>Regression Analysis Simplified</td>
</tr>
</tbody>
</table>
<h2>What is Regression Analysis?</h2>
<p><b>Lets take a simple example :</b> Suppose your manager asked you to predict annual sales. There can be a hundred of factors (drivers) that affects sales. In this case, sales is your <b>dependent variable</b>. Factors affecting sales are <b>independent variables</b>. Regression analysis would help you to solve this problem.</p>
<blockquote><p>In simple words, regression analysis is used to model the relationship between a dependent variable and one or more independent variables.</p></blockquote>
<p>It helps us to answer the following questions –</p>
<ol>
<li>Which of the drivers have a significant impact on sales. </li>
<li>Which is the most important driver of sales</li>
<li>How do the drivers interact with each other</li>
<li>What would be the annual sales next year.</li>
</ol>
<p><b></b></p>
<h2><b>Terminologies related to regression analysis</b></h2>
<p><b><span>1. Outliers</span></b><br>Suppose there is an observation in the dataset which is having a very high or very low value as compared to the other observations in the data, i.e. it does not belong to the population, such an observation is called an outlier. In simple words, it is extreme value. An outlier is a problem because many times it hampers the results we get.</p>
<p><span><b>2. Multicollinearity</b></span><br>When the independent variables are highly correlated to each other then the variables are said to be multicollinear. Many types of regression techniques assumes multicollinearity should not be present in the dataset. It is because it causes problems in ranking variables based on its importance. Or it makes job difficult in selecting the most important independent variable (factor).</p>
<p><b><span>3. Heteroscedasticity</span></b><br>When dependent variable’s variability is not equal across values of an independent variable, it is called heteroscedasticity. <b>Example –</b> As one’s income increases, the variability of food consumption will increase. A poorer person will spend a rather constant amount by always eating inexpensive food; a wealthier person may occasionally buy inexpensive food and at other times eat expensive meals. Those with higher incomes display a greater variability of food consumption.</p>
<p><span><b>4. Underfitting and Overfitting</b></span><br>When we use unnecessary explanatory variables it might lead to overfitting. Overfitting means that our algorithm works well on the training set but is unable to perform better on the test sets. It is also known as problem of <b>high variance.</b></p>
<p>When our algorithm works so poorly that it is unable to fit even training set well then it is said to <b>underfit the data.</b> It is also known as <b>problem of high bias.</b></p>
<p>In the following diagram we can see that fitting a linear regression (straight line in fig 1) would underfit the data i.e. it will lead to large errors even in the training set. Using a polynomial fit in fig 2 is balanced i.e. such a fit can work on the training and test sets well, while in fig 3 the fit will lead to low errors in training set but it will not work well on the test set.</p>
<table cellspacing="0" align="center" cellpadding="0">
<tbody>
<tr>
<td><a rel="nofollow" href="https://i0.wp.com/4.bp.blogspot.com/-dM4Iae3kVsQ/Wlt28eEHHiI/AAAAAAAACPg/X0dIT2a6RMwdEFUO44fQVX9HXakraYBagCLcBGAs/s1600/img1.png?ssl=1" target="_blank"><img border="0" src="https://i1.wp.com/4.bp.blogspot.com/-dM4Iae3kVsQ/Wlt28eEHHiI/AAAAAAAACPg/X0dIT2a6RMwdEFUO44fQVX9HXakraYBagCLcBGAs/s640/img1.png?resize=450%2C216&ssl=1" data-original-width="450" alt="Underfitting vs Overfitting" width="450" data-original-height="216" title="" data-recalc-dims="1"></a></td>
</tr>
<tr>
<td>Regression : Underfitting and Overfitting</td>
</tr>
</tbody>
</table>
<h2>Types of Regression</h2>
<p>Every regression technique has some assumptions attached to it which we need to meet before running analysis. These techniques differ in terms of type of dependent and independent variables and distribution.</p>
<div>
<h2><span>1. Linear Regression</span></h2>
<p>It is the simplest form of regression. It is a technique in which the <b>dependent variable is continuous</b> in nature. The relationship between the dependent variable and independent variables is assumed to be linear in nature. We can observe that the given plot represents a somehow linear relationship between the mileage and displacement of cars. The <span><b>green points</b></span> are the actual observations while the <b>black line fitted</b> is the line of regression</div>
<p></p>
<table cellspacing="0" align="center" cellpadding="0">
<tbody>
<tr>
<td><a rel="nofollow" href="https://i1.wp.com/4.bp.blogspot.com/-IOOxgPaXMVc/Wlj3LWvcnjI/AAAAAAAACKE/UeTFYvAxDmUDel5UBjdifeWaApB3-dXVgCLcBGAs/s1600/img1.jpg?ssl=1" target="_blank"><img border="0" src="https://i1.wp.com/4.bp.blogspot.com/-IOOxgPaXMVc/Wlj3LWvcnjI/AAAAAAAACKE/UeTFYvAxDmUDel5UBjdifeWaApB3-dXVgCLcBGAs/s1600/img1.jpg?resize=450%2C299&ssl=1" data-original-width="450" alt="regression analysis" data-original-height="299" title="" data-recalc-dims="1"></a></td>
</tr>
<tr>
<td>Regression Analysis</td>
</tr>
</tbody>
</table>
<p></p>
<blockquote><p>When you have <code>only 1 independent variable</code> and 1 dependent variable, it is called simple linear regression.<br>When you have <code>more than 1 independent variable</code> and 1 dependent variable, it is called simple linear regression.</p></blockquote>
<div>
<div><span></span></div>
<div><b><span>The equation of linear regression is listed below –</span></b>
<table cellspacing="0" align="center" cellpadding="0">
<tbody>
<tr>
<td><a rel="nofollow" href="https://i0.wp.com/2.bp.blogspot.com/-xbqTM5K3bIU/WkzhtHMPEmI/AAAAAAAACFs/RULnlMKw_0U14oRWOUcuETJNt9TBYiJEgCLcBGAs/s1600/b.jpg?ssl=1" target="_blank"><img border="0" data-original-height="44" src="https://i0.wp.com/2.bp.blogspot.com/-xbqTM5K3bIU/WkzhtHMPEmI/AAAAAAAACFs/RULnlMKw_0U14oRWOUcuETJNt9TBYiJEgCLcBGAs/s1600/b.jpg?resize=320%2C44&ssl=1" data-recalc-dims="1" data-original-width="320"></a></td>
</tr>
</tbody>
</table>
</div>
</div>
<p>Multiple Regression Equation<br>Here ‘y’ is the dependent variable to be estimated, and X are the independent variables and ε is the error term. βi’s are the regression coefficients.</p>
<p><b><span>Assumptions of linear regression: </span></b></p>
<ol>
<li>There must be a linear relation between independent and dependent variables. </li>
<li>There should not be any outliers present. </li>
<li>No heteroscedasticity </li>
<li>Sample observations should be independent. </li>
<li>Error terms should be normally distributed with mean 0 and constant variance. </li>
<li>Absence of multicollinearity and auto-correlation.</li>
</ol>
<div></div>
<div><b><span>Estimating the parameters</span></b>To estimate the regression coefficients βi’s we use principle of least squares which is to minimize the sum of squares due to the error terms i.e. </div>
<p><a rel="nofollow" href="https://i1.wp.com/3.bp.blogspot.com/-bHdTkTHhk-A/Wlj7qArK-vI/AAAAAAAACKQ/Afedqlb4p1AFVg9MO623FbdUhZKmIeFXACLcBGAs/s1600/img2.jpg?ssl=1" target="_blank"><img border="0" src="https://i0.wp.com/3.bp.blogspot.com/-bHdTkTHhk-A/Wlj7qArK-vI/AAAAAAAACKQ/Afedqlb4p1AFVg9MO623FbdUhZKmIeFXACLcBGAs/s400/img2.jpg?resize=332%2C38&ssl=1" data-original-width="332" width="332" data-original-height="38" data-recalc-dims="1" height="38"></a></p>
<div>On solving the above equation mathematically we obtain the regression coefficients as:</div>
<div><span><a rel="nofollow" href="https://i0.wp.com/4.bp.blogspot.com/-Srjys9kedH8/Wlj8XpIW4dI/AAAAAAAACKY/KeuZNb4RZpkoKrtFmpoDbq07ZXeKBvI1wCLcBGAs/s1600/img3.jpg?ssl=1" target="_blank"><img border="0" src="https://i1.wp.com/4.bp.blogspot.com/-Srjys9kedH8/Wlj8XpIW4dI/AAAAAAAACKY/KeuZNb4RZpkoKrtFmpoDbq07ZXeKBvI1wCLcBGAs/s200/img3.jpg?resize=135%2C35&ssl=1" data-original-width="135" width="135" data-original-height="35" data-recalc-dims="1" height="35"></a></span></div>
<p><b><span>Interpretation of regression coefficients</span></b><br>Let us consider an example where the dependent variable is marks obtained by a student and explanatory variables are number of hours studied and no. of classes attended. Suppose on fitting linear regression we got the linear regression as:</p>
<blockquote><p>Marks obtained = 5 + 2 (no. of hours studied) + 0.5(no. of classes attended)</p></blockquote>
<div>Thus we can have the regression coefficients 2 and 0.5 which can interpreted as:</div>
<div>
<div></div>
<ol>
<li>If no. of hours studied and no. of classes are 0 then the student will obtain 5 marks.</li>
<li>Keeping no. of classes attended constant, if student studies for one hour more then he will score 2 more marks in the examination. </li>
<li>Similarly keeping no. of hours studied constant, if student attends one more class then he will attain 0.5 marks more.</li>
</ol>
<div></div>
</div>
<div>
<div></div>
<p><span>Linear Regression in R</span></div>
<div>
<div>We consider the swiss data set for carrying out linear regression in R. We use lm() function in the base package. We try to estimate Fertility with the help of other variables.</div>
<blockquote><p>library(datasets)<br>model = lm(Fertility ~ .,data = swiss)<br>lm_coeff = model$coefficients<br>lm_coeff<br>summary(model)</p></blockquote>
<p><span>The output we get is:</span></div>
<p>> lm_coeff</p>
<pre>     (Intercept)      Agriculture      Examination        Education         Catholic <br>      66.9151817       -0.1721140       -0.2580082       -0.8709401        0.1041153 <br>Infant.Mortality <br>       1.0770481 <br>> summary(model)<br><br>Call:<br>lm(formula = Fertility ~ ., data = swiss)<br><br>Residuals:<br>     Min       1Q   Median       3Q      Max <br>-15.2743  -5.2617   0.5032   4.1198  15.3213 <br><br>Coefficients:<br>                 Estimate Std. Error t value Pr(>|t|)    <br>(Intercept)      66.91518   10.70604   6.250 1.91e-07 ***<br>Agriculture      -0.17211    0.07030  -2.448  0.01873 *  <br>Examination      -0.25801    0.25388  -1.016  0.31546    <br>Education        -0.87094    0.18303  -4.758 2.43e-05 ***<br>Catholic          0.10412    0.03526   2.953  0.00519 ** <br>Infant.Mortality  1.07705    0.38172   2.822  0.00734 ** <br>---<br>Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1<br><br>Residual standard error: 7.165 on 41 degrees of freedom<br>Multiple R-squared:  0.7067, Adjusted R-squared:  0.671 <br>F-statistic: 19.76 on 5 and 41 DF,  p-value: 5.594e-10<br></pre>
<div>Hence we can see that 70% of the variation in Fertility rate can be explained via linear regression.
</div>
<h2><span>2. Polynomial Regression</span></h2>
<div>It is a technique to fit a nonlinear equation by taking polynomial functions of independent variable.<br>In the figure given below, you can see the red curve fits the data better than the green curve. Hence in the situations where the relation between the dependent and independent variable seems to be non-linear we can deploy <b>Polynomial Regression Models.</b></div>
<div><a rel="nofollow" href="https://i2.wp.com/1.bp.blogspot.com/-dODuK8N5h1Q/Wlnyb3V9HFI/AAAAAAAACL4/WxQtCJ1pM5wccDABg4wIrTBUB0vlikXQQCLcBGAs/s1600/poly1.jpg?ssl=1" target="_blank"><img border="0" data-original-height="258" src="https://i2.wp.com/1.bp.blogspot.com/-dODuK8N5h1Q/Wlnyb3V9HFI/AAAAAAAACL4/WxQtCJ1pM5wccDABg4wIrTBUB0vlikXQQCLcBGAs/s1600/poly1.jpg?resize=450%2C258&ssl=1" data-recalc-dims="1" data-original-width="450"></a></div>
<div>Thus a polynomial of degree k in one variable is written as:</div>
<div><a rel="nofollow" href="https://i1.wp.com/1.bp.blogspot.com/-wrJdHn0X_Y8/Wln1K2YZO5I/AAAAAAAACMI/gScVjBesYCY0S4bqUV_tVL6DELUjVcvLwCLcBGAs/s1600/poly2.jpg?ssl=1" target="_blank"><img border="0" data-original-height="43" src="https://i1.wp.com/1.bp.blogspot.com/-wrJdHn0X_Y8/Wln1K2YZO5I/AAAAAAAACMI/gScVjBesYCY0S4bqUV_tVL6DELUjVcvLwCLcBGAs/s1600/poly2.jpg?resize=242%2C43&ssl=1" data-recalc-dims="1" data-original-width="242"></a></div>
<div>Here we can create new features like</div>
<div><a rel="nofollow" href="https://i1.wp.com/2.bp.blogspot.com/-cCV9hGqL9LQ/Wln157jicDI/AAAAAAAACMQ/oiIreV5AsTYAB26KLHAI_fnoxbVMevuNgCLcBGAs/s1600/poly3.jpg?ssl=1" target="_blank"><img border="0" src="https://i1.wp.com/2.bp.blogspot.com/-cCV9hGqL9LQ/Wln157jicDI/AAAAAAAACMQ/oiIreV5AsTYAB26KLHAI_fnoxbVMevuNgCLcBGAs/s200/poly3.jpg?resize=158%2C29&ssl=1" data-original-width="158" width="158" data-original-height="29" data-recalc-dims="1" height="29"></a></div>
<div>and can fit linear regression in the similar manner.</div>
<p>In case of multiple variables say X1 and X2, we can create a third new feature (say X3) which is the product of X1 and X2 i.e. </p>
<div><a rel="nofollow" href="https://i0.wp.com/1.bp.blogspot.com/-7PfDLmtSWJk/Wln2md8NJ2I/AAAAAAAACMc/XpDcnrF4Md0jd-jmBXRI5yY_TgMnGWChACLcBGAs/s1600/poly5.jpg?ssl=1" target="_blank"><img border="0" data-original-height="27" src="https://i0.wp.com/1.bp.blogspot.com/-7PfDLmtSWJk/Wln2md8NJ2I/AAAAAAAACMc/XpDcnrF4Md0jd-jmBXRI5yY_TgMnGWChACLcBGAs/s1600/poly5.jpg?resize=78%2C27&ssl=1" data-recalc-dims="1" data-original-width="78"></a></div>
<div><b>Disclaimer:</b> It is to be kept in mind that creating unnecessary extra features or fitting polynomials of higher degree may lead to overfitting.
</div>
<div><span><b>Polynomial regression in R:</b></span>
<div><span>We are using <a rel="nofollow" href="https://sites.google.com/site/breathe42/poly.csv" target="_blank"><b>poly.csv </b></a>data for fitting polynomial regression where we try to estimate the Prices of the house given their area.</span></div>
<p>Firstly we read the data using <b>read.csv( )</b> and divide it into the dependent and independent variable</p>
<blockquote><p>data = read.csv(“poly.csv”)<br>x = data$Area <br>y = data$Price </p></blockquote>
</div>
<p>In order to compare the results of linear and polynomial regression, firstly we fit linear regression:</p>
<blockquote><p>model1 = lm(y ~x) <br>model1$fit<br>model1$coeff</p></blockquote>
<p></p>
<div>The coefficients and predicted values obtained are:</div>
<pre>> model1$fit<br>       1        2        3        4        5        6        7        8        9       10 <br>169.0995 178.9081 188.7167 218.1424 223.0467 266.6949 291.7068 296.6111 316.2282 335.8454 <br>> model1$coeff<br> (Intercept)            x <br>120.05663769   0.09808581 <span><span><br></span></span></pre>
<div>We create a dataframe where the new variable are x and x square.</div>
<p></p>
<blockquote><p>new_x = cbind(x,x^2)</p></blockquote>
<p>new_x </p>
<pre>         x        <br> [1,]  500  250000<br> [2,]  600  360000<br> [3,]  700  490000<br> [4,] 1000 1000000<br> [5,] 1050 1102500<br> [6,] 1495 2235025<br> [7,] 1750 3062500<br> [8,] 1800 3240000<br> [9,] 2000 4000000<br>[10,] 2200 4840000</pre>
<p>Now we fit usual OLS to the new data:</p>
<blockquote><p>model2 = lm(y~new_x) <br>model2$fit<br>model2$coeff </p></blockquote>
<p>The fitted values and regression coefficients of polynomial regression are:</p>
<pre>> model2$fit<br>       1        2        3        4        5        6        7        8        9       10 <br>122.5388 153.9997 182.6550 251.7872 260.8543 310.6514 314.1467 312.6928 299.8631 275.8110 <br>> model2$coeff<br>  (Intercept)        new_xx         new_x <br>-7.684980e+01  4.689175e-01 -1.402805e-04 <br></pre>
<div></div>
<p>Using ggplot2 package we try to create a plot to compare the curves by both linear and polynomial regression.</p>
<blockquote><p>library(ggplot2) <br>ggplot(data = data) + geom_point(aes(x = Area,y = Price)) +<br>geom_line(aes(x = Area,y = model1$fit),color = “red”) +<br>geom_line(aes(x = Area,y = model2$fit),color = “blue”) +<br>theme(panel.background = element_blank()) </p></blockquote>
<p></p>
<div><a rel="nofollow" href="https://i2.wp.com/3.bp.blogspot.com/-GC6CZTGEsW0/Wls-Q-ROh_I/AAAAAAAACN0/1USwBPjxa60fgR_0K62HH2XUVGIl8T7-wCLcBGAs/s1600/poly.jpeg?ssl=1" target="_blank"><img border="0" data-original-height="356" src="https://i2.wp.com/3.bp.blogspot.com/-GC6CZTGEsW0/Wls-Q-ROh_I/AAAAAAAACN0/1USwBPjxa60fgR_0K62HH2XUVGIl8T7-wCLcBGAs/s1600/poly.jpeg?resize=450%2C356&ssl=1" data-recalc-dims="1" data-original-width="450"></a></div>
<p><span><b><br></b></span></p>
<h2><b>3. Logistic Regression</b></h2>
<div>In logistic regression, the dependent variable is binary in nature. Independent variables can be continuous or binary.</div>
<p></p>
<div>Here my model is:</div>
<div><span><a rel="nofollow" href="https://i2.wp.com/1.bp.blogspot.com/-_p1zRPDPx50/WlnuBnjBkTI/AAAAAAAACLs/bTgbGJpgOh4EkxRHDK-TlqqZAG-1BA5WwCLcBGAs/s1600/img10.jpg?ssl=1" target="_blank"><img border="0" src="https://i0.wp.com/1.bp.blogspot.com/-_p1zRPDPx50/WlnuBnjBkTI/AAAAAAAACLs/bTgbGJpgOh4EkxRHDK-TlqqZAG-1BA5WwCLcBGAs/s400/img10.jpg?resize=329%2C63&ssl=1" data-original-width="329" width="329" data-original-height="63" data-recalc-dims="1" height="63"></a></span></div>
<p><span><b>Why don’t we use linear regression in this case?</b></span> </p>
<ul>
<li>In linear regression, range of ‘y’ is real line but here it can take only 2 values. So ‘y’ is either 0 or 1 but X’B is continuous thus we can’t use usual linear regression in such a situation.</li>
<li>Secondly, the error terms are not normally distributed.</li>
<li>y follows binomial distribution and hence is not normal.</li>
</ul>
<p><b><span>Examples</span></b></p>
<ul>
<li><b>HR Analytics:</b> IT firms recruit large number of people, but one of the problems they encounter is after accepting the job offer many candidates do not join. So, this results in cost over-runs because they have to repeat the entire process again. Now when you get an application, can you actually predict whether that applicant is likely to join the organization (Binary Outcome – Join / Not Join).</li>
<p></p>
<li><b>Elections: </b>Suppose that we are interested in the factors that influence whether a political candidate wins an election. The outcome (response) variable is binary (0/1); win or lose. The predictor variables of interest are the amount of money spent on the campaign and the amount of time spent campaigning negatively.</li>
</ul>
<p><span><b>Predicting the category of dependent variable for a given vector X of independent variables</b><br>Through logistic regression we have </span> </p>
<div><a rel="nofollow" href="https://i0.wp.com/4.bp.blogspot.com/-gge1LswRgGI/Wlns7CsHITI/AAAAAAAACLc/cVoG8EU7eSQZYV374UZugJ4BKP3eBC2RQCLcBGAs/s1600/img9.jpg?ssl=1" target="_blank"><img border="0" data-original-height="56" src="https://i0.wp.com/4.bp.blogspot.com/-gge1LswRgGI/Wlns7CsHITI/AAAAAAAACLc/cVoG8EU7eSQZYV374UZugJ4BKP3eBC2RQCLcBGAs/s1600/img9.jpg?resize=156%2C56&ssl=1" data-recalc-dims="1" data-original-width="156"></a></div>
<div></div>
<div>Thus we choose a cut of probability say ‘p’  and if P(Yi = 1) > p then we can say that Yi belongs to class 1 otherwise 0.</div>
<p><span><b>Interpreting the logistic regression coefficients (Concept of Odds Ratio)</b></span></p>
<div>If we take exponential of coefficients, then we’ll get odds ratio for ith explanatory variable. Suppose odds ratio is equal to two, then the odds of event is 2 times greater than the odds of non-event. Suppose dependent variable is customer attrition (whether customer will close relationship with the company) and independent variable is citizenship status (National / Expat). The odds of expat attrite is 3 times greater than the odds of a national attrite.</div>
<div>
<div><span>Logistic Regression in R:</span></div>
<div>In this case, we are trying to estimate whether a person will have cancer depending whether he smokes or not.</div>
</div>
<p>We fit logistic regression with <b>glm( ) </b> function and we set <b>family = “binomial”</b></p>
<div>
<blockquote><p>model &lt;-glm(Lung.Cancer..Y.~Smoking..X.,data = data, family = “binomial”)</p></blockquote>
</div>
<div>The predicted probabilities are given by:</div>
<blockquote><p>#Predicted Probablities</p></blockquote>
<p>model$fitted.values </p>
<pre>        1         2         3         4         5         6         7         8         9 <br>0.4545455 0.4545455 0.6428571 0.6428571 0.4545455 0.4545455 0.4545455 0.4545455 0.6428571 <br>       10        11        12        13        14        15        16        17        18 <br>0.6428571 0.4545455 0.4545455 0.6428571 0.6428571 0.6428571 0.4545455 0.6428571 0.6428571 <br>       19        20        21        22        23        24        25 <br>0.6428571 0.4545455 0.6428571 0.6428571 0.4545455 0.6428571 0.6428571 <br></pre>
<div>Predicting whether the person will have cancer or not when we choose the cut off probability to be 0.5</div>
<blockquote><p>data$prediction &lt;-model$fitted.values>0.5</p></blockquote>
<pre>> data$prediction<br> [1] FALSE FALSE  TRUE  TRUE FALSE FALSE FALSE FALSE  TRUE  TRUE FALSE FALSE  TRUE  TRUE  TRUE<br>[16] FALSE  TRUE  TRUE  TRUE FALSE  TRUE  TRUE FALSE  TRUE  TRUE<br></pre>
<div></div>
<h2><b>4. Quantile Regression</b></h2>
<div>Quantile regression is the extension of linear regression and we generally use it when outliers, high skeweness and heteroscedasticity exist in the data.
<p>In linear regression, we predict the mean of the dependent variable for given independent variables. Since mean does not describe the whole distribution, so modeling the mean is not a full description of a relationship between dependent and independent variables. So we can use quantile regression which predicts a quantile (or percentile) for given independent variables.</p>
<blockquote><p>The term “quantile” is the same as “percentile”</p></blockquote>
</div>
<p><b><span>Basic Idea of Quantile Regression:</span></b>In quantile regression we try to estimate the quantile of the dependent variable given the values of X’s. <b>Note</b> that the dependent variable should be continuous.</p>
<p><b>The quantile regression model:</b><br>For qth quantile we have the following regression model:</p>
<div><a rel="nofollow" href="https://i2.wp.com/3.bp.blogspot.com/-v3umgz7unTs/Wllzkp4y5YI/AAAAAAAACK4/xAokU6rrQPMKyLsHtvn65bbIgfedSGMCwCLcBGAs/s1600/img5.jpg?ssl=1" target="_blank"><img border="0" data-original-height="29" src="https://i2.wp.com/3.bp.blogspot.com/-v3umgz7unTs/Wllzkp4y5YI/AAAAAAAACK4/xAokU6rrQPMKyLsHtvn65bbIgfedSGMCwCLcBGAs/s1600/img5.jpg?resize=96%2C29&ssl=1" data-recalc-dims="1" data-original-width="96"></a></div>
<p>This seems similar to linear regression model but here the objective function we consider to minimize is:</p>
<div><a rel="nofollow" href="https://i2.wp.com/1.bp.blogspot.com/-iQrIMqXI4Rk/Wll0V465mOI/AAAAAAAACLA/YPTqA4MhAGYE0u0P8NF23UTDIQM_R9PkQCLcBGAs/s1600/img6.jpg?ssl=1" target="_blank"><img border="0" data-original-height="48" src="https://i2.wp.com/1.bp.blogspot.com/-iQrIMqXI4Rk/Wll0V465mOI/AAAAAAAACLA/YPTqA4MhAGYE0u0P8NF23UTDIQM_R9PkQCLcBGAs/s1600/img6.jpg?resize=194%2C48&ssl=1" data-recalc-dims="1" data-original-width="194"></a></div>
<p>where q is the qth quantile.</p>
<p>If q  = 0.5 i.e. if we are interested in the median then it becomes <b>median regression </b>(or least absolute deviation regression) and substituting the value of q = 0.5 in above equation we get the objective function as:</p>
<div><span><a rel="nofollow" href="https://i2.wp.com/2.bp.blogspot.com/-W3cULkOl6vs/Wll1AfbrzWI/AAAAAAAACLM/TYEZb0HImycDIAOMXh_dU1l7NeOWt9HVgCLcBGAs/s1600/img%2B7.jpg?ssl=1" target="_blank"><img border="0" data-original-height="59" src="https://i2.wp.com/2.bp.blogspot.com/-W3cULkOl6vs/Wll1AfbrzWI/AAAAAAAACLM/TYEZb0HImycDIAOMXh_dU1l7NeOWt9HVgCLcBGAs/s1600/img%2B7.jpg?resize=63%2C59&ssl=1" data-recalc-dims="1" data-original-width="63"></a></span></div>
<p><b><span>Interpreting the coefficients in quantile regression:</span></b></p>
<div>Suppose the regression equation for 25th quantile of regression is: </div>
<div>y = 5.2333 + 700.823 x</div>
<div></div>
<div>It means that for one unit increase in x the estimated increase in 25th quantile of y by 700.823 units.</div>
<p><b><span>Advantages of Quantile over Linear Regression</span></b></p>
<ul>
<li>Quite beneficial when heteroscedasticity is present in the data.</li>
<li>Robust to outliers</li>
<li>Distribution of dependent variable can be described via various quantiles.</li>
<li>It is more useful than linear regression when the data is skewed.</li>
</ul>
<p><b><span>Disclaimer on using quantile regression!</span></b></p>
<div>It is to be kept in mind that the coefficients which we get in quantile regression for a particular quantile should differ significantly from those we obtain from linear regression. If it is not so then our usage of quantile regression isn’t justifiable. This can be done by observing the confidence intervals of regression coefficients of the estimates obtained from both the regressions.</div>
<div></div>
<p><span>Quantile Regression in R</span></p>
<div>
<div>We need to install <b>quantreg</b> package in order to carry out quantile regression.</div>
</div>
<p></p>
<blockquote><p>install.packages(“quantreg”) <br>library(quantreg) </p></blockquote>
<p></p>
<div>Using <b>rq </b>function we try to predict the estimate the 25th quantile of Fertility Rate in <b>Swiss data. </b>For this we set <b>tau = 0.25.</b></div>
<p></p>
<blockquote><p>model1 = rq(Fertility~.,data = swiss,tau = 0.25) <br>summary(model1) </p></blockquote>
<pre>tau: [1] 0.25<br><br>Coefficients:<br>                 coefficients lower bd upper bd<br>(Intercept)      76.63132      2.12518 93.99111<br>Agriculture      -0.18242     -0.44407  0.10603<br>Examination      -0.53411     -0.91580  0.63449<br>Education        -0.82689     -1.25865 -0.50734<br>Catholic          0.06116      0.00420  0.22848<br>Infant.Mortality  0.69341     -0.10562  2.36095</pre>
<p></p>
<div>Setting tau = 0.5 we run the median regression.</div>
<div>
<blockquote><p>model2 = rq(Fertility~.,data = swiss,tau = 0.5)<br>summary(model2)</p></blockquote>
</div>
<p></p>
<pre>tau: [1] 0.5<br><br>Coefficients:<br>                 coefficients lower bd upper bd<br>(Intercept)      63.49087     38.04597 87.66320<br>Agriculture      -0.20222     -0.32091 -0.05780<br>Examination      -0.45678     -1.04305  0.34613<br>Education        -0.79138     -1.25182 -0.06436<br>Catholic          0.10385      0.01947  0.15534<br>Infant.Mortality  1.45550      0.87146  2.21101</pre>
<p></p>
<div>
<div>We can run quantile regression for multiple quantiles in a single plot.</div>
</div>
<blockquote><p>model3 = rq(Fertility~.,data = swiss, tau = seq(0.05,0.95,by = 0.05)) <br>quantplot = summary(model3)<br>quantplot </p></blockquote>
<p></p>
<div>We can check whether our quantile regression results differ from the OLS results using plots.</div>
<p></p>
<blockquote><p>plot(quantplot)</p></blockquote>
<p>We get the following plot:</p>
<div><a rel="nofollow" href="https://i2.wp.com/3.bp.blogspot.com/-hQ1Vi3BsoC8/WlsZrq7z3mI/AAAAAAAACNk/PCxLz7EPpiIAtzUv3dWuNrluRr8mbo6dwCLcBGAs/s1600/quantplot.jpeg?ssl=1" target="_blank"><img border="0" src="https://i0.wp.com/3.bp.blogspot.com/-hQ1Vi3BsoC8/WlsZrq7z3mI/AAAAAAAACNk/PCxLz7EPpiIAtzUv3dWuNrluRr8mbo6dwCLcBGAs/s640/quantplot.jpeg?resize=450%2C356&ssl=1" data-original-width="450" width="450" data-original-height="356" data-recalc-dims="1" height="356"></a></div>
<p>Various quantiles are depicted by X axis. The red central line denotes the estimates of OLS coefficients and the dotted red lines are the confidence intervals around those OLS coefficients for various quantiles. The black dotted line are the <b>quantile regression estimates </b>and the gray area is the confidence interval for them for various quantiles. We can see that for all the variable both the regression estimated coincide for most of the quantiles. Hence our use of quantile regression is not justifiable for such quantiles. In other words we want that both the red and the gray lines should overlap as less as possible to justify our use of quantile regression.</p>
<h2>5. Ridge Regression</h2>
<div>It’s important to understand the concept of regularization before jumping to ridge regression.</div>
<p></p>
<h3>1. Regularization</h3>
<div>Regularization helps to solve over fitting problem which implies model performing well on training data but performing poorly on validation (test) data. Regularization solves this problem by adding a penalty term to the objective function and control the model complexity using that penalty term.
<p>Regularization is generally useful in the following situations:</p>
<ol>
<li>Large number of variables</li>
<li>Low ratio of number observations to number of variables</li>
<li>High Multi-Collinearity</li>
</ol>
</div>
<p></p>
<h3>2. <b>L1 Loss function or L1 Regularization</b></h3>
<div>In L1 regularization we try to minimize the objective function by adding a penalty term to the <b>sum of the absolute values of coefficients. </b> This is also known as least absolute deviations method. Lasso Regression makes use of L1 regularization.</div>
<p></p>
<h3>3. L2 Loss function or L2 Regularization</h3>
<div>In L2 regularization we try to minimize the objective function by adding a penalty term to the <b>sum of the squares of coefficients. </b>Ridge Regression or shrinkage regression makes use of L2 regularization.</div>
<p></p>
<blockquote><p>In general, L2 performs better than L1 regularization. L2 is efficient in terms of computation. There is one area where L1 is considered as a preferred option over L2. L1 has in-built feature selection for sparse feature spaces.  For example, you are predicting whether a person is having a brain tumor using more than 20,000 genetic markers (features). It is known that the vast majority of genes have little or no effect on the presence or severity of most diseases.</p></blockquote>
<p></p>
<div>In the linear regression objective function we try to minimize the sum of squares of errors. <b>In ridge regression</b> (also known as shrinkage regression) we add a constraint on the sum of squares of the regression coefficients. Thus in ridge regression our objective function is:</div>
<div><a rel="nofollow" href="https://i1.wp.com/2.bp.blogspot.com/-mQhz_RBk_Rs/WlrsUXF0U3I/AAAAAAAACMs/OZ2nOGaYYVk457X9Y3h1cC0d_ajcMTUDACLcBGAs/s1600/ridge1.jpg?ssl=1" target="_blank"><img border="0" data-original-height="38" src="https://i1.wp.com/2.bp.blogspot.com/-mQhz_RBk_Rs/WlrsUXF0U3I/AAAAAAAACMs/OZ2nOGaYYVk457X9Y3h1cC0d_ajcMTUDACLcBGAs/s1600/ridge1.jpg?resize=450%2C38&ssl=1" data-recalc-dims="1" data-original-width="450"></a></div>
<div>Here <b>λ is the regularization parameter</b> which is a non negative number. Here we do not assume normality in the error terms.</div>
<p><b><span>Very Important Note: </span></b></p>
<div>
<blockquote><p>We do not regularize the intercept term. The constraint is just on the sum of squares of regression coefficients of X’s.</p></blockquote>
</div>
<div>We can see that ridge regression makes use of <b>L2 regularization.</b></div>
<p>On solving the above objective function we can get the estimates of <span>β as:</span></p>
<div><a rel="nofollow" href="https://i1.wp.com/3.bp.blogspot.com/-CDhsY4B8YWQ/WlrunCkg0KI/AAAAAAAACM4/ff1hN83GwjIjSdA1tBOhVxF_TI6xwzXpQCLcBGAs/s1600/ridge2.jpg?ssl=1" target="_blank"><img border="0" data-original-height="64" src="https://i1.wp.com/3.bp.blogspot.com/-CDhsY4B8YWQ/WlrunCkg0KI/AAAAAAAACM4/ff1hN83GwjIjSdA1tBOhVxF_TI6xwzXpQCLcBGAs/s1600/ridge2.jpg?resize=314%2C64&ssl=1" data-recalc-dims="1" data-original-width="314"></a></div>
<p><b><span>How can we choose the regularization parameter λ?</span></b></p>
<p>If we choose lambda = 0 then we get back to the usual OLS estimates. If lambda is chosen to be very large then it will lead to underfitting. Thus it is highly important to determine a desirable value of lambda. To tackle this issue, we plot the parameter estimates against different values of lambda and select the minimum value of λ after which the parameters tend to stabilize.</p>
<div></div>
<div>
<h3><span>R code for Ridge Regression</span></h3>
</div>
<div>
<div>Considering the swiss data set, we create two different datasets, one containing dependent variable and other containing independent variables.</div>
</div>
<blockquote><p>X = swiss[,-1]<br>y = swiss[,1] </p></blockquote>
<p></p>
<div>We need to load <b>glmnet</b> library to carry out ridge regression.</div>
<blockquote><p>library(glmnet)</p></blockquote>
<p>Using <b>cv.glmnet( )</b> function we can do cross validation. By default<b> alpha = 0</b> which means we are carrying out ridge regression. <b>lambda</b> is a sequence of various values of lambda which will be used for cross validation.</p>
<blockquote><p>set.seed(123) #Setting the seed to get similar results.<br>model = cv.glmnet(as.matrix(X),y,alpha = 0,lambda = 10^seq(4,-1,-0.1)) </p></blockquote>
<p></p>
<div>We take the best lambda by using <b>lambda.min</b> and hence get the regression coefficients using <b>predict </b>function.</div>
<blockquote><p>best_lambda = model$lambda.min</p></blockquote>
<p>ridge_coeff = predict(model,s = best_lambda,type = “coefficients”)<br>ridge_coeff The coefficients obtained using ridge regression are:</p>
<pre>6 x 1 sparse Matrix of class &quot;dgCMatrix&quot;<br>                           1<br>(Intercept)      64.92994664<br>Agriculture      -0.13619967<br>Examination      -0.31024840<br>Education        -0.75679979<br>Catholic          0.08978917<br>Infant.Mortality  1.09527837</pre>
<p><b><span> 6. Lasso Regression</span></b></p>
<div>Lasso stands for <b>Least Absolute Shrinkage and Selection Operator</b>. It makes use of<b> L1 regularization </b>technique in the objective function. Thus the objective function in LASSO regression becomes:</div>
<div><a rel="nofollow" href="https://i1.wp.com/1.bp.blogspot.com/-vy7hx5HBZog/WlrxD3WTeGI/AAAAAAAACNE/qXVszdrqEmEhd8FLFT_Hz6uu3MXVzVXBwCLcBGAs/s1600/lasso%2B1.jpg?ssl=1" target="_blank"><img border="0" data-original-height="42" src="https://i1.wp.com/1.bp.blogspot.com/-vy7hx5HBZog/WlrxD3WTeGI/AAAAAAAACNE/qXVszdrqEmEhd8FLFT_Hz6uu3MXVzVXBwCLcBGAs/s1600/lasso%2B1.jpg?resize=450%2C42&ssl=1" data-recalc-dims="1" data-original-width="450"></a></div>
<div>λ is the regularization parameter and the intercept term is not regularized. </div>
<p>We do not assume that the error terms are normally distributed. </p>
<div>For the estimates we don’t have any specific mathematical formula but we can obtain the estimates using some statistical software.</div>
<p><b><i>Note that lasso regression also needs standardization.</i></b></p>
<h3>Advantage of lasso over ridge regression</h3>
<div>
<blockquote><p>Lasso regression can perform in-built variable selection as well as parameter shrinkage. While using ridge regression one may end up getting all the variables but with <b>Shrinked Paramaters.</b></p></blockquote>
</div>
<div>
<h3><span>R code for Lasso Regression</span></h3>
</div>
<div>Considering the <b>swiss dataset</b> from “<b>datasets</b>” package, we have: </div>
<div>
<blockquote><p>#Creating dependent and independent variables. <br>X = swiss[,-1]<br>y = swiss[,1] </p></blockquote>
</div>
<div>Using<b> cv.glmnet </b>in <b>glmnet </b>package we do cross validation. For lasso regression we set alpha = 1. By default standardize = TRUE hence we do not need to standardize the variables seperately.</div>
<blockquote><p>#Setting the seed for reproducibility <br>set.seed(123)<br>model = cv.glmnet(as.matrix(X),y,alpha = 1,lambda = 10^seq(4,-1,-0.1))<br>#By default standardize = TRUE </p></blockquote>
<p></p>
<div>We consider the best value of lambda by filtering out <b>lamba.min</b> from the model and hence get the coefficients using <b>predict </b>function.</div>
<blockquote><p>#Taking the best lambda <br>best_lambda = model$lambda.min<br>lasso_coeff = predict(model,s = best_lambda,type = “coefficients”)<br>lasso_coeff The lasso coefficients we got are:</p></blockquote>
<pre>6 x 1 sparse Matrix of class &quot;dgCMatrix&quot;<br>                           1<br>(Intercept)      65.46374579<br>Agriculture      -0.14994107<br>Examination      -0.24310141<br>Education        -0.83632674<br>Catholic          0.09913931<br>Infant.Mortality  1.07238898<br></pre>
<h3><b><span><br></span></b></h3>
<h3><b><span>Which one is better – Ridge regression or Lasso regression?</span></b></h3>
<div>Both ridge regression and lasso regression are addressed to deal with multicollinearity. </div>
<p>Ridge regression is computationally more efficient over lasso regression. Any of them can perform better. So the best approach is to <b>select that regression model which fits the test set data well.</b></p>
<div></div>
<p><b><span>7. Elastic Net Regression</span></b></p>
<div>Elastic Net regression is preferred over both ridge and lasso regression when one is dealing with highly correlated independent variables.</div>
<p>It is a <code>combination of both L1 and L2 regularization</code>. </p>
<div></div>
<p>The objective function in case of Elastic Net Regression is: </p>
<div><a rel="nofollow" href="https://i2.wp.com/1.bp.blogspot.com/-1C5RJPcZ1vk/Wlr2qDJsijI/AAAAAAAACNU/3bSXMjEcM5ALaeTsliyhvysR-ASuCFX4QCLcBGAs/s1600/elasticnet1.jpg?ssl=1" target="_blank"><img border="0" data-original-height="50" src="https://i2.wp.com/1.bp.blogspot.com/-1C5RJPcZ1vk/Wlr2qDJsijI/AAAAAAAACNU/3bSXMjEcM5ALaeTsliyhvysR-ASuCFX4QCLcBGAs/s1600/elasticnet1.jpg?resize=450%2C50&ssl=1" data-recalc-dims="1" data-original-width="450"></a></div>
<div>Like ridge and lasso regression, it does not assume normality.</div>
<p></p>
<h3>R code for Elastic Net Regression</h3>
<div>
<div>Setting some different value of alpha between 0 and 1 we can carry out elastic net regression.</div>
</div>
<blockquote><p>set.seed(123) <br>model = cv.glmnet(as.matrix(X),y,alpha = 0.5,lambda = 10^seq(4,-1,-0.1))<br>#Taking the best lambda<br>best_lambda = model$lambda.min<br>en_coeff = predict(model,s = best_lambda,type = “coefficients”)<br>en_coeff </p></blockquote>
<p>The coeffients we obtained are:</p>
<pre>6 x 1 sparse Matrix of class &quot;dgCMatrix&quot;<br>                          1<br>(Intercept)      65.9826227<br>Agriculture      -0.1570948<br>Examination      -0.2581747<br>Education        -0.8400929<br>Catholic          0.0998702<br>Infant.Mortality  1.0775714<br></pre>
<p><b><span>8. Principal Components Regression (PCR)</span> </b><br>PCR is a regression technique which is widely used when you have many independent variables OR multicollinearity exist in your data. It is divided into 2 steps:</p>
<div>
<ol>
<li>Getting the Principal components</li>
<li>Run regression analysis on principal components</li>
</ol>
</div>
<p>The most common features of PCR are: </p>
<div>
<ol>
<li>Dimensionality Reduction</li>
<li>Removal of multicollinearity</li>
</ol>
<div></div>
</div>
<h3><span>Getting the Principal components</span></h3>
<p>Principal components analysis is a statistical method to extract new features when the original features are highly correlated. We create new features with the help of original features such that the new features are uncorrelated.</p>
<div><span>Let us consider the first principle component:</span>
<div><a rel="nofollow" href="https://i2.wp.com/3.bp.blogspot.com/-vFggXtE8i3k/WltkDFPjqFI/AAAAAAAACOw/ve6r9aZqK_QJ8ZXLcKkORF3__QMLnJuSgCLcBGAs/s1600/pca1.jpg?ssl=1" target="_blank"><img border="0" data-original-height="66" src="https://i2.wp.com/3.bp.blogspot.com/-vFggXtE8i3k/WltkDFPjqFI/AAAAAAAACOw/ve6r9aZqK_QJ8ZXLcKkORF3__QMLnJuSgCLcBGAs/s1600/pca1.jpg?resize=176%2C66&ssl=1" data-recalc-dims="1" data-original-width="176"></a></div>
</div>
<p>The first PC is having the maximum variance.<br>Similarly we can find the second PC U2 such that it is <b>uncorrelated</b> with U1 and has the second largest variance.<br>In a similar manner for ‘p’ features we can have a maximum of ‘p’ PCs such that all the PCs are uncorrelated with each other and the first PC has the maximum variance, then 2nd PC has the maximum variance and so on. </p>
<h3><span><b>Drawbacks:</b></span></h3>
<div>It is to be mentioned that PCR is not a feature selection technique instead it is a feature extraction technique. Each principle component we obtain is a function of all the features. Hence on using principal components one would be unable to explain which factor is affecting the dependent variable to what extent.</div>
<div><span><br></span></div>
<h3><span>Principal Components Regression in R</span></h3>
<div>We use the longley data set available in R which is used for high multicollinearity. We excplude the Year column.</div>
<div>
<blockquote><p>data1 = longley[,colnames(longley) != “Year”]</p></blockquote>
</div>
<p>View(data)  This is how some of the observations in our dataset will look like:</p>
<div><a rel="nofollow" href="https://i0.wp.com/4.bp.blogspot.com/-B6eJCR7lOOQ/WltvJ8-LTaI/AAAAAAAACPA/8myMa8mnSPcJLolt2U5u_zNTnYvdph8fgCLcBGAs/s1600/pca2.jpg?ssl=1" target="_blank"><img border="0" data-original-height="368" src="https://i0.wp.com/4.bp.blogspot.com/-B6eJCR7lOOQ/WltvJ8-LTaI/AAAAAAAACPA/8myMa8mnSPcJLolt2U5u_zNTnYvdph8fgCLcBGAs/s1600/pca2.jpg?resize=450%2C368&ssl=1" data-recalc-dims="1" data-original-width="450"></a></div>
<p>We use <b>pls package</b> in order to run PCR.</p>
<blockquote><p>install.packages(“pls”) <br>library(pls) </p></blockquote>
<p></p>
<div>
<div>In PCR we are trying to estimate the number of Employed people; scale  = T denotes that we are standardizing the variables; validation = “CV” denotes applicability of cross-validation.</div>
</div>
<blockquote><p>pcr_model &lt;-pcr(Employed~., data = data1, scale = TRUE, validation = “CV”) <br>summary(pcr_model) </p></blockquote>
<p></p>
<div>We get the summary as:</div>
<pre>Data:  X dimension: 16 5 <br> Y dimension: 16 1<br>Fit method: svdpc<br>Number of components considered: 5<br><br>VALIDATION: RMSEP<br>Cross-validated using 10 random segments.<br>       (Intercept)  1 comps  2 comps  3 comps  4 comps  5 comps<br>CV           3.627    1.194    1.118   0.5555   0.6514   0.5954<br>adjCV        3.627    1.186    1.111   0.5489   0.6381   0.5819<br><br>TRAINING: % variance explained<br>          1 comps  2 comps  3 comps  4 comps  5 comps<br>X           72.19    95.70    99.68    99.98   100.00<br>Employed    90.42    91.89    98.32    98.33    98.74<br></pre>
<p>Here in the RMSEP the root mean square errors are being denoted. While in ‘Training: %variance explained’ the cumulative % of variance explained by principle components is being depicted. We can see that with 3 PCs more than 99% of variation can be attributed.<br>We can also create a plot depicting the mean squares error for the number of various PCs.</p>
<blockquote><p>validationplot(pcr_model,val.type = “MSEP”)</p></blockquote>
<div><a rel="nofollow" href="https://i2.wp.com/3.bp.blogspot.com/-_v_Uv2PL1UQ/WltwxC64CqI/AAAAAAAACPM/qFUihMP8RPM590m466Dm-DHiyRSPEW7RgCLcBGAs/s1600/pca3.jpeg?ssl=1" target="_blank"><img border="0" data-original-height="356" src="https://i2.wp.com/3.bp.blogspot.com/-_v_Uv2PL1UQ/WltwxC64CqI/AAAAAAAACPM/qFUihMP8RPM590m466Dm-DHiyRSPEW7RgCLcBGAs/s1600/pca3.jpeg?resize=450%2C356&ssl=1" data-recalc-dims="1" data-original-width="450"></a></div>
<p>By writing <b>val.type = “R2” </b>we can plot the R square for various no. of PCs.</p>
<blockquote><p>validationplot(pcr_model,val.type = “R2”)</p></blockquote>
<div><a rel="nofollow" href="https://i2.wp.com/4.bp.blogspot.com/-sHy2Oag4RSM/WltxEPdbeSI/AAAAAAAACPQ/hFAfZSVAFsEK_C8ZTNRaxTUIv0lrmsbsQCLcBGAs/s1600/pca4.jpeg?ssl=1" target="_blank"><img border="0" data-original-height="356" src="https://i2.wp.com/4.bp.blogspot.com/-sHy2Oag4RSM/WltxEPdbeSI/AAAAAAAACPQ/hFAfZSVAFsEK_C8ZTNRaxTUIv0lrmsbsQCLcBGAs/s1600/pca4.jpeg?resize=450%2C356&ssl=1" data-recalc-dims="1" data-original-width="450"></a></div>
<p> If we want to fit pcr for 3 principal components and hence get the predicted values we can write:</p>
<blockquote><p>pred = predict(pcr_model,data1,ncomp = 3)</p></blockquote>
<p><b><span>9. Partial Least Squares (PLS) Regression </span></b></p>
<p>It is an alternative technique of principal component regression when you have independent variables highly correlated. It is also useful when there are a large number of independent variables.</p>
<p><b><span>Difference between PLS and PCR</span></b></p>
<blockquote><p>Both techniques create new independent variables called components which are linear combinations of the original predictor variables but PCR creates components to explain the observed variability in the predictor variables, without considering the response variable at all. While PLS takes the dependent variable into account, and therefore often leads to models that are able to fit the dependent variable with fewer components.</p></blockquote>
<p><span><b>PLS Regression in R</b></span></p>
<blockquote><p>library(plsdepot)<br>data(vehicles)<br>pls.model = plsreg1(vehicles[, c(1:12,14:16)], vehicles[, 13], comps = 3)<br># R-Square<br>pls.model$R2</p></blockquote>
<div></div>
<p><b><span>10. Support Vector Regression</span></b></p>
<p>Support vector regression can solve both linear and non-linear models. SVM uses non-linear kernel functions (such as polynomial) to find the optimal solution for non-linear models.</p>
<p>The main idea of SVR is to minimize error, individualizing the hyperplane which maximizes the margin.</p>
<blockquote><p>library(e1071)<br>svr.model &lt;-svm(Y ~ X , data)<br>pred &lt;-predict(svr.model, data)<br>points(data$X, pred, col = “red”, pch=4)</p></blockquote>
<p><b><span>11. Ordinal Regression</span></b></p>
<p>Ordinal Regression is used to <b>predict ranked values</b>. In simple words, this type of regression is suitable when dependent variable is ordinal in nature. <b>Example of ordinal variables –</b> Survey responses (1 to 6 scale), patient reaction to drug dose (none, mild, severe).</p>
<p><b><span>Why we can’t use linear regression when dealing with ordinal target variable?</span></b></p>
<p>In linear regression, the dependent variable assumes that changes in the level of the dependent variable are equivalent throughout the range of the variable. For example, the difference in weight between a person who is 100 kg and a person who is 120 kg is 20kg, which has the same meaning as the difference in weight between a person who is 150 kg and a person who is 170 kg. These relationships do not necessarily hold for ordinal variables.</p>
<blockquote><p>library(ordinal)<br>o.model &lt;-clm(rating ~ ., data = wine)<br>summary(o.model)</p></blockquote>
<p></p>
<div><b><span>12. Poisson Regression</span></b></div>
<div></div>
<div>
<div>Poisson regression is used <b>when dependent variable has count data</b>.</div>
</div>
<div></div>
<div><b><span>Application of Poisson Regression –</span></b></div>
<div>
<div>
<ol>
<li>Predicting the number of calls in customer care related to a particular product</li>
<li>Estimating the number of emergency service calls during an event</li>
</ol>
</div>
</div>
<div>
<div>The dependent variable must meet the following conditions</div>
<div>
<ol>
<li>The dependent variable has a Poisson distribution.</li>
<li>Counts cannot be negative.</li>
<li>This method is not suitable on non-whole numbers</li>
</ol>
<div></div>
</div>
</div>
<div>In the code below, we are using dataset named warpbreaks which shows the number of breaks in Yarn during weaving. In this case, the model includes terms for wool type, wool tension and the interaction between the two.</div>
<div>
<blockquote><p>pos.model&lt;-glm(breaks~wool*tension, data = warpbreaks, family=poisson)<br>summary(pos.model)</p></blockquote>
</div>
<div></div>
<div><span>13. Negative Binomial Regression</span></div>
<div></div>
<div>Like Poisson Regression, it also deals with count data. The question arises “how it is different from poisson regression”. The answer is negative binomial regression does not assume distribution of count having variance equal to its mean. While poisson regression assumes the variance equal to its mean.
<blockquote><p>When the variance of count data is greater than the mean count, it is a case of <b>overdispersion</b>. The opposite of the previous statement is a case of under-dispersion.</p></blockquote>
<blockquote><p>library(MASS)<br>nb.model &lt;-glm.nb(Days ~ Sex/(Age + Eth*Lrn), data = quine)<br>summary(nb.model)</p></blockquote>
</div>
<div></div>
<div>
<div><span>14. Quasi Poisson Regression</span></div>
<div></div>
</div>
<div></div>
<div>It is an alternative to negative binomial regression. <b>It can also be used for overdispersed count data. </b>Both the algorithms give similar results, there are differences in estimating the effects of covariates. The variance of a quasi-Poisson model is a linear function of the mean while the variance of a negative binomial model is a quadratic function of the mean.</div>
<div>
<blockquote><p>qs.pos.model &lt;-glm(Days ~ Sex/(Age + Eth*Lrn), data = quine,  family = “quasipoisson”)</p></blockquote>
</div>
<div>Quasi-Poisson regression can handle both over-dispersion and under-dispersion.</div>
<div></div>
<div></div>
<div>
<div>
<div><span>15. Cox Regression</span></div>
<div></div>
</div>
</div>
<div></div>
<div>
<div>Cox Regression is suitable for time-to-event data. See the examples below –</div>
<div>
<ol>
<li>Time from customer opened the account until attrition.</li>
<li>Time after cancer treatment until death.</li>
<li>Time from first heart attack to the second.</li>
</ol>
</div>
<div>
<blockquote><p>Logistic regression uses a binary dependent variable but ignores the timing of events. </p></blockquote>
<p>As well as estimating the time it takes to reach a certain event, survival analysis can also be used to compare time-to-event for multiple groups.</p></div>
<div>
<div>Dual targets are set for the survival model </div>
<div>1. A continuous variable representing the time to event.</div>
<div>2. A binary variable representing the status whether event occurred or not.</div>
</div>
</div>
<div>
<blockquote><p>library(survival)<br># Lung Cancer Data<br># status:<span> </span>2=death<br>lung$SurvObj &lt;-with(lung, Surv(time, status == 2))<br>cox.reg &lt;-coxph(SurvObj ~ age + sex + ph.karno + wt.loss, data =  lung)<br>cox.reg</p></blockquote>
<p></p>
<div><span>How to choose the correct regression model?</span>
<ol>
<li>If dependent variable is continuous and model is suffering from collinearity or there are a lot of independent variables, you can try PCR, PLS, ridge, lasso and elastic net regressions. You can select the final model based on Adjusted r-square, RMSE, AIC and BIC.</li>
<li>If you are working on count data, you should try poisson, quasi-poisson and negative binomial regression.</li>
<li>To avoid overfitting, we can use cross-validation method to evaluate models used for prediction. We can also use ridge, lasso and elastic net regressions techniques to correct overfitting issue.</li>
<li>Try support vector regression when you have non-linear model.</li>
</ol>
</div>
</div>
<div>
<div></div>
</div>
</div>
<div><span> About Author:</span> 
<p>Deepanshu founded ListenData with a simple objective – Make analytics easy to understand and follow. He has over 7 years of experience in data science and predictive modeling. During his tenure, he has worked with global clients in various domains.</p>
<p>Let's Get Connected: <a rel="nofollow" href="https://www.linkedin.com/in/deepanshubhalla" target="_blank">LinkedIn</a></p>
</div>
	<p>
<div>
<div>To <strong>leave a comment</strong> for the author, please follow the link and comment on their blog: <strong><a href="http://www.listendata.com/2018/03/regression-analysis.html"> ListenData</a></strong>.</div>
<hr>
<a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers.com</a> offers <strong><a rel="nofollow" href="https://feedburner.google.com/fb/a/mailverify?uri=RBloggers">daily e-mail updates</a></strong> about <a rel="nofollow" href="https://www.r-project.org/" title="The R Project for Statistical Computing">R</a> news and <a rel="nofollow" href="https://www.r-bloggers.com/search/tutorial" title="R tutorials">tutorials</a> on topics such as: <a rel="nofollow" href="https://www.r-bloggers.com/search/data%20science" title="Data science">Data science</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/Big%20Data" title="Big Data">Big Data, <a rel="nofollow" href="https://www.r-users.com/" title="R jobs">R jobs</a>, visualization (<a rel="nofollow" href="https://www.r-bloggers.com/search/ggplot2" title="ggplot and ggplot2 tutorials">ggplot2</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/boxplot" title="Boxplots using lattice and ggplot2 tutorials">Boxplots</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/map" title="Maps and gis">maps</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/animation" title="Animation in R">animation</a>), programming (<a rel="nofollow" href="https://www.r-bloggers.com/search/RStudio" title="RStudio IDE for R">RStudio</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/sweave" title="Sweave and literate programming">Sweave</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/LaTeX" title="LaTeX in R">LaTeX</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/SQL" title="SQL and databases">SQL</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/eclipse" title="Eclipse IDE for R">Eclipse</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/git" title="git and github, Version Control System">git</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/hadoop" title="Large data in R using Hadoop">hadoop</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/Web+Scraping" title="Web Scraping of google, facebook, yahoo, twitter and more using R">Web Scraping</a>) statistics (<a rel="nofollow" href="https://www.r-bloggers.com/search/regression" title="Regressions and ANOVA analysis tutorials">regression</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/PCA" title="principal component analysis tutorial">PCA</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/time+series" title="Time series">time series</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/trading" title="finance trading">trading</a>) and more...
<img width="1" alt="" src="http://feeds.feedburner.com/~r/RBloggers/~4/yyy7kTN8u0w" height="1"></a></div>