Spark Machine Learning – Regression and Cluster Models
local graph
Chapter 11 — Spark Machine Learning – Regression and Cluster Models
Section titled “Chapter 11 — Spark Machine Learning – Regression and Cluster Models”“The study of thinking machines teaches us more about the brain than we can learn by introspective methods. Western man is externalizing himself in the form of gadgets.”
- William S. Burroughs (Naked Lunch)
In the previous chapters, we introduced Spark and SparkR, with the emphasis on exploring data using SQL. In this chapter, we will begin to look at the machine learning capabilities of Spark using MLlib, which is the native machine learning library which is packaged with Spark.
In this chapter we will cover logistic regression, and clustering algorithms. In the next chapter we will cover rule based algorithm, which include decision trees. Some of the material has already been discussed in prior chapters using PC versions of R. In this chapter, as well as the next, we will focus predominantly on how to prepare your data and apply these techniques using the MLLib algorihms which exist in Spark.
In the last chapter, we saved the out_sd to an external parquet file. In the real world, you will be faced with analyzing multiple data sources. Often, these data sources will have similar schemas but will differ by the time period that they were written.
For example, log files can be archived in different directories, categorized by date, and you as an analyst will need to read in multiple files and concatenate them together.
So although each individual file may be small, when aggregated together, they will yield a much larger file.
Let’s pretend that we will be performing some machine learning on several files that have been written over the past two days. For illustration purposes, we will use the same file for the two inputs. However, in practice, you may be concatenating many days worth of transactions:
- First, read the data back in. Recall that the files were saved in the previous chapter in parquet format:
todays_file <- parquetFile(sqlContext,"/tmp/temp.parquet")yesterdays_file <- parquetFile(sqlContext,"/tmp/temp.parquet")- Concatenate the two days of data into one file using the Spark unionAll() function:
out_sd <- unionAll(todays_file,yesterdays_file)- Once we read in the files, we can cache the out_sd file to allow it to be queried optimally for the rest of the session:
cache(out_sd)Next, use the SparkR mean() and count() functions to verify the integrity of the file. For example, we know from the original data that ~34% of the outcomes are positive, so we can use these functions as a calculator to determine that the files contain 536,000 positive cases. Why even do this? When dealing with large datasets, it is usually worth the effort verifying the contents of the file first before you start manipulating the records. Saving time by performing data prep is crucial:
head(SparkR::select(out_sd,count(out_sd$outcome),mean(out_sd$outcome),mean(out_sd$outcome)*count(out_sd$outcome)))
Next, we will create a summary of the dataframe. However, instead of just printing the summary as we have done in the past, we will save the results of the summary to an object as well, since we will be using the aggregate information later in order to join it back to the original data. Again, if you will be manipulating large datasets, there is no need to run summary() functions more than once on the same data:
- Set up some global options, such as thue number of significant digits, plot width and height, etc.
- Assign the summary output to an dataframe.
- Use the databricks display() function (or head() function) to print a portion of the file:
options(digits=3)options(repr.plot.width = 1000, repr.plot.height = 500,repr.plot.res = 144, repr.plot.pointsize = 5)sumdf = summary(out_sd)display(sumdf)
Proceed to create our test and train datasets. The objective will be to sample 80% of the data for the training set and 20% of the data for the test data set.
To speed up sampling somewhat, we can sequentially sample the tails of the sample_bin range for the test dataset and then use the middle for the training data. This is still a random sample, since sample_bin was originally generated randomly and the sequence or range of the numbers have no bearing on the randomness.
Since we want 80% of our data to be training data, first take all of the sample_bin numbers which lie between the high and low cutoff values. We can define the cutoff range as 20% of the difference between the highest and lowest value of sample_bin.
Set the low cutoff as the lowest value plus the cutoff range defined previously, and the high cutoff as the highest value minus the cutoff range:
#compute the minimum and maximum values of sample binset.seed(123)sample_bin_min <- as.integer(collect(select(out_sd, min(out_sd$sample_bin))))sample_bin_max <- as.integer(collect(select(out_sd, max(out_sd$sample_bin))))
Cutoff <- .20*(sample_bin_max - sample_bin_min)Cutoff_low <- sample_bin_min + CutoffCutoff_high <- sample_bin_max - Cutoff
rm(df)
#take 80% of the training samples. These happens to be the ones that fall in the middle.
df <- filter(out_sd, out_sd$sample_bin > Cutoff_low & out_sd$sample_bin < Cutoff_high)train_sumdf = summary(df)Print some of the key fields using the Spark select() function within the databricks display command. Note that when printing the summary object in this way, there are always five rows (count, mean, sdev, min, and mins) along with one column for each variable:
display(select(train_sumdf,"summary","outcome","pregnant","age","mass","glucose","triceps"))
For generating the test data, we will select only the rows which fall beyond the cutoff points. That will yield the 20% sample. Note that the SparkR describe function is an alias for the summary() function. Use this when you want to avoid conflict of names between the Spark and base R functions.
#set the test data set to include the rest of the populationset.seed(123)test <- filter(out_sd, out_sd$sample_bin <= Cutoff_low | out_sd$sample_bin >= Cutoff_high)test_sumdf = describe(test)
display(select(test_sumdf,"summary","outcome","pregnant","age","mass","glucose","triceps"))
Spark will take advantage of parallel processing algorithms as much as possible. Extracting training and test data samples is a prime example of this, since extracting the training data set can be performed independently of the training data.
So, in Databricks, you will be able to visually see them run at the same time via a progress bar. In cases in which a block of code is dependent upon another block of code, you will see the execution begin, but it will be in wait state until the needed prior blocks have been completed.
The takeaway from this is that you should always try to develop your analytics code in a manner which utilizes this in order to take advantage of parallel processing.
Since both the test and training datasets have been generated by simulated random normal distributions, the data is almost too perfect. To compensate for this, and to make the data more realistic and help you develop more simulation skills, we can introduce some random error into the test data set. For example, we might want to add up to a plus/minus 10% variation into the test data variables.
To accomplish this, we will first generate an error distribution that we can apply to the original data. For simplicity’s sake, we can derive four discrete error bins, each designating a different percentage adjustment to the data. Percentage errors between -10% and +10% are reasonable limits.
We will generate this by using the following rnorm function, and then set any value beyond +/- 10 percent to 0. This will become our own customized distribution for selecting a probability of error:
#set the random seedset.seed(123)#set the binsx <- rnorm(n=25,mean=0,sd=4)/100#assign errors conditionallyx <- ifelse(abs(x) > .10,0,x)Rather than simply plotting the distribution, let’s plot a histogram of the distribution so that we can see what the approximate error bins will look like. In fact, let’s generate two different histograms, one containing the actual counts and the other containing percentages:
par(mfrow=c(1,2))h <- hist(x,freq=FALSE,right=FALSE,breaks=c(-.20, -.15,-.10,-.05, 0, .05, .1, .15, .20))
print(h)
plot(h$mids,100*h$counts/sum(h$counts),type="h",lwd=25, lty=1, main="Probability of Errors Introduced")In the plots below, you can see from the histogram on the left that there are no values beyond the limits specified. In fact, since the distribution was generated with a mean=0, a good number of the test elements will have no errors added to them. This is by design.
The bar chart on the right has been generated simply to show the relative percentage of each bar (rather than the straight frequency). From this, we can see, for example, that the probability of an adjustment of 5-10% is about 12%:

