Introduction to Decision trees, Clustering, and SVM
local graph
Chapter 5 — Introduction to Decision trees, Clustering, and SVM
Section titled “Chapter 5 — Introduction to Decision trees, Clustering, and SVM”“My interest is in the future because I am going to spend the rest of my life thereâ€
– Charles F. Kettering.
Decision trees are considered a good predictive model to start with, and have many advantages. Interpretability, variable selection, variable interaction, and the flexibility to choose the level of complexity for a decision tree all come into play.
Decision trees methods are considered classification methods, so the typical use case for a decision tree is predicting a class or category. However, there are also certain types of decision trees, which are known as regression trees, where the output is a continuous variable. In this way, we can begin development models that are a mix of numeric and categorical variables.
Decision trees are heavily used in marketing and advertising, and in any industry where there is a need to segment customers into different groups. They are also used in healthcare for disease and risk classification.
Decision trees have many advantages. They can be easily understood by both technical and business people and can be presented in an extremely simplified or detailed way.
They can be specifically tailored to the type of audience, depending upon the inclusion/exclusion of domain-specific variables and the level of complexity. They are most useful when there are a small to medium number of variables that are generally understood, and the goal is to learn about the interactions between them. Decision trees are also good vehicles for storytelling since the natural presentation of a tree, and its splitting mechanism, corresponds well with business rule decision making and each specific node can be examined and questioned if need be.
Decision trees can handle both categorical and number variables, and deal with missing values. There is no need to discard or impute them.
Most decision trees utilize what are known as greedy algorithms. There are many definitions of what greedy means, but I like the one that suggests that it always makes the optimal choice based upon whatever information happens to be available at that moment. There is no hindsight that is used when building trees. Slight changes in data can alter results, and if you run the algorithm on a subsequent sample, the results may not replicate in exactly the same way. It is also difficult to force the tree to split the way you want it to when running in an automated fashion. If you want to control splits exactly, you may be better off using interactive decision trees in which you are able to split a node by pointing and clicking. Unfortunately there are not a lot of open source options for this.
Additionally, there is a built-in bias in decision tree algorithms in that they favor variables with a large number of categories. This enables the algorithm to be able to split over a large category, even when the result would not make any sense (we will see this in an example). Large trees can produce invalid or silly results, especially when the size of the tree is very large. Over-fitting is common, but there is a technique known as pruning which can be used to reduce this. Random forest trees can help with these disadvantages somewhat, since not all variables are included in every tree, and it uses consensus building to generate a result.
Despite these disadvantages of decision trees, I advocate their use as more of an exploratory tool (unsupervised learning), and you will find that they are very good at uncovering many important relationships that exist in your data when the analysis is performed in an organized and methodical method. It is also a good way to validate results obtained from other types of models. If you find that other models obtain much better results that you cannot replicate visually in a decision tree model, chances are good that the results from the more complex model will not replicate in the future.
Decision trees algorithm are analogous to the game of 20 questions, or animal, vegetable, mineral. A basic decision tree algorithm will start at the root of the tree, representing all of the data, and continue to break each category into two separate categories that are based upon optimal methods, to be able to guess the best characteristics to identify each of the two categories. This is known as splitting a node. Then the algorithm will continue to split the data until it either cannot split any more, or stops in other ways based upon the control parameters.
For example, if we want to classify gender based upon the presence of osteoporosis, ischemic heart disease, and the average number of prescriptions, we could develop a tree that looked something like this:

