Introduction to Regression Algorithms
local graph
Chapter 4 — Introduction to Regression Algorithms
Section titled “Chapter 4 — Introduction to Regression Algorithms”“It ain’t ignorance causes so much trouble; it’s folks knowing so much that ain’t so.”
-Billings
Every day, the number of predictive analytics techniques seems to be increasing. There is a constant debate about whether we need better algorithms, or whether more or better data is needed in order to attack a predictive analytics problem.
Whatever the case, it is always good to keep abreast of all of the available algorithms at your disposal. It is equally important to hone your skills on the top three or four algorithms that can tackle 90% of the problems that you will face, and be able to understand the situations in which it makes sense to use them.
This chapter is the first of two chapters which will present four basic algorithms which cover a lot of typical business situations that you will encounter. In fact, many of the data science surveys which poll analytics practitioners will often include these techniques in the top techniques that all data scientists should know. Among these techniques, we will discuss regression in detail for this chapter and the three remaining core algorithms in the following chapters. But lets start by introducing all four:
- Regression techniques represent a standard parametric approach to problem solving which assigns a coefficient or weight to each of the independent variables. Variables are related to the outcome variable via a linear function.
- Decision trees are an important algorithm class which can be used as an alternative to regression when the relationships of the variables may not necessarily be linear.
- Cluster analysis is also discussed as a form of unsupervised learning, which is more exploratory in nature, but not necessarily predictive.
- Support vector machines are useful in situations in which you have high dimensional data. High dimensional data comes into play when you have a large number of variables appearing in the data, and you have chosen to use all or most of them in the model, without first applying some sort of data reduction technique. This can often occur as you apply analysis to some real-time data in raw form, in which case models need to be applied in split-second time.
We have already discussed the concept of target (dependent) variables and independent variables, or features. Features (or independent variables) are used to describe the relationship with, or to predict values of, a target variable. After defining your independent and depending variables, you will formulate your model. One way to characterize the way in which a model learns from the data, is by classifying it into either a supervised or unsupervised learning model.
When the possible values of a target variable are specified and labeled, a model is considered supervised, that is, we know what we want to predict, and the goal is to find the most appropriate predictive model which will predict the outcome.
As an example, if we are predicting the approval rating for a product, we know what we are predicting (approval rating of a product), and we also usually know the range of possible outcomes. It could be a percentage from 0-100, or it could be some category such as high approval or low approval.
When the problem is supervised, the choice of which models to use are usually dependent upon the type of the target variable, that is, whether it is continuous or categorical. It can also be dependent upon factors such as bias/variance (discussed in Chapter 2, The Modeling Process), and the various assumptions we are willing to make concerning the model. Regression and decision tree algorithms are considered supervised algorithms since the target variables or target classes (in the case of decision trees) are specified even before the predictive modelling begins.
Unsupervised problems are more exploratory in nature. In an unsupervised learning context, one doesn’t specify a target variable, or even have any idea what something should be. A data scientist is usually given a set of attributes, and then asked to derive some relationships, or discover some new attributes which are not obvious from looking at the data.
As an example, during an exploratory customer analysis, you could look at different attributes of customers, such as age, gender, and sales history, which could then lead you to create new variables (which hadn’t existed before), which would describe each customer as best, good, or average. You could then choose an appropriate algorithm to suit this problem which might be a clustering algorithm, a decision tree, or a support vector machine.
Another example would be to use a neural network algorithm with some financial trading data in order to uncover some potential fraud or anomaly findings.
Usually, you will match up an unsupervised algorithm (such as neural networks) cast to an unsupervised setting (find fraud), but that is not always the case. You may find that you are able to incorporate traditional supervised techniques such as regression to find results which are totally unexpected using post-diagnostic tools which would examine such thing as residuals and outliers. That might lead you to other explorations which could cause you to reformulate your problem.
Finally, supervised learning and unsupervised learning often work hand in hand. It is possible to find yourself creating a new variable, discovered through an unsupervised process, which in turn would lead to incorporating this as a latent variable into a traditional supervised algorithm, such as a decision tree.
Regression analysis (which is considered a supervised learning algorithm) dates back to the early 1800s when Gauss and Legendre utilized these techniques to measure the trajectories of the planets around the sun (https://en.wikipedia.org/wiki/Regression_analysis). The regression algorithm’s usage is still going strong within the predictive analytics community due to its large base of literature and its ability to adapt to a wide range of problems.
Linear regression is the basic regression technique to use when your target variable is continuous. Linear regression is built upon the concept of ordinary least squares, and the functional form of the model is:

The preceding formula illustrates that linear regression models are additive, that is, the results of the prediction are calculated by summing the cross-product values of all of the independent variables, and then adding an intercept (first term of the formula), and error term (last term of the formula). That calculation yields the prediction for the dependent or target variable (y). The linear regression line is fitted via the method of ordinary least squares (OLS), in which the squared (residual) differences between the observed value and the predicted distances on the regression line are minimized. Squared differences are used, rather than the actual differences, since we are really interested in the magnitude, not the direction of the differences. Squaring the results eliminates the negative or positive sign. The residuals are often used to test the errors resulting from the predictive model.
One advantage to using linear regression is that it facilitates easy interpretation of the linear coefficients which are attributed to each variable. Specifically, the slope of each variable in a regression model (the β in front of each of the regression terms), will indicate the change in the prediction for each 1-unit change in the corresponding independent variable, with all other variables in the model held constant. There is a fair amount of flexibility in using linear models in that you can also model nominal (categorical) independent variables as well as continuous ones, and incorporate a fair degree of non-linear relationships by using variable transformations and interactions. The body of knowledge for linear regression is vast, and based heavily on probability theory.
While linear regression can be very powerful when used correctly, here are some of the major assumptions of linear regression which you should pay attention to:
- Independence: the observations have no relationship with each other. This assumption will often be violated when you are dealing with time-series data. Knowing how the data was sampled will help with understanding whether or not the data is independent and randomly sampled.
- Linearity: there is a linear relationship between the independent and dependent variables. Other kinds of relationships can exist; for example there can be a curvilinear relationship between the variables. The second plot of the first row in the Wikipedia reference for Anscombe’s quartet shows how this can occur.
- Normality: the errors term in the regression model is normally distributed. Intuitively, normally distributed residuals are good to have since they imply that the correct variables are all accounted for in your model, and there is nothing left to explain. You are just left with random error.
- Equal variances of errors: the error terms also have constant variance. For example, non equality of variances can mean that the errors in prediction are increasing or decreasing as values of the independent variables grow larger or smaller.
If any of the assumptions are grossly violated, you probably should not be using linear regression. I say grossly since there is a certain degree of tolerance that any model has for assumptions, and there are statistical tests that can be used to measure that degree for some of the assumptions. However, if your data meets the assumptions of linear regression, the predictions can be quite powerful.
Generalized linear models (GLMs) refer to a larger framework of prediction techniques which can include linear regression, logistic regression (used to predict binary outcomes), and poisson regression (used to predict counts). They are a generalization of linear regression techniques which allow you to work with other distributions which have non-normal error terms. GLMs can be implemented in R by using the glm package, in which you supply a link function to specify which distribution you are modeling. That makes it easier to work with different types of models within a single package, using standard syntax.
In Chapter 1, Getting Started with Predictive Analytics, our original example that we used to predict womens’ heights based upon womens’ weights used the lm package. We could also have used the glm package, specifying family=Gaussian as the link function:
lm_output <- lm(women$height ~ women$weight)or:
glm_output <- glm(women$height ~ women$weight,family=gaussian)A very popular use of GLM is via logistic regression. This is the type of regression to use when your target variable is a binary value, that is, it can only take on two values. These two binary values usually take the form:
- Something occurred (binary value = 1)
- Something did not occur (binary value = 0)
These two values typically vary according to the type of industry. Here are some examples of binary responses in different industries:
- Marketing: Did the customer respond to a specific offer or not?
- Health care: Was a specific drug effective in treating a condition or was it not?
- Financial: Did a specific trading strategy lead to a profit or not?
- Web tracking: Did a customer abandon a shopping cart at the checkout or not?
Virtually every industry will have problems which can be formulated in terms of binary outcomes. In fact, sometimes standard linear regression problems are often recast, so instead of predicting the specific values for the target value, the problem will be reformulated into a binary problem. Often this is done to take advantage of some of the relaxed assumptions of logistic regression.
You may ask, “Why not use regular linear regression for these kinds of problems?” Unfortunately, linear regression itself will not work when you have a binary outcome variable for a variety of reasons. Here are two important ones:
- First of all, if regular regression is used, the results will extend way beyond the bounded ranges of 0 and 1, since a line is infinite in both directions.
- Second, one of the requirements of regular regression is that the residual errors are normally distributed, and this is not true in the case of logistic regression. The error term is related to a conditional Bernoulli distribution.
However, logistic regression does share many of the features of regression models:
- It is a low variance algorithm, and as a result it is fairly simple to implement and explain, and does not have as many problems with overfitting as some of the other algorithms.
- It also has good capabilities for feature selection, and the addition of transformed variables and interactions which it shares with linear regression. However, what it does predicts (the likelihood of an event), sets it apart from standard regression techniques.
While linear regression will predict an actual outcome for the dependent variable, logistic regression does not predict actual outcomes or events. What it will predict is the likelihood, (or odds ratio) of one of the events occurring. This is slightly different since it is related to the probability of an event occurrence (rather than the prediction of the event itself).
The odds ratio is defined as the ratio of the probability of an event A occurring divided by the probability of an event not occurring. In functional form, this ratio is expressed as a natural logarithm:

The coefficients returned from the logistic regression are standardized, in that they measure the effect of a 1-unit change in the independent variable on the log of the odds ratio, and not on the change of the variable itself.
The algorithm determines these coefficients not by using the OLS method used in linear regression, but it determines the coefficients by using a method called maximum likelihood estimation. Simply put, this means that the algorithm starts with arbitrary values of the coefficients and then puts forth an initial model. Then the algorithm measures the errors in the model and adjusts the coefficients to new values so that the results of the next model conform better to the values contained in your data. This is performed iteratively until the errors converge to an optimal solution.
Since the predictions from a linear model are determined by summing up the cross products and intercepts from the model, this result can be compared to a 0.5 percent cut-off value, which is used as a decision rule to classify an occurrence into one of the two values of the target variables. So while the output of a logistic regression is really a function of an odds ratio, logistic regression can essentially be used as a classification algorithm.
This example takes data from a research study which predicts whether or not a subject reported experiencing a reduction of pain for a condition, after being administered various treatments. The Gender, Age, and the Duration columns of any pre-existing pain were also used as independent variables in the model. The outcome variable, Pain, is coded as 1 (reported pain), or 0 (reported no pain). The Treatment column refers to 1 of 2 treatments (A or B), as well as a control group (P).
We will use the read.table with the text= option to read the raw data inline, that is, without the need to first create an external file. This method is useful for analysis in which you are copying and pasting data from another source, for example, a spreadsheet:
df <- read.table(text = 'Treatment Gender Age Duration Pain P F 68 1 0 P M 66 26 1 A F 71 12 0 A M 71 17 1 B F 66 12 0 A F 64 17 0 P M 70 1 1 A F 64 30 0 B F 78 1 0 B M 75 30 1 A M 70 12 0 B M 70 1 0 P M 78 12 1 P M 66 4 1 A M 78 15 1 P F 72 27 0 B F 65 7 0 P M 67 17 1 P F 67 1 1 A F 74 1 0 B M 74 16 0 B F 67 28 0 B F 72 50 0 A F 63 27 0 A M 62 42 0 P M 74 4 0 B M 66 19 0 A M 70 28 0 P M 83 1 1 P M 77 29 1 A F 69 12 0 B M 67 23 0 B M 77 1 1 P F 65 29 0 B M 75 21 1 P F 70 13 1 P F 68 27 1 B M 70 22 0 A M 67 10 0 B M 80 21 1 P F 67 30 0 B F 77 16 0 B F 76 9 1 A F 69 18 1 P F 64 1 1 A F 72 25 0 B M 59 29 0 A M 69 1 0 B F 69 42 0 P F 79 20 1 B F 65 14 0 A M 76 25 1 B F 69 24 0 P M 60 26 1 A F 67 11 0 A M 75 6 1 P M 68 11 1 A M 65 15 0 P F 72 11 1 A F 69 3 0',header = TRUE)Now that the data has been read, switch over to the console window. At the console prompt, enter the command table(df$Pain). This function will give you the raw counts of the number of patients who did or did not experience pain:
> table(df$Pain)This is the output that will appear in the console window:
0 135 25The prop.table function will supply you with the percentages of reported pain:
> prop.table(table(df$Pain))This is the following output:
0 10.5833333 0.4166667Before we do anything else, let’s save this dataframe to disk, since we will be using it again in this chapter. Before saving the file, make sure you set your working directory to the data directory:
setwd("C:/PracticalPredictiveAnalytics/Data")save(df,file="pain_raw.Rda")Now we will fit a logistic model using the glm package. Logistic regression typically predicts the probability of the 1 event, so make sure that the 1 events corresponds to what you want to predict. Often there is some confusion when variables are coded 1 for negative conditions such as not present, or does not exist. For our model, Pain=1 represents reduction of pain. Be sure to specify family=“binomial” as an option, since that tells GLM that you will be running a logistic model:
PainGLM <- glm(Pain ~ Treatment + Gender + Age + Duration, data=df, family="binomial")The summary function will list the coefficients (Estimate), along with the standard error, standardized z value, and the p-values. The p-values (last column) which contain an asterisk (* or **) usually specify the significant variables, and are usually the ones you should look at first. However, please try not to automatically look at just the variables with asterisks. You should look at the coefficients and statistics for all of the variables, since p-values should not be treated as absolute numbers, especially when dealing with people’s health:
summary(PainGLM)This is the output that is produced:
Call:glm(formula = Pain ~ Treatment + Gender + Age + Duration, family = "binomial", data = df)
Deviance Residuals: Min 1Q Median 3Q Max-2.7638 -0.5904 -0.1952 0.6151 2.3153
Coefficients: Estimate Std. Error z value Pr(>|z|)(Intercept) -20.588282 7.102883 -2.899 0.00375 **TreatmentB -0.526853 0.937025 -0.562 0.57394TreatmentP 3.181690 1.016021 3.132 0.00174 **GenderM 1.832202 0.796206 2.301 0.02138 *Age 0.262093 0.097012 2.702 0.00690 **Duration -0.005859 0.032992 -0.178 0.85905---Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
(Dispersion parameter for binomial family taken to be 1)
Null deviance: 81.503 on 59 degrees of freedomResidual deviance: 48.736 on 54 degrees of freedomAIC: 60.736
Number of Fisher Scoring iterations: 5As mentioned earlier, the output coefficients are expressed as the log of the odd-ratio. To express the coefficients in the original scale, you will need to apply the exp() function. Also, in the following code, we will include confidence intervals along with the exponentiated coefficients to get an idea of the ranges. Look for any confidence interval in which 0 is contained within the range, since that implies that the effect may be non-existent or slight.
In the following example, TreatmentB and Duration all contain 0 within their respective confidence intervals:
cbind(exp(coef(PainGLM)),confint(PainGLM))This is the output which results:
2.5 % 97.5 %(Intercept) 0.000000001144518 -36.68451736 -8.30307052TreatmentB 0.590460426864162 -2.47589653 1.28411227TreatmentP 24.087421759279735 1.38534008 5.45845778GenderM 6.247629578965714 0.38227954 3.58627713Age 1.299647808771851 0.09349231 0.48146218Duration 0.994158449470197 -0.07338820 0.05768555The exp() function will give you the actual likelihood ratios for each of the variables. This allows you to observe the effect of each variable on the likelihood of the predictor occurring. In our previous example, increasing the Age by 1 year increases the likelihood of Pain by a factor of 1.3. Is that a lot? Start thinking beyond the numbers and consider how you might perceive that result if you happened to be suffering a chronic condition.
One of the first things I do after looking at the coefficients is to look at the residuals.
You can see all of the residuals by using the residuals() function:
residuals(PainGLM, type="deviance") # residualsFor many good models, the residuals will be scattered around zero, and will have roughly the same variance at all levels. The deviance of the residuals for this model are listed within the summary section shown previously. We can see that the distribution is balanced since the absolute values of the min and max are approximately equal, as well as 1Q (25th percentile) with 3Q (75th percentile):
Deviance Residuals: Min 1Q Median 3Q Max-2.7638 -0.5904 -0.1952 0.6151 2.3153If we want to look at the mean, we can wrap the mean() function around the residuals() function. Note that the mean value of -0.04 is greater than the median value of -0.195. This means that the residuals have a slightly positive skew:
mean(residuals(PainGLM, type="deviance"))Here is the output which will appear in the console:
[1] -0.04269042Plots are extremely helpful at showing the residuals, and often are critical at diagnosing problems with a model:
plot(residuals(PainGLM, type="deviance"))The plot which is output indicates a good example of neatly distributed residuals. Along the range of index, the residuals look like they are scattered around 0, and there seems to be no major trending upwards or downwards along the range, other than the slight skew noted previously:

Added variable plots allow you to examine the effect of a specific variable, while holding the coefficients of the other variables constant. In other words, it visually describes what happens when you add one more variable to the model. It can also be seen as one way to examine a specific variable’s effect, by projecting a multiple regression line onto a 2-dimensional space. In this way, you can examine which variables have more influence compared to the others.
In the following plots, we will use the avPlots() function from the car package. You can see the strong linear effect of Age, while there is a negligible effect for Duration. This is also reflected in the coefficients and significance of the logistic regression model shown previously:
library(car)library(car)avPlots(PainGLM, id.method="mahal", id.n=2)
Note that preceding each plot also identifies extreme data points in the dataset which may have an influence upon the regression line (line drawn through the data). The extreme values are represented in bold within the plot itself.
For example,in all of the preceding plots, you can see that observation 26 is considered an outlier with respect to the other covariates.
Print this observation to the console along with some of its neighbors. You can see how this could be considered an outlier just by inspection, since two variables (Duration and Treatment) immediately pop out as being different from the surrounding observations:
df[c(26,27,28,25),]This is the output which is sent to the console:
Treatment Gender Age Duration Pain26 P M 74 4 027 B M 66 19 028 A M 70 28 025 A M 62 42 0P-values have been the traditional way of performing hypothesis testing on output statistics, but have come under criticism in recent year as not being the appropriate measure to use, in many cases.
Datasets are much larger than they used to be. A very large dataset with a large number of variables can always show a significant p-value, even when none exist.
There are also a large number of different kinds of algorithms as well than can produce p-values, and there is a good chance you can pick one which will give you the p-value you want.
There are different p-value cut-off levels that an analyst can use to force significance.
The more dangerous situation is when you can select or alter the data to affect the p-value. This can be often very subtle, and can manifest itself through non-random sampling, data transformations from one level to another, keeping missing values, or deleting or imputing them. All of the decisions made by the modeler prior to applying the statistical test will affect the p-value.
Having said that, p-values are still useful for identifying possible significant predictors, and for understanding if the data fits the model. But it should be treated as only one tool, just as each algorithm you use is only one tool of many which you will use to help reveal the truth. Other tools we have demonstrated (such as confidence intervals, random sampling, and variable influence plots) should be used along with the calculation of p-values to present a complete picture of the data.
Here is an important statement from the American Statistical Associatio n on the usage of p-values (AMERICAN STATISTICAL ASSOCIATION RELEASES STATEMENT ON, 2016):
- P-values can indicate how incompatible the data is with a specified statistical model
- P-values do not measure the probability that the studied hypothesis is true, or the probability that the data was produced by random chance alone
- Scientific conclusions and business or policy decisions should not be based only on whether a p-value passes a specific threshold
- Proper inference requires full reporting and transparency
- A p-value, or statistical significance, does not measure the size of an effect or the importance of a result
- By itself, a p-value does not provide a good measure of evidence regarding a model or hypothesis
There has always been this concern regarding p-values with small samples, however using data with large samples can also yield bad results, in that the p-value may be correct, but the magnitude of the change (the effect) is very small.
Take this example in which you are measuring the effect of winning between an average of 1,000,001 in a lottery.
We will generate two probability samples:
- X contains 1 million observations with a mean value of 1,000,000
- Y also contains 1 million observations but with a mean value of 1,000,001 and it is only a 1-unit difference
Generate a dataframe with X and Y and print some summary statistics:
set.seed(1020)lottery <- data.frame( cbind(x=rnorm(n=1000000,1000000,100),y=rnorm(1000000,1000001,100) )) summary(lottery)The output shows the simulated X and Y exactly as we expect. Both with the same number of observations, but with only a 1-unit difference in the mean values:
x yMin. : 999503 Min. : 9995131st Qu.: 999933 1st Qu.: 999934Median :1000000 Median :1000001Mean :1000000 Mean :10000013rd Qu.:1000067 3rd Qu.:1000068Max. :1000526 Max. :1000489If we run a statistical t-test on the difference between the means, the p-value shows a very significant difference based upon the p-value. But, for only a $1 difference:
t.test(lottery$x,lottery$y)This is the output which is written to the console:
Welch Two Sample t-test
data: lottery$x and lottery$yt = -7.4518, df = 2000000, p-value = 9.209e-14alternative hypothesis: true difference in means is not equal to 095 percent confidence interval: -1.3303374 -0.7762632sample estimates:mean of x mean of y 999999.9 1000001.0Now let’s repeat this simulation, but this time run this same code using a much smaller value of n, say n=100000:
set.seed(1020) lottery <- data.frame( cbind(x=rnorm(n=100000,1000000,100),y=rnorm(n=100000,1000001,100) ) )summary(lottery)This is the output which is written to the console:
x yMin. : 999545 Min. : 9995901st Qu.: 999933 1st Qu.: 999934Median :1000000 Median :1000000Mean :1000000 Mean :10000013rd Qu.:1000068 3rd Qu.:1000068Max. :1000446 Max. :1000450Now re-run the t-test again, and notice we are obtaining a much larger p-value of 0.2492:
t.test(lottery$x,lottery$y)This is the output which is written to the console:
Welch Two Sample t-test
data: lottery$x and lottery$yt = -1.1522, df = 200000, p-value = 0.2492alternative hypothesis: true difference in means is not equal to 095 percent confidence interval: -1.3899758 0.3607735sample estimates:mean of x mean of y 1000000 1000001Here is the point of this exercise.
If these were amounts won in a lottery, most people would not care whether or not they won 1,000,001 (regardless of the sample size), so what comes into play is the effect size, which in this case is simply the difference between the two means (1 does not make a difference, but what is important about this is that you need to know approximately how much of a change is meaningful to you in your analytics work.
Stepwise regression can be used as a variable selection method in cases in which you have a large number of variables, and you need to define a starting point in which you can start looking at a limited set of variables. However, all of the caveats regarding p-values come into play here as well. Use this method only to look at a candidate list of variables for model testing. It is not a good idea to use stepwise regression to determine a final model, since there are several methods use to determine the best variables, the final model can yield artificially high and biased results.
However, let’s just start with identifying a list of potential variables for our PainGLM model, which is small, but will be good to illustrate the process. In the following example, the stepwise() function is used to determine a maximum AIC using the stepwise regression forward/backward options.
The variable selection process starts by adding variables one at a time, and then implementing a form of variable swapping, that is, taking into account whether or not AIC would be improved by removing any variable which was already in the model. Once AIC cannot be improved, the selection process stops.
- In the PainGLM example, the algorithm is illustrated, listing all the steps it goes through to determine the final variables selected. It begins with an initial AIC statistic of 83.5 (intercept-only model). Adding all of the variables into the model produces an AIC of 73.48. However, the AIC can then be improved by removing Duration. Therefore, it ends with a Treatment, Age, and Gender model with an AIC of 58.77, since it can no longer improve the AIC:
install.packages("RcmdrMisc")library(RcmdrMisc)stepwise(PainGLM, direction='forward/backward',criterion='AIC')The output of the stepwise function is written to the console:
Direction: forward/backward-Criterion: AIC
Start: AIC=83.5Pain ~ 1
Df Deviance AIC+ Treatment 2 67.480 73.480+ Age 1 73.056 77.056+ Gender 1 75.849 79.849<none> 81.503 83.503+ Duration 1 79.886 83.886
Step: AIC=73.48Pain ~ Treatment Df Deviance AIC+ Age 1 55.044 63.044+ Gender 1 59.886 67.886<none> 67.480 73.480+ Duration 1 66.688 74.688- Treatment 2 81.503 83.503
Step: AIC=63.04Pain ~ Treatment + Age Df Deviance AIC+ Gender 1 48.767 58.767<none> 55.044 63.044+ Duration 1 55.036 65.036- Age 1 67.480 73.480- Treatment 2 73.056 77.056
Step: AIC=58.77Pain ~ Treatment + Age + Gender
Df Deviance AIC<none> 48.767 58.767+ Duration 1 48.736 60.736- Gender 1 55.044 63.044- Age 1 59.886 67.886- Treatment 2 68.900 74.900
Call: glm(formula = Pain ~ Treatment + Age + Gender, family = "binomial", data = df)
Coefficients: (Intercept) Treatment[T.B] Treatment[T.P] Age Gender[T.M] -20.8694 -0.5474 3.1790 0.2650 1.8235
Degrees of Freedom: 59 Total (i.e. Null); 55 ResidualNull Deviance: 81.5Residual Deviance: 48.77 AIC: 58.77We have seen that regression is additive, that is, the prediction is mostly calculated via adding crossproducts of the coefficients and independent single variables together. However, often single variables by themselves are not enough to adequately predict an outcome in a simple regression model. Often considering how say, predictor variable A affects predictor variable B can improve the outcome. This also goes a long way in terms of explaining the rationale behind using certain variables. The way two or more variables influence each other is referred to as interaction, and using an interaction in a model can produce an effect which is greater than the sum of their individual effects. Usually, two or more interaction variables are involved, and the way that one variable effects the dependent variable is conditional upon the different levels or ranges of the other variables.
In this example, we will take our original Pain model and determine if there is a separate effect for the different treatments by age. Interaction effects can be specified in the model by using the : separator (the colon). If we also want to include the individual variable effects as well as the interaction we would use the * separator.
First we will set up the model as we did before, but specify an Age:Treatment effect in the model. We will do this because we already know that Age and the Type of treatment independently can predict the Pain outcome to some degree, but we are interested to see if knowing the Age of the participant together with the type of treatment they received will improve the model. If so, we could research administrating different treatments to the various age groups, and as a result, affect the output variable (Pain):
install.packages("effects")library(effects)output <- glm(Pain ~ Treatment + Gender + Age + Duration + Age:Treatment ,data=df, family="binomial")summary(output)The output of the summary function is written to the console:
glm(formula = Pain ~ Treatment + Gender + Age + Duration + Age:Treatment, family = "binomial", data = df)
Deviance Residuals: Min 1Q Median 3Q Max-2.21745 -0.38598 -0.05829 0.44605 2.53761
Coefficients: Estimate Std. Error z value Pr(>|z|)(Intercept) -39.420723 20.276062 -1.944 0.0519 .TreatmentB -9.012876 31.965793 -0.282 0.7780TreatmentP 38.338070 21.827078 1.756 0.0790 .GenderM 1.957605 0.872107 2.245 0.0248 *Age 0.524314 0.283665 1.848 0.0646 .Duration 0.003562 0.036643 0.097 0.9226TreatmentB:Age 0.100597 0.433846 0.232 0.8166TreatmentP:Age -0.504315 0.307248 -1.641 0.1007---Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
(Dispersion parameter for binomial family taken to be 1)
Null deviance: 81.503 on 59 degrees of freedomResidual deviance: 41.928 on 52 degrees of freedomAIC: 57.928
Number of Fisher Scoring iterations: 7In the output that appears preceding, note that instead of having one coefficient for Treatment, we have two separate coefficients for TreatmentB and TreatmentP, as well as the interaction of these levels versus Age. Note that none of the new interaction terms have significance codes in the last column.
Interaction effects plot:
The interaction effects can be shown using plot with the effects() function:
plot(effect("Treatment*Age", output, xlevels=list(age=0:99)),ticks=list(at=c(.001, .005, .01, .05, seq(.1,.9,by=.2), .95, .99, .995)))As the plots indicate, there is no interaction between TreatmentP (Placebo) and Age, which is what you would expect in a controlled study. The plots also indicate the relationship between Age and Pain for the other two treatments, but there is not enough of a significant difference (at the 0.05 level) to justify including this as an individualized coefficient:

Goodness of fit tests determine how well a model fits the data. There are several methods of judging how well the data fits the logistic regression model:
- Data partitioning: One way we learned how to do this was by dividing the data into training and testing datasets and measuring the degree to which they produce similar results. That method was demonstrated in Chapter 2, The Modeling Process.
- Single metrics: Another way to do this is to come up with a quantitative measure of how well your independent variable predicts your dependent variables on a scale from 0 to 1, with 0 meaning no predictive power, and 1 meaning the best possible predictive power. Area Under the Curve (AUC), and R-square are examples of these kind of Goodness of Fit (GOF) tests.
- R-Square is a popular method of assessing goodness of fit, and it roughly measures the amount of explained variation in a model to the total variation. In linear regression, it is calculated by first taking the ratio of the residual Sum of Squares to the total Sum of Squares and subtracting the result from 1. (Coefficient of Determination)

- Interestingly enough, logistic regression does not have an R-square statistic. That is because R-Square is based upon the assumption that the model you are fitting is linear, and as we have seen, logistic regression does not make that assumption. However, pseudo R-Square measures have been developed which contain the same 0-1 scale. Of these measure is the McFadden Statistic.
The McFadden statistic approximates an R-Square type measure by looking at the ratio of the log-likelihood of the full model (analogous to the sum of squared errors in the OLS R-square model formula previously defined), divided by the log-likelihood of an intercept-only model (similar to the R-square total sum of squares denominator). This approximates the improvement of a logistical model over the intercept-only null model. The McFadden statistic can be considered a pseudo R-square since it will try to measure the same thing, and produce similar R-square results within the same 0-1 scale.
Here is the McFadden formula from the UCLA Institute for Digital Research and Education. (FAQ: WHAT ARE PSEUDO R-SQUAREDS?):

In the following code, the McFadden statistic of 0.40 shows that the model has a reasonably good fit:
install.packages("pscl")library(pscl)pR2(PainGLM)The output of the pR2() function is written to the console:
llh llhNull G2 McFadden r2ML-24.3678589 -40.7515960 32.7674742 0.4020392 0.4208099 r2CU 0.5664233A Wald test is used to evaluate the statistical significance of each coefficient in the model and is calculated by taking the ratio of the square of the regression coefficient to the square of the standard error of the coefficient. The idea is to test the hypothesis that the coefficient of an independent variable in the model is not significantly different from zero.
The output shows the 95% confidence interval (with the lower 2.5% limit, and the upper 97.5% limit). Two intervals are given, one for the actual model coefficient, and the other for the exponentiated coefficient. We can again see that 0 is contained within the range for Duration, so we can consider removing the variable from the model:
confint(output, level=0.95, type="Wald")The output of the confint() function is written to the console:
Estimate 2.5 % 97.5 % exp(Estimate)(Intercept) -20.588282035 -34.50967776 -6.66688631 1.144518e-09Treatment[T.B] -0.526852662 -2.36338765 1.30968232 5.904604e-01Treatment[T.P] 3.181689786 1.19032495 5.17305463 2.408742e+01Gender[T.M] 1.832202124 0.27166722 3.39273703 6.247630e+00Age 0.262093311 0.07195380 0.45223282 1.299648e+00Duration -0.005858679 -0.07052171 0.05880435 9.941584e-01 2.5 % 97.5 %(Intercept) 1.029526e-15 1.272354e-03Treatment[T.B] 9.410090e-02 3.704997e+00Treatment[T.P] 3.288150e+00 1.764530e+02Gender[T.M] 1.312150e+00 2.974726e+01Age 1.074606e+00 1.571818e+00Duration 9.319075e-01 1.060568e+00Plots are very critical for diagnosing fit and any potential problems associated with a regression model. These four plots can help you identify observations which do not fit in neatly with the regression, and should be looked at individually to see if there is anything special about them. It is just a part of the iterative process which is a part of developing your model, and does not by itself indicate a bad model.
Run the basic plot for PainGLM. Note that we will plot the four plots in a 2x2 quadrant:
oldpar <- par(oma=c(0,0,3,0), mfrow=c(2,2))plot(PainGLM)par(oldpar)
Residual versus fitted: The residual versus fitted plot helps with determining if there are any patterns in the residuals. Ideally, the pattern (or ideally, no pattern) will be random scatter of the residual around a horizontal line.
If there is any obvious pattern, it is a good idea to revisit some of the bivariate correlations, or partial regression plot to try to tie the area back to some of the original scatterplots:
- Normal Q-Q: This plot will indicate if the residuals are normally distributed. It is a good sign if the residuals track the straight line.
- Scale location: This plot is used to check for the assumption of equal variances. It is also a good sign if this plot shows if residuals are spread equally along the ranges of predictors. This is how you can check the assumption of equal variance (homoscedasticity). It’s good if you see a horizontal (red) reference line with points randomly equidistant from the line.
- Residuals versus leverage: This plot will help identify which outliers influence the regression estimates. Not all outliers will influence the regression, even if they are far from the regression line. The outliers outside of the dashed lines are the ones which can affect the regression coefficients, and if they are removed from the analysis, your results can change.
When looking at the diagnostic plots, you are only looking at one possible distribution of the residuals. The library TeachingDemos has an interesting interactive function named vis.test which will challenge you to pick out the residuals which were generated from the regression which was run, with an alternate set of randomly generated residuals from the same regression. Remember, the residuals are supposed to be random, so the test essentially randomizes the residuals. If you are able to discern your own residuals from the other residuals that it generates, the residuals fail the test, and the test concludes (with a p-value of course) that your residuals really aren’t random, which will send you back to the modelling drawing board.
To run the test, and play the game, run the following code:
install.packages("TeachingDemos")library(TeachingDemos)set.seed(1)if(interactive()) {vis.test(residuals(PainGLM, type="response"), vt.qqnorm, nrow=4, ncol=4, npage=1)}After the following pattern appears, click on the pattern that you believe matches the normal Q-Q plot in row 1, column 2 previously:

After clicking your answer, the function will test if you matched correctly, and what the probability was. If you keep on getting it wrong, reduce the number of rows and columns until you are able to match the Q-Q plot.
This goodness of fit test will look at subgroups of the predicted probabilities, for example, the probability ranges grouped into 10 (deciles), and measuring whether or not the prediction of the response variable is significantly different from what would be expected by chance.
First the data is group by their predicted probabilities from lowest to highest, and then binned into equally-sized groups.
Then a chi-square test is used to compare the predicted probability of each binned group to their expected probabilities. In a good model, predictions should do better than what is expected for most of the binned groups. If it does not, the groups which are problematic will be indicated in the predicted vs. expected plot, and you will be able to go back and attempt to identify any potential model problems.
In the following example, we will apply the Hosmer-Lemeshow test to the PainGLM dataset. We will implement the Hosmer-Lemeshow test via the hoslem.test() function contained within the ResourceSelection package.
To set up the test, supply the observed values, with the fitted (predicted) values as part of the hoslem.test() function:
install.packages("ResourceSelection")library(ResourceSelection)hoslem.test(PainGLM$y,fitted(PainGLM))The hoslem.test output is written to the console:
Hosmer and Lemeshow goodness of fit (GOF) test
data: PainGLM$y, fitted(PainGLM)X-squared = 8.4981, df = 8, p-value = 0.3864From the p-value statistic (0.38) the test shows that there is no problem with the fit.
The following plot shows that some of the predicted probabilities are better than expected (above the outperforms some of the bins do better than expected, and others do worse, relative to the ideal straight line).
We can see the bins, predicted, and observed values using a cbind() function:
cbind(hoslem$observed,hoslem$expected)The first column shows the defined bins for each of the probability ranges.
Columns 2 and 3 give the observed and expected frequencies for each bin:

In certain cases in which you have a large number of variables, you can end up overfitting the model. This will result in a biased model with some variables having more of an influence on the prediction than is reasonable to expect.
One way to deal with this is to select a subset of the original variables. We demonstrated all subsets regression which only considers a reduced number of variables for a final model. However, in some cases you may want to keep all or most of the variables in your model. For example, if you know via past studies that particular variables should always be included, you would want to keep that in the model, even though it might drop out of contention after a variable selection procedure has been run.
Regularization in regression is a method by which certain coefficients are reduced or even set to 0 in an effort to reduce their influence. While I believe it is always the better course to simplify the model by reducing the model to the most important variables, regularization can also help to reduce multicollinearity, or correlation between the independent variables, along with some other techniques that we have discussed such as principal components.
If you do choose the regularization path, there are many regularization options. Some of the regularization methods are ridge regression, LASSO, or LARS.
To illustrate regularization for our PainGLM data, we will use the ElasticNet regularization algorithm (contained within the glmnet package), which combines several different methods of regularization.
Start by creating some dummy variables using the model.matrix() function which we have used previously. Then, merge in the Duration variable to form a new matrix:
dummy.vars <- model.matrix(df$Pain ~ df$Treatment + df$Gender + df$Age + df$Duration)[,-1]x <- as.matrix(data.frame(df$Duration,dummy.vars))head(x)This is the following output:
df.Treatment.T.B. df.Treatment.T.P. df.Gender.T.M. df.Age df.Duration1 0 1 0 68 12 0 1 1 66 263 0 0 0 71 124 0 0 1 71 175 1 0 0 66 126 0 0 0 64 17Next, run Lasso regularization (alpha=1) on the model, using matrix x as input, and setting.
The Pain as the target variable. Note that the syntax for glmnet is similar to that of the glm function which we used earlier:
install.packages("glmnet")library(glmnet)options(scipen = 999)mod.result<-glmnet(x,y=as.factor(df$Pain),alpha=1,family='binomial')The model output will show the ranges of lambda (the regularization parameter), which will smooth out the effects of the various coefficients to different degrees.
A plot of mod.results will display the size of the coefficients as lambda changes:
plot(mod.result,xvar="lambda")The parameter lambda controls the amount of shrinkage for the coefficients.
Notice that as lambda gets larger, more coefficients will be shrinking towards 0:

If you print some of the results you will see how many non-zero coefficients are included in the model for each lambda, as well as the percent deviation for each model. This will help you select an appropriate lambda for your model:
head(print(mod.result))The table of Lambdas are written to the console:
Df %Dev Lambda[1,] 0 -0.0000000000000004904 0.2357[2,] 1 0.0284499999999999996 0.2148[3,] 1 0.0519700000000000023 0.1957[4,] 2 0.0739900000000000002 0.1783[5,] 2 0.1071000000000000008 0.1625[6,] 2 0.1351999999999999869 0.1480
tail(print(mod.result)) Df %Dev Lambda[56,] 5 0.4019 0.0014130[57,] 5 0.4019 0.0012870[58,] 5 0.4020 0.0011730[59,] 5 0.4020 0.0010690[60,] 5 0.4020 0.0009739[61,] 5 0.4020 0.0008874Using some of the lambda values, you can print out the different coefficients for each model.
This will also help you choose a lambda value that is good for your model:
coef(mod.result,s=0.1957000) # 4 of 5 coefficient are at 0, too much shrinkagecoef(mod.result,s=0.0131800) # only 1 coefficient is set to 0coef(mod.result,s=0.0120100) # All coefficients are includedcoef(mod.result,s=0.01)Using a lambda of.01 will use all of the variables, so let’s print out the coefficients using that value:
> coef(mod.result,s=0.01)7 x 1 sparse Matrix of class "dgCMatrix" 1(Intercept) -17.57297008856023268208df.Duration -0.000962546df.TreatmentB -0.33638216397784859168df.TreatmentP 2.82134076268210698402df.GenderM 1.54779351031200929079df.Age 0.22139548722788335300df.Duration.1 .Comparing the regularized coefficients with the original glm coefficients, you can observe that the magnitude of the coefficients has been reduced. As an exercise, try experimenting with different lambda values and observe how the coefficients change:
Coefficients: Estimate Std. Error z value Pr(>|z|)(Intercept) -20.588282 7.102883 -2.899 0.00375 **TreatmentB -0.526853 0.937025 -0.562 0.57394TreatmentP 3.181690 1.016021 3.132 0.00174 **GenderM 1.832202 0.796206 2.301 0.02138 *Age 0.262093 0.097012 2.702 0.00690 **Duration -0.005859 0.032992 -0.178 0.85905In this chapter, we started with a discussion of supervised and unsupervised learning and emphasized the difference between pure predictive and exploratory analytics. We were then introduced to the first of the core algorithms (general linear models) which are important in the predictive analytics world. We then discussed various regression methods, along with its pros and cons, and noted that regression can be an extremely flexible and well researched statistical based modeling tool. We then used a pain threshold study to show examples of logistic regression and regularized regression, along with discussing important regressions concepts such as interaction, p-values and effect sizes.
In the next chapter, we will resume our discussion of the core predictive analytics algorithms by discussing three additional algorithms, that is, decision trees, clustering, and support vector machines.