Now we can introduce some variation into the dataset by adding a random percentage of each variable to itself. This is done by first sampling from the error distribution (x).
Note that we need to preface base: to the sample function, since the base sample function has a different syntax from the Spark sample function. If you do not do this, you will get an error:
## alter the test data set by sampling from the 'x' distribution and adding or subtracting the introduced error adjustment.
test$age = test$age + test$age*base::sample(x, 1, replace = FALSE, prob = NULL)
test$pregnant = test$pregnant + test$pregnant*base::sample(x, 1, replace = FALSE, prob = NULL)
test$glucose = test$glucose + test$glucose*base::sample(x, 1, replace = FALSE, prob = NULL)
test$pressure = test$pressure + test$pressure*base::sample(x, 1, replace = FALSE, prob = NULL)
test$triceps = test$triceps + test$triceps*base::sample(x, 1, replace = FALSE, prob = NULL)
test$insulin = test$insulin + test$insulin*base::sample(x, 1, replace = FALSE, prob = NULL)
test$mass = test$mass + test$mass*base::sample(x, 1, replace = FALSE, prob = NULL)
test$pedigree = test$pedigree + test$pedigree*base::sample(x, 1, replace = FALSE, prob = NULL)
#calculation the number of rows again, to make sure they are the same as before
nrow(test)
Now that we have constructed our test and training datasets, we will begin by building a logistic regression model which will predict the outcome 1 or 0. As you will recall, 1 designates diabetes detected, while 0 designates diabetes not detected.
The syntax of a Spark glm is very similar to a normal glm. Specify the model using formula notation. Be sure to specify family = “binomial” to indicate that the outcome variable has only two outcomes:
# run glm model on Training dataset and assign it to object named "model"
model <- spark.glm(outcome ~ pregnant + glucose + pressure + triceps + insulin + pedigree + age,family = "binomial", maxIter=100, data = df)summary(model)You can observe the coefficients of the model in the Estimate column. You can also see that the residuals range from -2.54 to +2.40, which encompasses about 2.5 standard devations, and that the median value (not the mean) is supplied, which is -.326. Also note that p-values are not supplied in this version of spark.glm, since they are all displayed as 0.
The AIC for this model is listed at the bottom; however, it has no meaning unless it is compared with another model.