Notice that the first question is “Does the patient have Osteopororis?”. Then based upon the answer, another series of question are asked which will ultimately place a patient into a final node of the tree, in which no more questions can be asked which will improve the results.
Our original node always starts at the root of the tree. In the preceding diagram, the first node merely starts with a description of how the population breaks down by gender. In this case, females make up the majority class at 58% of the population. The goal in decision of tree algorithms is to always grow a tree and improve predictions. So, at this point, we want to do better than 58% prediction for gender.
As we grow the tree, two questions will always need to be taken into consideration:
- Which variable will best improve the prediction for each of the classes of the target variable at that point?
- For that variable, what is the best split point that will segment a categorical variable into two parts, or divide a continuous variable into two parts, and will improve the prediction for that class?
The outcome of this decision will be a new tree node, or leaf. In a classical decision tree, there are typically two paths (yes or no, high or low) that are followed, but there can be more than two paths depending upon the algorithm.
In our preceding example, the algorithm will first run through all of the variables and determine which one will improve the prediction. That variable happens to be the presence of osteoporosis. If osteoporosis is present, one could predict that the patient is female with 74% accuracy. However, when osteoporosis is not present, the probability of being female actually decreases to 51%, which is slightly worse than the original 58% representation of females in the study.
But wait. The partitioning algorithm will continue to try to split the data again. This time it looks at the average prescriptions variable as a way to improve the prediction. The average number of prescriptions per year per beneficiary for this analysis runs from about 15 per year to about 200. The algorithm will try all values in this range to split the data into two parts. For example, it might try to first compare patients with 10 or more prescriptions, with those with 9 or less prescriptions. It will then look at the prediction for that cutoff. Then it will continue to change to cutoff value until it finds the cutoff value which optimizes the separation between the two classes.
In this instance, it has found that 51 prescriptions is the cutoff that optimizes the split for those patients without osteoporosis. When the number of prescriptions is greater than 50, there is a 64% probabiltity that the patient is male.
One a node is split according to the best criteria, the resulting nodes are examined for impurity. Impurity measures the separation of the classes, based upon what the expected frequencies should be at that point. The most impure case is when a node is split 50/50 for a binary class. This essentially designates a random class assignment. The least impure case is when a decision rule places all the observations completely in one class, and 0 observations are placed in the other class. This is the more desirable case, since it allows us to make a perfect prediction for that node.
Once an impurity measure is calculated, the algorithm will compute an information gain measure, which calculates how much the impurity decreases by splitting each of the variables, and proceeds to calculate all possible split points for a continuous variable.
One characteristic of the cart (implemented as rpart in R) is that it will try all possible variables and split points until it finds the best one to use. Depending upon how the algorithm is configured, it can be, the one that achieves the highest information gain. However, in a real-world setting, very few trees are grown with unlimited boundaries. Trees are grown with constraints. Examples of constraints would be specifying the maximum number of branches that can be grown, or the minimum number of observations contained within a leaf. As a result, the predictive modeler can construct a tree to be as simple or as complex as needed.
In R, two types of decision tree algorithms are illustrated. We will first look at the traditional algorithm, known as rpart and we will analyze the state.x77 data to determine life expectancy, based upon a number of attributes.
Here is a description of the metadata for the state.x77 data. You can also get more information able this table by entering ?x77.data at the R console.
| Population | Population estimate as of July 1, 1975 |
|---|---|
| Income | Per capita income (1974) |
| Illiteracy | Illiteracy (1970, percent of population) |
| Life experience | Life expectancy in years (1969-71) |
| Murder | Murder and non-negligent manslaughter rate per 100,000 population (1976) |
| HS graduate | Percentage high-school graduates (1970) |
| Frost | Mean number of days with minimum temperature below freezing (1931-1960) in capital or large city |
| Area | Land area in square miles |
First, we will concatenate this data with two other reference datasets. Use the R help system to obtain more information about the adjunct tables as well:
- state.abb: To obtain the state abbreviation
- state.region: To obtain the state”s geographical region
statedf <- as.data.frame(state.x77)x <- data.frame(statedf,state.abb,state.region)summary(x)The output from the summary() function appears in the console:

A quick histogram of the target variable, Life.Exp, shows a considerable amount of variation. Therefore, it can be considered a good potential target variable.
hist(x$Life.Exp)
We have already seen how to specify regression models in R using formula notation. For example, we use lm(womenweight)) to predict height based upon weight.
The general form of formula notation in regression models is:
Dependent variable ~ Independent variables
Where the dependent variable is on the left side of the tilde (~), and the independent variables are on the right side of the tilde.
An rpart model can be set up using formula notation as well, with a slight change in terminology. In an rpart model, we can specify the target variable (Life.Exp) on the left side of the tilde (~), and the predictor variables on the right side of the tilde. We will use dot notation (.) to designate that we will be considering all variables.
Dot notation is a convenient way to specify all your variables; however, as you build out your model, you may want to avoid using this, and instead specify the specific list of the variables that you are interested in. This will speed up processing, and will avoid unnecessary splits.
In the following example, you can see that rpart will select state as the best initial split variable. While this may ultimately grow a very accurate tree, in terms of prediction ability, splitting initially on a high dimensional variable such as state does not offer great insight into what causes variation in life expectancy. There is always the possibility that the states will be broken out into geographic areas. But often you will obtain a split of states that do not make any sense.
In the following example we will use the rpart() function to generate a simple decision tree. We will also use the prp() function from the package rpart.plot to visualize the tree:
install.packages("rpart")install.packages("rattle")install.packages("rpart.plot")install.packages("RColorBrewer")
library(rpart)library(rattle)library(rpart.plot)library(RColorBrewer)set.seed(1020)y1 <- rpart(Life.Exp ~ .,data=x,cp=.01)prp(y1, type=4, extra=1)In the following plot, the splitting of the nodes is purely based upon state, with no insights on how the states were grouped. Notice that state.region does not factor at all in the splitting algorithm, so it would be a good guess that much of the splitting is purely mechanical and visually, no obvious grouping is reflected in many of the splits:

*
> print(y1)This print() function sends this output to the console:
n= 50
node), split, n, deviance, yval * denotes terminal node
1) root 50 88.2990000 70.878602) state.abb=AK,AL,AR,AZ,DE,FL,GA,IL,IN,KY,LA,MD,ME,MI,MO,MS,MT,NC,NJ,NM,NV,NY,OH,PA,SC,TN,TX,VA,WV,WY 30 21.0890000 69.980004) state.abb=AK,AL,GA,LA,MS,NC,NV,SC,WV 9 2.2790220 68.82556 *5) state.abb=AR,AZ,DE,FL,IL,IN,KY,MD,ME,MI,MO,MT,NJ,NM,NY,OH,PA,TN,TX,VA,WY 21 1.6747240 70.4747610) state.abb=DE,IL,KY,MD,ME,NM,PA,TN,VA,WY 10 0.1656400 70.21400 *11) state.abb=AR,AZ,FL,IN,MI,MO,MT,NJ,NY,OH,TX 11 0.2109636 70.71182 *3) state.abb=CA,CO,CT,HI,IA,ID,KS,MA,MN,ND,NE,NH,OK,OR,RI,SD,UT,VT,WA,WI 20 6.6488550 72.226506) state.abb=CA,CO,ID,MA,NH,OK,OR,RI,SD,VT,WA 11 0.7760909 71.78091 *7) state.abb=CT,HI,IA,KS,MN,ND,NE,UT,WI 9 1.0192890 72.77111 *If we remove state from the model, we will start off with a much more understandable model. After prp() function has plotted the result, you can see that the left branches of the tree are based purely on the high murder rate. The two terminal loads for this branch indicate that the life expectance for an area with murder rate >= 11% is one year less than with a murder rate < 11%.
The right branches of the tree concentrate on lower murder rates. For these branches, region is considered. The North and Southern regions have a 1 year. lower life expectancy than the West or North Central regions:
y2 <- rpart(Life.Exp ~ Population + Income + Illiteracy + Murder + HS.Grad + Frost + Area + state.region,method='anova',data=x)
prp(y2, type=4, extra=1)
The ctree function gives some advantages over rpart in that the results produced can be a bit more intuitive. Rather than optimizing a result node based purely upon the purity of the resultant node, ctree uses statistical hypothesis testing to determine if the results of the split are statistically significant. It uses chi-square test statistics to test the association, only keeping the associations that are significant, and thus removing bias due to a large number of categories. So, while accuracy may suffer in some cases, benefit is gained by having the results be more explanatory:
install.packages("partykit")library(partykit)y2 <- ctree(Life.Exp ~ .,data=x)y2plot(y2)As you can see from the following plot, ctree and rpart both agree on the first split (murder), and the cutoff points are very similar. This can add additional credence to the first split since the split is corroborated by two different algorithms:

Pruning is another way to defend against overfitting. If you visually examine a tree and find that you want to stop the growth of branches at a particular point, you can prune all branches below that node, so that all of the results under that node are collapsed into a single node. That may give you more interpretable results for the decision rules displayed at that point.
The rpart has a unique interactive pruning feature using the prp() function which can help you do this.
In the previous states example, you might want to rid yourself of all of the nodes below node 70 in order to balance the tree and keep it at two levels deep. Balanced trees can also be considered a desirable feature:
PrunedTree <- prp(y1,type=4, extra=1,snip=TRUE)$objClick on node 70 and observe the delete node 5 message in the console. After you see that message, click Quit in the plot:
> PrunedTree <- prp(y1,type=4, extra=1,snip=TRUE)$objClick to snip ...Delete node 5 state.ab = DE,IL,KY,MD,ME,NM,PA,TN,VA,WY var n wt dev yval complexity ncompete nsurrogate5 state.abb 21 21 1.7 70 0.015 4 5Display the results of the tree and note the nodes have been eliminated:
prp(PrunedTree, type=4, extra=1)
These are the important control parameters that are used by rpart to grow a tree. You can often play with these values to get a tree to render in a reasonable form, and to control its complexity:
- cp parameters: The cp (complexity parameter) is an option used in rpart that controls how liberal you want the splitting algorithm to be when it decides whether or not to split a node. Utilizing a small cp value (< 0.01) can generate an enormous tree that can contain unexplainable splits, while a tree with a high cp value (> 0.05) can produce a tree containing only obvious information. Therefore, it is important to set the cp level at a number that generates a fair amount of nodes, yet remains explainable.
- Maximum depth: If you want the number of levels of the tree to stop at a certain level, specify this number as an option within the function call. Some people will stop a decision tree after 10 levels or so, assuming that there will be no interpretable information beyond that point. However, if you suspect that there may be single nodes that pop up that could contain the information you are looking for, by all means continue to grow the tree. However, remember as you extend the number of levels, that will increase the computation time and memory needed. It is always a good idea to see limits on the growth of the tree, even if it is a high number.
- Minbucket: Many analysts like to concentrate on terminal nodes. However, a terminal node needs to be a minimum size for it to have statistical meaning. The only exception would be if you were looking for true outliers or anomalies. But generally, for segmentation, we want groups that are large enough to have meaning.
- Minsplit: This option controls how many observations a node has to have in order to even be considered for a split.
Cluster analysis has many uses. At its very basic level, a cluster is a group of people or objects that share similar characteristics. In the marketing and sales industries, clustering is important, since customers (or potential customers) can be grouped by characteristics such as average spending, frequency of purchase, and recency of purchases, and assigned a cluster that represents one single measure of the different levels contained in all of the attributes that make up that cluster. So, for our RFM example, cluster A might represent frequent purchasers who spend a lot of money, and spend often (every marketers dream). Cluster B could represent people who are just average consumers across all three of those RFM metrics, and there might even be a cluster Z which represents things that seem to be impossible, such as customers who buy Halloween costumes only on Tuesdays.
Data analysts can often get good results by using tools such as SQL, or by having great insights in customers behavior. So, while cluster analysis is not necessarily an end in itself, clustering algorithms allow you to cut to the chase rather quickly and enable you to begin to look at groupings in different ways.
Clustering is often related to other terms that you may hear in different industries:
- In marketing and sales, you will hear the term product segmentation, which refers to how we cluster people according to their product preferences along various dimensions. It can also refer to a customer’s willingness to buy a product with the ultimate goal of being able to cluster customers into those two groups (willing and not willing) and only marketing to those customers who we predict are willing to buy.
- An insurance company might cluster customers according to how often they file a claim, or cluster customers according to a certain risk profile.
A cluster can be defined as a group of objects with similar characteristics. Clusters can vary in size. There is no requirement that a cluster must have a certain number of members. It can even have a single member. This might be useful in fraud applications, in which you want to identify anomalies in the data. In this case, very small clusters can act as outliers.
Clusters are often constructed to have an equal number of members in each group, as in partitioning clustering. In this case, all of the members in each cluster are homogeneous within each cluster group.
Furthermore, clusters are constructed so they have distinct differences from the remaining clusters. Differences are usually calculated based upon measurements between each of the clusters centroids, which is the middle of each cluster, and the centroid of each cluster can be thought of as the average representative values of the attributes for the cluster that it represents.
Clustering is usually done on numeric variables only. That is because clustering utilizes distance measures, and as we have seen, categorical variables have no measure between them. However, there are ways to incorporate similarity using categorical variables, which we will see later on.
There are two types of clustering that are often utilized, partional clustering and hierarchical clustering:
This is also known as non-hierarchical clustering. In partitional clustering, each object is divided into smaller non-overlapping subsets (partition) that have similar characteristics. An observation can belong to one, and only one, cluster.
Here is a classic example of a three-cluster partitioned model. However, you may wonder why some of the yellow observations end up in the yellow group cluster, rather than the red group. That is because k-means has determined what the linear boundaries are for each of the clusters (right diagram), and any point that falls within any particular decision boundary is defined by the boundaries of that cluster:

K-means clustering is the most popular algorithm used for partition clustering. In k-means clustering, similarity between clusters is based, in part, upon distance measures. Generally, the goal is to group similar clusters together with each observation having a relatively small distance from other observations in the same clusters. On the other hand, another goal is to have the maximum distance from one cluster to the next, so that the distances can be discerned. It is essentially a balancing act in which there is a tradeoff between defining similarities within groups, and defining opposing dissimilarities between groups.
The k-means algorithm is based upon an iterative process.
First, we decide how many clusters we desire. The number of clusters can be determined by a number of methods, but bear in mind that there is really no correct number of clusters. Typically, between 3 and 20 clusters can be used as a range.
As an initial step, cluster members are randomly assigned to one of the three clusters that have been specified. In the following example, we have 12 observations (in gray), and three centroids (solid colors) which have been randomly generated. For this example lets make believe we have only two variables, lets say there were age, and height. We will represent them on an x and y axis but we wont label them:

The next step is to assign each observation to the nearest cluster. The nearness of each cluster will be discussed in the next section, but for now let’s say that each of the observations have been assigned to each of the three clusters randomly as shown below. The solid lines define the boundaries of the cluster. Visually you can see that that some adjustment could help the random assignment. For example, would the green observation at the border between the red and green cluster border could be a better fit if it was assigned to the red (top) cluster? That could be true since it looks like it could be closer to the cluster at the top than the one it was randomly assigned to:

After the random assignment, the cluster assignment are recalibrated. What that means is that the centroids of each cluster are recomputed (we will see how that is done later), and then each data point is then moved to the new closest centroid. This movement is demonstrated in the following figure showing the centroids being shifted:

This process is repeated. Centroids are recalculated, and the data points move again to their nearest centroid until there can be no additional improvement. When done the final centroids are computed, the clusters are finalized as in the diagram below. You can see that the observations are clustered slightly better than the original random assignment. Note that the data point in each cluster tend to be closer together than the original random assignment, and that there is more separation between at least two of the clusters (the one on the left, and the other in the middle):

K-means clustering uses Euclidian distances to determine how far apart each of the clusters are from each other. For clusters of just one variable, the computation is trivial. You just take the centroids from any two clusters and subtract them from one another. As you add more variables, the computation becomes slightly more involved since you will be summing the squared difference between all of the variables that comprise each of the clusters, and summing them all together to determine the total distance.
Here is an example of how the centroid is determined for three cluster members that have been assigned to cluster 1. Centroid 1 has been calculated, the vector [186,45] where 186 is the average of the weight of the three members, 1, 2, and 3, and 45 is the average age of members 1, 2, and 3. These will not be the final cluster assignments, but merely a best guess at this point:
| Member | Weight | Age |
|---|---|---|
| 1 | 146 | 25 |
| 2 | 175 | 43 |
| 3 | 236 | 68 |
| Centroid 1 | 186 | 45 |
The next step is to get a better estimate for each cluster assignment. Each member’s dimensions are then compared to the centroids of all of the clusters, and then reassigned to the cluster to which it is the closest. This is done using the concept of Euclidean distances.
The formula for Euclidean distance is as follows:

For a cluster that contains only two variables, this is equivalent to:

In our age and weight example previously defined, the Euclidean distances have been computed for member 1 between cluster 1 (the first cluster assignment that it is currently a member of), and an alternative cluster 2. The distance is calculated using the preceding formula, and the results of the final sum of squares is listed in the final column. As you can see, cluster 2 is computed as being closer to member 1, since the distance is smaller, and as a result, member 1 is moved into cluster 2:

After the distances have been computed for all members, and each member has been moved into its closest cluster, the centroids for each cluster will change, since members will have been added or removed. So, the process is repeated until no more members can be moved into more suitable clusters.
This example will illustrate a simple RFM clustering example. RFM analysis is simple database marketing that can be used to segment out your best (and worst) customers. It is a good example to use for demonstrating cluster analysis since there are only three variables, and can be segmented, theoretically, into a much larger number of marketing segments.
The data comes from the CDNOW database, which contains the entire purchase history up to the end of June 1998 of the cohort of 23,570 individuals who made their first-ever purchase at CDNOW in the first quarter of 1997 (Fader, 2001).
Here are three variables that we will be using:
- Date of purchase: This is the date that the item was purchased and will be used to determine the recency part of the RFM analysis.
- Units bought: This corresponds to the number of items purchased in the cart, and roughly corresponds to the frequency of the customer.
- Total paid: This is the total amount of the purchase. This reflects the monetary portion of the RFM.
As a first step, we will read on the data, transform the dates to date values, and then compute the number of days since purchase.
Then we will assign column names to the variables:
library(graphics)library(dplyr)x <- read.table("C:/PracticalPredictiveAnalytics/Data/CDNOW_master.txt", quote="\", stringsAsFactors=FALSE)Next we will transform the purchase date to date format, and calculate how long it has been since that purchase. Use July 1, 1998 as the reference date:
x$xd <- as.Date(as.character(x$V2), "%Y%m%d")x$diffdate <- as.integer(as.Date("1998-07-01") - x$xd)#rename the columns
colnames(x) <- c("id","orig.date","units.bought","TotalPaid","purch.date","Days.since")str(x)summary(x)We will illustrate the k-means function to perform k-means clustering on the variables units.bought, TotalPaid, and Days.since. One characteristic of k-means clustering is that each observation can be categorized into one and only one cluster. K-means requires all variables to be numeric, you cannot use categorical variables in the kmeans function.
One decision you will need to make is how many clusters you would like kmeans to produce. I usually like to aim for between 5 and 15 clusters. Anything more than that will make it difficult to explain the meaning behind each individual cluster, but you can certainly do that. One problem with increasing the number of clusters is that the k-means algorithm specifies approximately equal size clusters, so as you increase the number of clusters, some of the outlier clusters will have a smaller number of members.
The output from k-means will give you a general idea of the goodness of fit of your clusters. The within cluster sum of squares indicates the separation of the individual data points within each cluster. Smaller numbers show the cluster is more homogeneous. The ratio betweenss / totss is a single metric that you can use as a measure of how all of the clusters are separated as a group. A higher number indicates a better separation of clusters.
For this example, we will generate clusters of size 3, 5, and 7:
attach(x)#cluster on the RFM variablesy <- subset(x, select = c(units.bought,TotalPaid,Days.since))
#perform kmeans producing 3 and 5 clustersK-means relies on a random seed in order to initially populate a pseudo-random cluster assignment. Changing the seed may change your results. Since clustering involves some degree of human interpretation, it is common to run the algorithm several times using different seeds, and observe how well they conform (or not) with each other.
#always set seed before clustering
set.seed(1020)clust3 <- kmeans( y,3)clust3$betweenss/clust3$totssclust5 <- kmeans( y,5)clust5$betweenss/clust5$totssclust7 <- kmeans( y,7)clust7$betweenss/clust7$totssAfter creating the three clusters, print the ratio of the cluster between sum of squares to the cluster total sum of squares. That will give you a starting metric to begin comparing clusters. A higher number implies better separation between the clusters:

So, based on the output above, cluster 7 has the highest betweenss / totss ratio, and having seven clusters would be considered the optimal number of clusters. But, if you run the analysis, increasing the number of clusters each time, you will always see an increase in the ratio. So, we need to determine where the law of diminishing returns kicks in.
One way to determine this is by using an automated method known as the elbow method in which you plot the total within clusters sum of squares for all values within a range, and look at where an elbow method develops in the plot:
#elbow methodset.seed(1020)## Compute and plot wss for k = 3 to k = 15
df <- sapply(3:15,function(k){kmeans(y,k)$tot.withinss})
plot(3:15, df,type='b',xlab="# of clusters",ylab="Total Within Clusters SS")In the following plot, you might see two elbows, one at 5-6 cluster, and one at 8-9. We will assume for now that five is the optimal number, only because there is an elbow in that area, and the names given to the clusters will be easier to explain:

Let’s extract the cluster assignments from the clust objects, and then compare the counts for each cluster with clusters of size 3, 4, and 7:
#cluster assignmentsclusters3 <- clust3$clusterclusters5 <- clust5$clusterclusters7 <- clust7$clusterWe can plot the clusters in many different ways. The first thing you would want to look at would be histograms of the cluster segments. Remember, k-means likes to see approximately equal clusters:
#usually but now always the middle cluster is the average clusterpar(mfrow=c(1,3))hist(clusters3)hist(clusters5)hist(clusters7)
We can also plot the assigned clusters with the original data, to see if there are any problems with cluster assignment.
First, we need to append the cluster assignment to the original dataset:
#append the clusters the original dataappend.clust <- data.frame(x, clusters3,clusters5,clusters7)For illustration purposes, let’s sample from the append.clust dataset. We will set the sample size to 100, but you can set it to any number that makes the diagram readable:
library(cluster)set.seed(1020)sampleit <- append.clust[sample(nrow(append.clust), 100), ]We will use the clusplot package from the cluster library to plot the cluster assignments based upon the first two principal components. If you recall, principal components are a way to reduce the number of variables in this exercise to two, mainly so that we can graph it on a two-dimensional x and y axis.
If you run the following command, you will see that the first component is a measure of the price and number of units bought, and the second component is a measure of time since the last purchase. That is what is represented on the x and y axis. This is trivial for this case since the cluster model only has three variables as input, but becomes more important as the number of variables you use increases:
prcomp(append.clust[,c(3,4,6)], scale = TRUE)
par(mfrow=c(1,3))clusplot(sampleit[,c(3,4,6)], sampleit$clusters3, color=TRUE, shade=TRUE,labels=2, lines=0)clusplot(sampleit[,c(3,4,6)], sampleit$clusters5, color=TRUE, shade=TRUE,labels=2, lines=0)clusplot(sampleit[,c(3,4,6)], sampleit$clusters7, color=TRUE, shade=TRUE,labels=2, lines=0)
Based on the preceding plots, I would eliminate clusters7, since the third centroid seems to have a small count.p.
Let’s look at the makeup of each of the clusters and see how they relate to the original variables.
Look at the output from the head() function. Notice that each row contains three different cluster assignments. Let’s look at the means and counts of the original variables grouped by each of the cluster assignments:
head(append.clust)
We will use dplyr to get the average values and counts for each cluster:
library(dplyr)attach(append.clust)append.clust %>% select(units.bought,TotalPaid,Days.since,clusters3) %>% group_by(clusters3) %>% summarise_each(funs(n(),mean))append.clust %>% select(units.bought,TotalPaid,Days.since,clusters5) %>% group_by(clusters5) %>% summarise_each(funs(n(),mean))append.clust %>% select(units.bought,TotalPaid,Days.since,clusters7) %>% group_by(clusters7) %>% summarise_each(funs(n(),mean))In the following output, the display shows the total counts and the averages for the number of units purchased, total amount paid, and days since last purchased. Each line lists the specific statistics relevant to the specific cluster assigned, and there are three sets of statistics, one each for clusters of 3, 5, and 7:

We can explain the clusters in terms of the original variables:
For the three-cluster assignment:
- Cluster 1 has the lowest average number of units bought, as well as the lowest TotalPaid amount of all of the three clusters. It also has customers who purchased items a long time ago, relative to the other customers.
- Cluster 2 is categorized by customers who have purchased recently, since they have the lowest Day.since mean statistic.
- Cluster 3 is categorized by those customers who purchase a relatively high number of units, and have a higher total invoice, but are not necessarily recent buyers.
Based upon these cluster definitions, a marketing department can customize different offerings for each customer group.
As an alternative to k-means, you can perform hierarchical clustering, which does not require you to specify the number of clusters beforehand. In hierarchical clustering, you can either start with one cluster and then continue to subdivide two clusters at a time, or start with every record being in its own cluster, and then merge them together to become a larger cluster. In any case, it is easy to scan up and down the tree, known as a dendrogram, and identify the grouping of clusters that suit your needs, rather than having to run the clustering one at a time. However, for large computational processing, partitioning clustering (k-means) definitely has a performance edge, which is why it is favored in industry.
We will use the hclust R function with the Pain dataframe to demonstrate hierarchical clustering. After reading in the data, we will scale or normalize the data by centering the mean to 0. The reason we do this is that we do not want the clustering procedure to favor any variable over another, by nature of its size or variance, so we try to equalize the magnitude as best we can.
First, we will load the pain_raw data we saved earlier into a dataframe object:
require(graphics)setwd("C:/PracticalPredictiveAnalytics/Data")load("pain_raw.Rda")
df2 <- subset(df, select=c(Age,Duration,Pain))df2 <- scale(df2)head(df2)Next, we will compute a distance matrix, and run the hierarchical clustering algorithm using the average linkage method:
fit <- hclust(dist(df2), "average")Before plotting the dendrogram, we will specify that we want to show a red border around the three groups of clusters that are the most similar:
groups <- cutree(fit, k=3)rect.hclust(fit, k=3, border=""red"")The dendrogram is plotted and it should look similar to the following plot. Observation numbers are shown at the ends of the vertical lines, so it will be easy to subset the original dataframe and inspect the data:

From the bottom of the dendrogram, we can see some of the observations associated with cluster1. Extract them from the original dataframe (df):
cluster1 <- df[c(35,52,10,30),]Examine the output using the View command. The output shows that cluster1 may be associated with males in their 70s, who are reporting pain with a duration between 21 and 29 days:
View(cluster1)
Similarly, pull some observations from cluster 2, and view them:
cluster2 <- df[c(23,49,25,47),]View(cluster2)This cluster looks like it could be related to those who were administered treatments A and B, who reported no pain, within the age range of 59-72:

Extract and view some examples from cluster3:
cluster3 <- df[c(20,26,38,53),]View(cluster3)Cluster 3 could be patients who reported no pain. However, they are characterized by a much shorter duration than cluster2:

Note that in the preceding examples we only pulled four observations from each cluster. However, you need not pull only four of them. Pull as many as necessary, and try to give it a name that categorizes the clusters characteristics.
We have already seen some examples in which we use a straight line to separate classes.
As the dimensionality, or feature space, of a model increases, there may be many different ways to separate classes, in both linear and non-linear ways.
In the cases of support vector machines, data is first transformed into a higher dimensional space using a mapping function known as a kernel, and an optimal hyperplane is used to segment the higher dimensional space. A hyperplane uses one dimension less than the space it is trying to measure, so a straight line is used to segment a two-dimensional space, and a 2-dimensional sheet of paper is used to segment a three-dimensional space. The hyperplane can be either linear or non-linear.
Hyperplanes use support vectors which are important training tuples and are used to define the boundaries of each class. They are the most critical points in the data, and they are the most important points used which support the definition of the hyperplane. The hyperplane is used do define the boundaries beween the different classes. A class is often a binary class, such as 0 or 1. The boundaries between the classes can also be wide or thin. That characteristic is measured by the margins which define a maximum separation that can be optimized between the classes.
Here is an example of a dataset with two features, x and y. The lines A and B could be considered as two separate linear classifiers for a decision rule that separates the red observations from the blue observations. The A line is preferable, since it contains a larger margin, separation value between the decision line and the nearest observation. The observations that are close to the line are known as the support vectors:

To illustrate how a kernel mapping function can help in defining a linear boundary, look at the following plots and see how creating a new variable z will help differentiate among the new transformed points that are mapped by the polynomial function t2High.Low.Temp^2 in two-dimensional space. However, a kernel mapping will take place in a higher dimension, and the results of the mapping reverse mapped back into the original space:
#generate a non-linear circle of point
radius <- 2t2 <- data.frame(x=radius * cos(seq(0,6,length = 20)),y = radius * sin(seq(0, 6, length = 20)))names(t2) <- c("Latitude","High.Low.Temp")plot(t2$Latitude,t2$High.Low.Temp)
# create a new variable and plot it against on the original pointst2$z = (t2$Latitude^2*t2$High.Low.Temp^2)
plot(t2$High.Low.Temp,t2$z)
Typically, SVMs are used with data that is very high dimensional. That could include applications involving object and facial recognition. SVM can be very accurate, but its disadvantage includes interpretability and performance. SVMs can also overfit the data, since the decision boundaries are highly dependent upon the choice of the kernel that is used to perform the mapping. There are a large number of kernel choices available and the choice of a kernel should not be made based upon the best model fit. This would not be unlike using higher order polynomial functions to overfit a regression model.
In this example, we will use a text classification model to define a linear SVM model. Unstructured text data is a perfect way to illustrate SVM since the data is very high dimensional.
To illustrate SVM classifiers, we will begin by reading in some consumer complaint data regarding student loans. We will be using two packages, e1071 and RTextTools:
install.packages("e1071")install.packages("RTextTools")library(e1071)library(RTextTools)Begin by loading the data from the CSV file. The data frame simply consists of some consumer narrative regarding student loans, along with how the complaint was classified. The goal is to develop a SVM model which will classify future customer complaints into the various issue categories:
data <- read.csv("C:\\PracticalPredictiveAnalytics\\Data\\Consumer_Complaints.csv", sep=",")str(data)Subset the data and keep only the columns we will need:
data <- subset(data,l select=c(Issue,Consumer.complaint.narrative))Take a sample of the first 50 records and view:
data.samp <- subset(data[1:50,], select=c(Issue,Consumer.complaint.narrative))View(data.samp)
Notice that complaint data is in unstructured format. Certain text mining algorithms treat unstructured text as a bag of words, which means that in analyzing documents, one disregards semantics and grammar, and ends up treating each word as its own feature or variable.
An important data structure in text mining is a term document matrix (TDM), which simply indicates which words appear in each document.
The create_matrix() function will do this for us. However, before we do this, we will want to clean the data and impose some restrictions on the creation of the term document matrix.
First, we do not want to include any words, such as the, an, or it, that would not add any value to the TDM and would force it to be quite large. These are known as stopwords. So, we will filter these words using the option removeStopwords=TRUE. Similarly, we will also eliminate any numbers and punctuation, and only consider words that have a minimum length of four. These options are not arbitrary. It is up to the text miner to set these options at the optimal value, tempering the need to capture the most value from the data, while keeping the size of the data at a minimum. Knowledge of the domain is extremely helpful when setting these options. For example, had I set minwordLength=5, I would have not included words such as Paid:
# Create the document term matrixdtMatrix <-create_matrix(data.samp[""Consumer.complaint.narrative""],minDocFreq = 1, removeNumbers=TRUE, minWordLength=4,removeStopwords=TRUE,removePunctuation=TRUE,stemWords = FALSE)The TDM is a data structure that is optimized for text mining. It can be difficult to view as the number of documents and words increase. However, in our example, we only have 50 documents, and since we have started by taking a sample of the data, only have a limited number of words, so we can view a small TDM using the transpose() function:
xx = as.data.frame( t(as.matrix( dtMatrix )) )head(xx)Notice that even in this small sample, we can see the document contains several references to access, able, and ability. The column indicates the documents that the word occurs in, along with the number of references. There is a column for every document, even though any particular word (listed as rows) do not appear in the document:

Now that we have viewed a TDM for a sample, let”s run it for the entire dataframe.
dtMatrix <- create_matrix(data[""Consumer.complaint.narrative""],minDocFreq = 1, removeNumbers=TRUE, minWordLength=4,removeStopwords=TRUE,removePunctuation=TRUE,stemWords = FALSE)Instead of viewing the TDM (which in this case would be quite large), let’s perform a frequency on the terms, by adding up the number of times that they occurred. By scrolling through the dataframe, you will get a very good idea of the single terms that are popping up. You would also want to compute these terms in combination (bi-grams, and N-grams), which would give you insight into the kinds of things that the customers are complaining about:
freq <- colSums(as.matrix(dtMatrix))length(freq)head(freq)freq.df <- as.data.frame(freq)View(freq.df)The output of the View command will display the following terms in the TDM, in alphabetical order. Use the elevator bars to scroll through the list:

The RTextTools package uses containers to hold different kinds of R objects. We will create a container that will be used as a holding object to train the first 500 customer comments:
container <- create_container(dtMatrix, data$Issue, trainSize=1:500,virgin=FALSE)str(container)Once the container is created, we can use it to train many different kinds of models. We will be using an SVM with a linear kernel.
That means that we will be using linear hyperplanes to separate the data into segments within the high dimensional text space:
# train a SVM Modelmodel <- train_model(container, ""SVM"", kernel=""linear"", cost=1)str(model)head(model)summary(model)The output from the summary model appears as follows; 349 support vectors where created, which were used to separate the data into three classes:
Call:svm.default(x = container@training_matrix, y = container@training_codes, kernel = kernel, cost = cost, cross = cross, probability = TRUE, method = method)
Parameters: SVM-Type: C-classification SVM-Kernel: linear cost: 1 gamma: 9.832842e-05
Number of Support Vectors: 349
( 189 143 17 )
Number of Classes: 3
Levels: Can''t repay my loan Dealing with my lender or servicer Getting a loanNow that the data has been trained, we will take the next 500 observations to do the testing, and see how the model performs. Similar to what we did for training, we will create a TDM for the test data, but use the same labels, or terms that we created for the training data:
predictionData <- data$Consumer.complaint.narrative[501:1000]
# create a prediction document term matrixpredMatrix <- create_matrix(predictionData, originalMatrix=dtMatrix)
# create the corresponding container
plength = length(predictionData);predictionContainer <- create_container(predMatrix, labels=rep(0,plength), testSize=1:plength, virgin=FALSE)To see how the model performs, we will use the classify model function to score the test dataset based on the model. Then we will aggregate the data based upon the issue type, and the average SVM probability. As the output shows, the model does best in classifying Dealing with my lender or servicer, and is not able to discern Getting a loan as well. This all provides valuable information for a loan lender, since we now can see what types of topics a caller is discussing:
# predictresults <- classify_model(predictionContainer, model)head(results)aggregate(results$SVM_PROB, by=list(results$SVM_LABEL), FUN=mean, na.rm=TRUE)
> head(results)The output appears in the console as shown as follows:
SVM_LABEL SVM_PROB1 Dealing with my lender or servicer 0.54364382 Dealing with my lender or servicer 0.75218353 Dealing with my lender or servicer 0.51539984 Dealing with my lender or servicer 0.76111525 Dealing with my lender or servicer 0.72257026 Dealing with my lender or servicer 0.7590674> aggregate(results$SVM_PROB, by=list(results$SVM_LABEL), FUN=mean, na.rm=TRUE) Group.1 x1 Can''t repay my loan 0.62118512 Dealing with my lender or servicer 0.69677353 Getting a loan 0.4779246- AMERICAN STATISTICAL ASSOCIATION RELEASES STATEMENT ON STATISTICAL SIGNIFICANCE AND P-VALUES. (2016, March 7). Retrieved from ASA news: http://www.amstat.org/asa/files/pdfs/P-ValueStatement.pdf
- Anscombe’s quartet. Retrieved from Wikipedia: https://en.wikipedia.org/wiki/Anscombe%27s_quartet
- Coefficient of determination. Retrieved from Wikipedia:https://en.wikipedia.org/wiki/Coefficient_of_determination
- Fader, P. S. (2001, May-June). Forecasting Repeat Sales at CDNOW. Interfaces, 31 (May-June), Part 2 of 2, S94-S107.
- FAQ: WHAT ARE PSEUDO R-SQUAREDS? Retrieved from UCLA Institute for Digital Research and Education: http://stats.idre.ucla.edu/other/mult-pkg/faq/general/faq-what-are-pseudo-r-squareds/
In this chapter, we added three more algorithms to our arsenal, and these 3, along with regression form the core basic algorithms that can cover a lot of ground in terms of the typical problems a predictive analyst will face. We saw that a good knowledge of decision tree methodologies allows you to start developing models quickly, they are easily interpretable, and are the basis for more advanced techniques such as random forests. We then went on to clustering. Clustering allows you to begin to grasp the concepts of similarity and dissimilarity, and we introduced distance measures. We then ended with a basic introduction to support vector machines, which were demonstrated in the context of text mining.
In the next chapter, we will begin to look at some examples of creating models that predict how long a customer will stay with a company, or for predicting how long it will be until a patient develops a certain medical condition.