Regularization models are an alternative to spark.glm; you can also run spark.logit and supply regularization parmeters to the independent variables.
By default, spark.logit will yield the same results as spark.glm without regularization parameters:
model2 <- spark.logit(df, outcome ~ pregnant + glucose + pressure + triceps + insulin + pedigree + age)To verify this, run both spark.logit and spark.glm and verify that the results are identical.
Once you have verified this, you may add regularization parameters if you wish to smooth out the model by flattening the coefficients or set some of them to 0.
The model which has been run below only includes glucose, insulin, and pressure as predictors. Since the elasticnetparm (.8) is between 0 and 1, where 0 uses L2 and 1 will use L1, it will be using a combination of L1 and L2 regularization. Therefore, you will see some shrinkage of the coefficients to 0:
# Fit an binomial logistic regression model with spark.logit
model2 <- spark.logit(df, outcome ~ pregnant + glucose + pressure + triceps + insulin + pedigree + age, maxIter = 10, regParam = 0.1, elasticNetParam = 0.8)
summary(model2)

SparkR does have a prediction method, aptly named predict(), so we can run predictions on the training set:
- After running the following code, you will observe that the resulting object contains a new column named prediction
- We can also add a unary flag (1) to the results (grp) to indicate that the output is from the training data
- We will also append the total number of rows to each record, since we will need them later for calculations:
#look at the predictions vs. the training datasetpreds_train <- predict(model, df)preds_train$grp <- 1preds_train$totrows = nrow(preds_train)The prediction variable is the probability that the outcome of the event (diabetes) will occur:
head(preds_train)
One way to plot this in Spark is to construct a histogram of the probabilities, using the midpoints of the binned range (centroids) for the x axis and the raw counts for each bin plotted on the y axis.
x=SparkR::histogram(preds_train,preds_train$prediction, nbins = 100)x$centroids=round(x$centroids,2)display(x)After the display command has run, click on the Plot Icon (2nd Icon at the bottom left), and click on “Plot Options”. The customize plot screen will then display:
- Set Display type to Grouped Bar Chart using a combination of the drop down selection and radio buttons.
- Drag counts from All Fields to Values.
- Drag Centroids to Keys.
Centroids represent the midpoints of the bars. In the code above, we rounded them to two decimal places for readability on the generated plot. If the plot renders too small, you will need to open up Customize Plot again to see it again but larger.
The output shows a typical density for a logistic model, with most of the weight predicting a non-event. The higher probabilities, to the right, bin the frequencies for the probabilities which predict outcome=1.

Next, we have similar code for the test data group. Set the grp flag to 0 to designate this is from the test group:
#run predictions on test dataset based on training modelpreds_test <- predict(model, test)preds_test$grp <- 0preds_test$totrows = nrow(preds_test)Print a few rows from the results using the SparkR select function to extract several key columns:
head(SparkR::select(preds_test,preds_test$outcome,preds_test$prediction,preds_test$grp,preds_test$totrows))
Next, we will combine the training (grp=1) and testing (grp=0) datasets into one dataframe and manually calculate some accuracy statistics:
- preds$error: this is the absolute difference between the outcome (0,1) and the prediction. Recall that for a binary regression model, the prediction represents the probability that the event (diabetes) will occur.
- preds$errorsqr: this is the calculated squared error. This is done in order to remove the sign.
- preds$correct: in order to classify the probability into correct or not correct, we will compare the error to a .5 cutoff. If the error was small (<- .5) we will call it correct, otherwise it will be considered not correct. This is a somewhat arbitrary cutoff, and it is used to determine which category to place the prediction in.
As a final step, we will once again separate the data back into test and training based upon the grp flag:
#classify 'correct' prediction if error is less than or equal to .5
preds <- rbind(preds_train,preds_test)preds$error = abs(preds$prediction-preds$outcome)
#square the error to get the absolute squared error
preds$errorsqr = (preds$prediction-preds$outcome) ^ 2
#assign correct=Yes, or correct=No
preds$correct = ifelse(preds$error <= .5, "Y","N")preds$errbin = round( (preds$error*10),0)
#separate the data again, including the new columns
preds_train = filter(preds, preds$grp==1)preds_test = filter(preds, preds$grp==0)Next, print some of the results. You can see from the output that the first observation was classified as correct since the model probability was.03 and it is closer to the actual outcome (0). On the other hand, the sixth observation was (marginally) classified into predict outcome=1, but was wrong, therefore correct was set to N:
head(preds)
We can now register our three key tables so that we can run some SQL code in order to obtain some additional diagnostics:
registerTempTable(preds,"preds_tbl")registerTempTable(preds_train,"preds_train")registerTempTable(preds_test,"preds_test")Logistic regression in SparkR lacks some of the cross-validation and other features that you may be used to in base R. However, it is a starting point to enable you to start running large-scale models. If you need to employ some of the cross-validation techniques that have already been covered, you can certainly extract a sample of the data (via collect) and run the regression in base R.
However, there are some techniques that you can use to produce pseudo R-Squares and other diagnostics while continuing to work within Spark, which we will demonstrate.
We can compute the confusion, or error, matrix in order to determine how our manual calculation performed, when we classified the prediction outcomes as correct or not:
#Confusion matrixresult <- sql("select outcome,correct, count(*) as k, avg(totrows) as totrows from preds_tbl where grp=1 group by 1,2 order by 1,2")result$classify_pct <- result$k/result$totrows
display(result)
To determine the grand total correct model prediction, sum the correct=Y columns previously:
Summary of correct predictions for training group:
| Correctly predicted outcome=1 | 20% |
|---|---|
| Correctly predicted outcome=0 | 59% |
| Total Correct Percentage | 79% |
You can see that there is much more predictive power in predicting outcome=0 than there is outcome=1.
The results for the test group are similar to those of the training group. Any discrepancies between test and training would warrant looking more closely at the model and observing how the data was sampled or split:
#Confusion matrix for TEST groupresult <- sql("select outcome,correct, count(*) as k, avg(totrows) as totrows from preds_tbl where grp=0 group by 1,2 order by 1,2")result$classify_pct <- result$k/result$totrowsdisplay(result)
Add up the correct calculation is a similar way to the training group. The results are slightly less, which is normal when comparing test to training results:
Summary of Correct Predictions for Test Group:
| Correctly predicted outcome=1 | 22% |
|---|---|
| Correctly predicted outcome=0 | 52% |
| Total Correct Percentage | 74% |
Distribution of errors is another that you can look at how well a model has fit the data. In this analysis, we look at the distribution of errors for all four combinations of the following variables:
- Outcome
- Correct prediction flag
- Average error as grouped into categories via the errbin variable:
result2 <- sql("select outcome,correct,errbin, count(*) as k, avg(error) as avgerr from preds_tbl group by 1,2,3 order by 1,2,3")Once the query has completed, issue a display command so that we can perform some visualizations.
display(result2)- Once the display has run, select the “Plot Options” icon (third icon bottom left), and select a Stacked bar chart plot from the plot menu.
- Drag k (counts) to the Values box.
- Drag outcome and correct to the Series grouping box.
- Click Apply to update the visualization:
- As can be seen from the plot below, The lowest (and best) error for a predictor class was for the non-diabetic patients (bars 1-5, Outcome 0, Prediction N).
- The highest error can be seen for cases in which diabetes was predicted, but the patient was, in fact, nondiabetic (bars 6-11, Outcome 0, Prediction Y).
- A critical category, undetected diabetes (bars 12-16, outcome=1, prediction N) also had a relatively low error:

In this plot, we can look at the average error across both the test and training data and as well as outcome. Set up the “Series grouping” box to include both grp and outcome. We can see that the average error increases in the test data set for both outcome=1 and outcome=0.
A slight increase in error is to be expected when measured over the testing data:
#distribution of error binresult2 <- sql("select outcome,grp,errbin, count(*) as k, avg(error) as avgerr from preds_tbl group by 1,2,3 order by 1,2,3")display(result2)
Recall that a true R-square measure is not a standard output statistic for logistic regression but there are other goodness of fit measures we can use, such as the McFadden pseudo R-square.
We calculate this in code, by first obtaining both the residual deviance and the null deviance. The residual deviance measures the deviation in the model with all of the dependent variables included. The null deviation measures the residuals with only the intercepts included. You want the ratio of deviation/null.devation to be as small as possible for a good model. Subtract this value from 1 to obtain a pseudo R-square.
All of these measures are available via the model_summary object:
#mcfadden pseudo Rsquare
1-(model_summary$deviance/model_summary$null.deviance)The calculation is automatically printed:

We have already computed the squared error from the data, so to compute the root-mean-square error (RMSE), all we need to do is call SQL in order to take the average squared error for each outcome. We can see that there is much more variation in predicted outcome=1 (diabetes) than there is for predicting outcome=0:
result <- sql("select outcome,avg(errorsqr) from preds_tbl group by 1")display(result)
If you wish to use other tools to plot the data, you can first take a sample of the Spark data and plot it using another package such as ggplot. Note that some versions of Spark may now have ggplot integrated and available for use within Spark. However this example will show another example of extracting data which can be used by other packages.
We will take a 2% sample of all of the predictions and then print some of the results. Note that the Spark sample function has a different syntax from the base R sample function we used earlier. You could also specify this as SparkR::sample to make sure you are invoking the correct function:
local = collect(sample(preds, F,.02))
head(local)
Next, you can run ggplot to graphically display the errors grouped by outcome. The resulting boxplots show that the three quartiles for diabetes are above the non-diabetic patients. This demonstrates that the model’s prediction error runs higher when predicting those patients who actually developed diabetes. This would certainly imply that the model needs to be improved:
library(ggplot2)ggplot(local, aes(factor(outcome),error)) + geom_boxplot()
We are now done with machine learning using logistic regression. For the next section (k-means), we will need to register some additional tables for dataframes that have already been produced:
registerTempTable(sumdf,"sumdf")registerTempTable(out_sd,"out_sd")registerTempTable(df,"df")registerTempTable(test,"test")Creating global views will also allow us to pass data between different databricks notebooks. These views will be referenced in the next section. Use the %sql magic command as the first line in the databricks notebook to signify that these are SQL statements:
%sqlCREATE GLOBAL TEMPORARY VIEW df_view AS SELECT * FROM df
%sqlCREATE GLOBAL TEMPORARY VIEW test_view AS SELECT * FROM test
%sqlCREATE GLOBAL TEMPORARY VIEW out_sd_view AS SELECT * FROM out_sd
%sqlCREATE GLOBAL TEMPORARY VIEW sumdf_view AS SELECT * FROM sumdfAfter the views have been created, use SQL to read back the counts and verify the totals with the row counts produced for the original dataframes:
%sqlselect count(*) from global_temp.df_view union allselect count(*) from global_temp.test_view union allselect count(*) from global_temp.sumdf_view union allselect count(*) from global_temp.out_sd_view
In this section, we will illustrate how to implement a cluster analysis directly in Spark using k-means. K-means is a form of unsupervised learning and is an excellent place to begin to explore big data, especially if your data is large and you have no clear definition of target variables.
We will first perform some data preparation in order to normalize the data for k-means. Normalization is pretty much a requirement for k-means, since it forces each variable to be scale-independent so that measuring distances between the k-means clusters is also scale-independent.
Recall that one way to normalize a variable is to first obtain the mean of the variable and then divide by its standard deviation.
We saved the diabetes dataset as a table and a global view in the previous section, so we can now read it back using SQL. We will first read the training table (temp.df_view) and then follow by reading the test table (test_view). The resulting objects are both Spark dataframes.
After reading the table in, print the count of the rows. If you want to see the counts as one result, you can use a function such as cat() to print the results on one line:
df = sql("select age, pregnant, glucose, pressure, insulin, pedigree, triceps, massfrom global_temp.df_view")
test = sql("select age , pregnant, glucose, pressure, insulin, pedigree, triceps, massfrom global_temp.test_view")
cat(count(df),count(test))
In order to normalize the data, we will need the means and standard deviations of each column. If you were doing this purely in base R, there would be many ways to do this using built-in functions and packages. However, using SparkR may limit how we would typically proceed, and force us to be more efficient and process the data in different ways.
Recall that we have already stored this data in a summary object (sumdf_view and so on), so in order to save some processing time, we will simply read the summary statistics back in and avoid having to recalculate the summary statistics.
First, we will read the means row in, followed by the stddev row:
means = sql("select age as age_mean, pregnant as pregnant_mean, glucose as glucose_mean, pressure as pressure_mean, insulin as insulin_mean, pedigree as pedigree_mean, triceps as triceps_mean, mass as mass_meanfrom global_temp.sumdf_view where summary='mean'")stds = sql("select age as age_std, pregnant as pregnant_std, glucose as glucose_std, pressure as pressure_std, insulin as insulin_std, pedigree as pedigree_std, triceps as triceps_std, mass as mass_stdfrom global_temp.sumdf_view where summary='stddev'")Now we can join the aggregate means and standard deviations together using a crossJoin. No key is necessary since the tables have the same number of rows and they correspond 1 to 1.
Then join the summary data with the original data. The resulting object is another Spark dataframe (df_means) with the means and standard deviations of all of the variables joined to each row:
#join the means and standard deviationsboth <- crossJoin(means,stds)#join with the original datadf_means <- crossJoin(df,both)nrow(df_means)
Print a portion of the resultant object. All of the original variables are displayed along with their corresponding means and standard deviations:
print(head(select(df_means,"age","age_mean","age_std","mass","mass_mean","mass_std")))
Similar to the preceding code, we join the means and standard deviations to the test data set separately.
Check the number of rows created. If you want to see the actual results, print a portion of the data as we did with the training data above:
test_means <- crossJoin(test,both)nrow(test_means)
We now have all the needed statistics to normalize the data. Recall that the formula for normalizing a variable x is as follows:
In order to implement this, we will wrap the needed computations into a function and invoke it for both the training and test datasets:
- Use the SparkR selectExpr expression to calculate the normalized version of each variable using the formula above.
- Also, create a new variable with old appended to the name, which preserves the original value of the variable. After testing, you should remove these extra variables to save space, but it is good to retain them while debugging:
normalize_it <- function (x) { selectExpr(x, "age as ageold","(age-age_mean)/ age_std as age", "mass as massold","(mass-mass_mean)/ mass_std as mass", "triceps as tricepsold", "(triceps-triceps_mean)/ triceps_std as triceps", "pressure as pressureold", "(pressure-pressure_mean)/ pressure_std as pressure", "pedigree as pedigreeold", "(pedigree-pedigree_mean)/ pedigree_std as pedigree", "glucose as glucoseold", "(glucose-glucose_mean)/ glucose_std as glucose", "pregnant as pregnantold", "(pregnant-pregnant_mean)/ pregnant_std as pregnant", "insulin as insulinold", "(insulin-insulin_mean)/ insulin_std as insulin" )}First, call the function for the test dataset:
test_normal <- normalize_it(test_means)Next, normalize for the training dataset:
df_normal <- normalize_it(df_means)Print some of the output for the normalized training data.
head(df_normal)Notice from the output below that the normalized values appear to range between -2 and +2 with a mean of 0. Any value close to these extremes falls near the extreme range for the variables.
For example, observation 4 shows a normalized age of less than -2, which corresponds to the original age of 9, while observation 4 also shows a normalized body mass of 1.68, which corresponds to the original body mass of 44.
This is at the upper range for a 9-year-old child, and we have been able to quickly identify some extreme values simply by looking at the relationship between some of the normalized values:

Now that the data is normalized, we can move on to model building.
SparkR contains a k-means model which is very similar in syntax to the base k-means model. There is an additional parameter, InitMode, in which you can specify that a random seed be generated for generating the starting cluster. As of this version of SparkR, you cannot manually set a seed. Therefore, be aware that the clusters generated may be slightly different each time the model is run.
Additionally, you can specify the outcome variable (glucose) as well as the variables to be clustered, so that you can evaluate the fit of the cluster model.
For illustration purposes, we will generate a model of five clusters.
Use summary(model) to display the coefficients needed to generate the prediction as well as the size of each of the clusters, as shown as follows.
model <- spark.kmeans(df_normal, glucose ~ age + mass + triceps + pregnant,k = 5, initMode = "random")
summary(model)You can see from the sizes that each of the clusters are approximately equal in size, except perhaps for cluster 1:
#here is the output from summary function
$k[1] 5
$coefficients age mass triceps pregnant1 0.974506 0.871064 1.096543 0.98354012 -0.2056799 0.9210847 0.666911 -0.4326243 0.7791526 -0.4984192 -0.2448071 0.89734914 -1.092614 -0.1553198 -0.1833185 -0.90762265 -0.2380403 -1.001556 -1.246133 -0.2903638
$size$size[[1]][1] 170000
$size[[2]][1] 276000
$size[[3]][1] 298000
$size[[4]][1] 274000
$size[[5]][1] 220000Since you have the coefficients, you could actually predict the cluster membership manually via code. You would probably want to do this if you were implementing cluster assignment in a production environment. However, it is easier to use a predict method.
Let’s fit the model first to the training data. We can print out some of the fitted values just to see what was generated. The last column indicates the cluster assignment for that observation:
fitted <- predict(model, df_normal)SparkR:::registerTempTable(fitted,"fitted_tbl")head(fitted)
Fit the model on the test data and print out some of the results obtained for the test data:
fitted_test <- predict(model, test_normal)SparkR:::registerTempTable(fitted_test,"fitted_tbl_test")head(fitted_test)
Bivariate cluster plots are often useful for seeing how the cluster assignments correlate with an x - y plot of two variables. Each cluster is plotted in a different color.
In Databricks, you can do this easily:
First, run the display command on some of the fitted data. In the code below, I have first extracted a 1,000-row sample. You want the sample to be small enough so that the points on the plot are not too dense.
tmp <- head(sample(fitted, F, .01),1000)display(tmp)
#show cluster assignment by 2 variable matrixNext, switch to the plot dialog box, Open the Customize Plot dialog. and perform the following graph setup:
- Change the graph type to scatter plot.
- Drag the prediction to the keys area.
- Drag all the possible x - y plotting variables to the values area:
- If you add a LOESS line to the plots, you will be able to pick out some of the clusters which are easily separable by a combination of two variables.
Click Apply to update the plot. In the following plot, the upward trending line at the intersection of age and pregnant shows distinct cluster separation as age and months pregnant varies:

To get a larger and more detailed plot, you can also use the pairs function to produce a scatter matrix on your desired variables using color to outline the various clusters.
We can see that the clusters are separated from the rest in some cases, while in other cases there can be minor or major overlap:
pairs(tmp[c("age","mass","pressure","pregnant")], col=tmp$prediction)
To start analyzing the components of the clusters, you can look at how the variables are plotted along each of the axes.
For example, the red cluster shows a relationship between older patients and number of months pregnant. This would seem to indicate a positive diabetes condition. To double-check, you can look at body mass, and also see that the higher values show up in the red cluster for all of the other variables as well.
On the other hand, the relationship between pressure and mass is not as clear, possibly due to the fact that other factors could be in play which are not apparent in a two-dimensional plot.
Another way to look at the clusters is by looking directly at their mean values. We can do this directly by using SQL:
- First, look at any variables which have normalized values >1 or < -1, or high the highest absolute value for that variable. That will give you some clues on how to begin to classify the clusters.
- Also look at the magnitude and the signs of the coefficients. Coefficients with large absolute values can indicate an important influence of the variable on that particular cluster. Variables with opposite signs are important in terms of characterizing or naming the clusters.
tmp_agg <- SparkR::sql("SELECT prediction, mean(age),mean(triceps),mean(pregnant),mean(pressure),mean(insulin),mean(glucose),mean(pedigree) from fitted_tbl group by 1")head(tmp_agg)
Scanning through the five clusters produced, you might categorize Cluster 2 as a group consisting of younger people with lower pregnancy rates since the mean values for both variables are near the negative -1 value. Remember that these are all standardize values so you can compare them, and use +1/-1 standard deviation levels as cutoffs. So, using that as a cutoff, you could also also hypothesize that Cluster 3 could be people with lower body mass since the triceps level is also near -1. Values close to 0 implies that the variable has a negligible influence on the cluster.
Results for this data set are similar to the training data:
tmp_agg <- SparkR::sql("SELECT prediction, mean(age), mean(triceps), mean(pregnant),mean(pressure),mean(insulin),mean(glucose),mean(pedigree) from fitted_tbl_test group by 1")head(tmp_agg)
In this chapter we went beyond SQL, and started to explore the machine learning capabilities of Spark. We covered both regression and kmeans clustering using our diabetes dataset. We constructed our training and testing data sets, and learned how to introduce some variation into our data via simulation. A lot of Databricks visualization was covered, as well as some visualizations using the collect() function to export the data to base R so that we could use ggplot. We also learned how to perform some regression diagnostics manually using code. We then learned how to standardize a data set via code, and used the results to illustrate a kmeans example using Spark. Finally we looked at the resulting clusters and examined some simple interpretations.