Skip to content
ImagineWorld

Exploring Large Datasets Using Spark

node_idnode-book_practical-predictive-analytics_chapter-10-exploring-large-datasets-using-spark
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num10
chapter_titleExploring Large Datasets Using Spark
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Chapter 10 — Exploring Large Datasets Using Spark

Section titled “Chapter 10 — Exploring Large Datasets Using Spark”

“I never guess. It is a capital mistake to theorize before one has data. Insensibly one begins to twist facts to suit theories, instead of theories to suit facts.”

- Sir Arthur Conan Doyle

In this chapter, we will begin to perform some exploratory data analysis on the Spark dataframe we created in the previous chapter. We will learn about some specific Spark commands that will assist you in your analysis, and will discuss several ways to perform graphing and plotting.

As you go through these examples, remember that data that resides in Spark may be much larger than you are used to, and that it may be impractical to apply some quick analytic techniques without first considering how the data is organized, and how performance will be affecting using standard techniques.

If you are picking up where you left off in the previous chapter, you will have to load the saved Spark data frame before you begin. Recall that we saved the results of the diabetes data set as a parquet file, so we can use the parquetFile() function to read the data back into memory. Then filter out the positive diabetes cases since we will be explore them next:

out_sd <- parquetFile(sqlContext, "/tmp/temp.parquet")
out_sd1 = SparkR::filter(out_sd,out_sd$outcome == 1)

Before we move on to exploring the entire Spark dataframe, we can look at some of the data already generated for positive cases. As you may recall from the prior chapter, this is stored in the Spark dataframe out_sd1.

We have generated some random sample bins specifically so that we can do some exploratory analysis.

We can use the filter command to extract random sample 1, and take the first 1,000 records:

  • The filter is a SparkR command that allows you to subset a Spark dataframe
  • The display command is a databricks command that is equivalent to the View command we have previously used and you can also use the head function as well to limit the number of rows that are displayed:

This code chunk extracts 1000 records from the positives and displays them:

small_pos <- head(SparkR::filter(out_sd1,out_sd1$sample_bin==1),1000)
nrow(small_pos)
display(small_pos)

The data appears in tabular form, and you can scroll up/down, or left/right to look for missing values, extreme values, and so on.

The filter command serves two functions:

  • Extracting a segment of interest for your analysis.
  • Extracting a sample, which can be helpful for debugging your Spark data flow. This can help subsequent steps run quicker, and avoids unnecessarily running large jobs, especially if the sample reflects the makeup of the population.

There are several ways of displaying subsets of your Spark dataframe. Some of the choices are as follows:

  • showDF: This is a Spark command that displays the contents of a dataframe in a condensed manner.
  • head: This is the normal R function that can be used on a Spark dataframe; it follows the same syntax as base R.
  • take: This command also prints some rows, but collects the rows from the underlying RDD.
  • display: This is a special databricks command that is roughly equivalent to the base R View command, but also allows you to plot a subset of the output via control icons below the horizontal scroll bar below the data. Using display also allows you to switch to graphing mode.

Click on the second icon:

You will be taken to a graph dialog, in which you can graph the various relationships among the variables. To graph these relationships, first drag a variable from the All fields column to the Values column:

  • For example, the first plot displays a boxplot for insulin levels for diabetes=1
  • Plot 2 shows a histogram of insulin levels with 20 bins defined
  • Plot 3 shows a scatter plot between age and insulin levels
  • Plot 4 shows the correlation matrix of age, insulin, and the number of months pregnant:

Correlation and covariance functions are available which operate directly on Spark dataframes. The following example shows that, for patients with diabetes, there is an 11% correlation between age and glucose level:

corr <- corr(out_sd1, "glucose", "age", method = "pearson")
corr

Since Spark excels at processing in-memory data, we will first remove our intermediary data and then cache our out_sd dataframe, so that subsequent queries run much faster. Caching data in memory works best when similar types of queries are repeated. In that way, Spark is able to know how to juggle memory so that most of what you need resides in memory.

However, this is not foolproof. Good Spark query and table design will help with optimization, but out-of-the-box caching usually gives some benefit. Often, the first queries will not benefit from memory caching, but subsequent queries will run much faster.

Since we will no longer use the intermediary dataframes we created, we will remove them with the rm function, and then use the cache() function on the full dataframe:

#cleanup and cache df
rm(out_sd1)
rm(out_sd2)
cache(out_sd)

We can also use the Count and groupby functions to aggregate individual variables.

Here is an example of using this to tally the number of observations by outcome. Since the result is another dataframe, we can use the head function to write the results to the console.

You might have to alter the number of rows returned by head if you change the query. It is always a good idea to filter results using a function such as head, to make sure that you are not printing hundreds of rows (or more).

However, you also need to ensure that you do not cut off all of your output. If you are unsure as to the number of rows, first assign the result to a dataframe and then check the number of rows (with nrow) first:

This code line count the number of rows by outcome. I know that there should be only 2 outcomes, but I place the count function within a head statement just to program defensively.

head(SparkR::count(groupBy(out_sd, "outcome")))

Printing values from a Spark dataframe is very quick. Here are a few values from each outcome group. Note that the sample.bin is negative for outcome == 0, and positive for outcome == 1:

First print some of the negatives. We can see that some of the pregnant numbers are negative, showing that the simulation wasn’t perfect.

head(SparkR::filter(out_sd,out_sd$outcome == 0),5)

Now print some of the positives.

head(SparkR::filter(out_sd,out_sd$outcome == 1),5)

Correlations and covariances can also be computed directly from a Spark dataframe. For our example, we can see that there is a larger correlation between age and glucose for non-diabetic patients:

First the diabetic outcomes. Correlation is.113:

Now, the non-diabetic outcomes. Correlation is.22:

For the entire population the correlation is 0.26:

Usually it’s necessary to create some new transformation based on existing variables which will improve a prediction. We have already seen that binning a variable is often done to create a nominal variable from a quantitative one.

Let’s create a new column, called agecat, which divides age into two segments. To keep things simple, we will start off by rounding the age to the nearest integer.

filtered <- SparkR::filter(out_sd, "age > 0 AND insulin > 0")
filtered$age <- round(filtered$age,0)
filtered$agecat <- ifelse(filtered$age <= 35,"<= 35","35 Or Older")
SparkR::head(SparkR::select(filtered, "age","agecat"))

In the code which you just ran, you may notice that some commands are prefaced by SparkR::

This is done to let the program know which version of the function we wish to apply, and it is always good practice to preface commands in this way, in order to avoid syntax errors and misapplying identically named functions which occur between SparkR and normal R.

Now that we have categorized age, we can run a cross-tab which counts outcomes by the age category.

Since there are only two outcomes and two age categories, this results in a four-cell crosstab:

  1. First, display the results using the special Databricks display command.
  2. After the results appear as shown in the table below, you can click the plot button (2nd icon on the bottom left) and the Customized Plot dialogue will appear, which will allow the results to be plotted as a bar chart. The plot show that diabetes occurs more frequently in the higher age group than in the lower age group, while the reverse is true for the non-diabetes group:
table <- crosstab(filtered, "outcome", "agecat")
display(as.data.frame(table))

Histograms are also a quick way to visually inspect and compare outcome variables.

Here is another example of using the Spark histogram function to contrast the mean values of body mass index for diabetic versus non-diabetic patients in the study. For the first bar chart, we can see a peak bar of about 38.9 BMI, versus a peak bar of 29.8 for non-diabetic patients. This suggests that BMI will be an important variable in any model we develop:

This code uses the SparkR histogram function to compute a histogram with 10 bins. The centroids gives the center value for each of the 10 bins. The most frequently occurring bar is the bar with a center value of 38.9 with a count of about 50,000. This type of histogram is useful for quickly getting a sense of the distribution of variables, but is somewhat lacking in labeling, and controlling various elements since as scales and ranges. If you wish to fine tune some of the elements you may want to start by using a collect() function to download a sample to your local R machine. We will discuss this capability later on.

If you prefer to use ggplot to plot your results, load the ggplot2 package to run your plots directly against the Spark dataframe. You will have more of an opportunity for further customization:

Here is a basic ggplot which corresponds to the histogram() functions illustrated above:

require(ggplot2)
plot <- ggplot(age_hist, aes(x = centroids, y = counts)) +
geom_bar(stat = "identity") +
xlab("mass") + ylab("Frequency")
plot

Another way to explore data in Spark is by using Spark SQL. This allows analysts who may not be well-versed in language-specific APIs, such as SparkR, PySpark (for Python), and Scala, to explore Spark data.

I will describe two different ways of accessing Spark data via SQL:

  • Issuing SQL commands through the R interface:

This has the advantage of returning the results as an R dataframe, where it can be further manipulated

  • Issuing SQL queries via databricks SQL magic: directive

This method allows analysts to issue direct SQL commands, without regard to any specific language environment

Before processing an object as SQL, the object needs to be registered as a SQL table or view. Once it is registered, it can be accessed through the SQL interface of any language API.

Once registered, you can use the show tables SparkR command to get a list of registered tables for your session.

#register out_sd as a table
SparkR:::registerTempTable(out_sd,"out_tbl")
SparkR:::cacheTable(sqlContext,"out_tbl")
head(SparkR::sql(sqlContext, "SHOW tables"))

Writing SQL this way consists of constructing a valid SQL string query via the sql function:

  • The query must reference a registered table
  • You can assign the results of the query to a dataframe:

Here is an example of getting a frequency count of the available samples from the registered object out_table. Note that the code begins with %r command which is a special Databricks directive that indicates that the code that follows applies to R. However, it is sometimes necessary to specify this (even in R notebooks), when a previous code chunks has used another language directive, such as %sql, or %python.

%r
rm(tmp)
tmp <- SparkR::sql(sqlContext, "SELECT sample_bin, count(*) FROM
out_tbl group by sample_bin")
  • Additionally in databricks, sqlcontext is preassigned, and so can be omitted in
    the code as follows.
tmp <- SparkR::sql("SELECT sample_bin , count(*) FROM out_tbl group
by sample_bin")
  • Once you have extracted the data to a tmp dataframe, you can display the counts of each of the samples. In subsequent queries, you can select samples corresponding to the size and proportion of the outcome you are interested in:
head(tmp,1000)

Based upon the preceding sample_bin counts, we might decide to extract a sample based upon a sample of some negative and positive cases. We know that positive sample_bin represent an outcome of 1, and negative sample_bins represent an outcome of 0. We can also pick a cutoff value which will accomodate whatever sample size we would like. We will be looking to extract a 10,000 row sample, so we will set the bounds to +10 and -10.

bin_extract <- SparkR::sql("SELECT * from out_tbl where sample_bin >= -10 AND sample_bin <= 10")
nrow(bin_extract)
#nrow should be 10,000 in the output

Next, we will register bin_extract so that we can perform some SQL

SparkR:::registerTempTable(bin_extract,"bin_extract")

If we were interested in comparing blood pressure values with the average age, we could then construct a query to calculate some mean and standard deviations on the larger Spark table (out_tbl), and then group the results by outcome. The output also indicates that diabetics are older:

bin_agg <- SparkR::sql("SELECT outcome,
mean(pressure) as mean_pressure,
std(pressure) as std_pressure,
mean(age) as mean_age,
std(age) as std_age
from out_tbl group by 1")
#register the table
SparkR:::registerTempTable(bin_agg,"bin_agg")
#print a few records
head(bin_agg)

Now we will construct a third query that will extract all records that may be considered outliers. For this example, we will define an outlier as any record that has age or pressure greater or less than 1.5 standard deviations below the mean for their outcome class. This is accomplished by joining our detail-level data with the aggregated means for age and pressure:

  • We can also compute a new column, agediff, which is the difference between age and average age.
  • We add limit=1000 as a protective filter, so that we retrieve more than the number of results. Placing limits on SQL queries tends to speed up result processing. In this case one record is returned:
anomolies <- SparkR::sql("select distinct
a.outcome,pressure,mean_pressure,age,b.mean_age,
(age- b.mean_age) as agediff
from bin_extract a inner join bin_agg b
on a.outcome=b.outcome
AND
(a.pressure > mean_pressure + (1.5*std_pressure))
OR
(a.pressure < mean_pressure - (1.5*std_pressure))
OR
(a.age < b.mean_age - (1.5*std_age))
OR
(a.age > mean_age + (1.5*std_age))
order by agediff desc
limit 1000")
head(anomolies)

The output shows only one record with an age 1.5 standard deviations higher than the average. You can customize the cutoff standard deviation to increase or decrease the number of rows returned for the purposes of outlier inspection.

You can change to the SQL interface by coding %sql on the first line. That allows all subsequent code statements in that particular notebook cell to be interpreted as SQL only.

If you wish to return to another language in a subsequent cell, enter %r, %python, %scala, and so on as the first line of the cell. If you do not enter one of these magic directives, it will be interpreted in the syntax of the default notebook type (in this case, R).

Here is the version of the count sample_bin query that we performed earlier in R, but now purely in the SQL interface. The results are shown as a pivot table. If you wish, you can manipulate the format by selecting the raw data icon (the first one on the left, below the data), or by selecting the Plot icon (the second one after that), and choosing a specific plot:

%sql
SELECT sample_bin , count(*) as k FROM out_tbl group by sample_bin order by k

The SQL window allows us to utilize all of the benefits of standard SQL. That includes the ability to create new columns. In this example, we query the entire table and compute the average mass split by high mass (>30), and low mass (<-30).

In this way, we can see that the mean mass is higher at the upper end for diabetes patients than for the non-diabetes patients. The same seems to be true at the low end:

%sql
select case when mass > 30 then "BMI_HIGH" else "BMI_LOW" end as BMICAT,
outcome,avg(mass) from out_tbl
group by 1,2

Splitting age at the 30 breakpoint also shows many more outcomes at the higher age range than at the lower:

Interesting comparisons can be made, purely using SQL, by calculating the coefficient of variation for all of the variables, and grouping by outcome. A coefficient of variation is a way in which we can standardize the means and variances of the variables and thus be able to disregard scale when making comparisons:

%sql
select outcome,
mean(pregnant)/std(pregnant),
mean(glucose)/std(glucose),
mean(pressure)/std(pressure),
mean(triceps)/std(triceps),
mean(insulin)/std(insulin),
mean(mass)/std(mass),
mean(pedigree)/std(pedigree),
mean(age)/std(age)
from out_tbl
group by 1
  1. After the query is done, switch to the plot window, and change the plot type to line chart.
  2. Then drag the outcome to the Keys pane.
  3. Then drag all of the other variables to the Values pane.

A simple line graph will appear, which will allow you to compare the average values of these variables between both of the outcomes.

We can see that the mean values of the variables increase for diabetic patients, although the magnitude of changes is larger for some variables than for others:

We can also demonstrate a query similar to the outlier query in the previous section. This time, we will be querying all records that have age or pressure records that fall above two standard deviations over the mean:

%sql
select distinct a.outcome,pressure,mean_pressure,age,mean_age from bin_extract a inner join bin_agg b
on a.outcome=b.outcome
AND
(a.pressure > mean_pressure + (2*std_pressure))
OR
(a.age > mean_age + (2*std_age))
limit 100

It will often be the case that some of the analysis you wish to perform will not be available within SparkR and you will need to extract some of the data from Spark objects, and return them to base R.

For example, we were able to run correlation and covariance functions earlier directly on a Spark dataframe, by specifying specific pairs of variables. However, we did not generate correlation matrices for the entire dataframe for a couple of reasons:

  • The capability to do this may not be built into the version of Spark that you are currently running
  • Even if it was available, these kinds of calculation could be very computationally expensive to perform

One strategy you may want to use is to use Spark functions to explore basic characteristics of the data, and/or utilize specialized packages written for Spark (such as MLlib) to perform this.

For other cases, in which you want to perform more in-depth analysis, simply extract a sample from the Spark dataframe, and perform the analysis using normal R dataframes. When doing this, it is good practice not to return the entire population, but only to return a sample or a subsegment. After all, if you extract the entire dataframe from Spark, you do not really need to use Spark in the first place, and might as well perform the whole analysis using local R!

We can use the collect() function to perform this, by first filtering by sample_bin and then returning the results to a local dataframe named samp. If you run a str() function on samp, you can see that the first line of the output indicates that the object is a normal R dataframe, and NOT a Spark dataframe:

#bring a sample back to R and visualize
samp <- SparkR::collect(SparkR::filter(out_sd, "sample_bin >= -50 and sample_bin <= 50"))
str(samp)

Once you have extracted your sample, you can run normal R functions such as pairs to generate a correlation matrix, or use the reshape2 package along with ggplot to generate a correlation plot.

#this takes our "collect()" data frame which we exported from Spark, and runs a basic correlation matrix
pairs(samp[,3:8], col=samp$outcome)

Here is a more sophisticated visualization which uses ggplot to illustrate how to generate a correlation matrix using shading to indicate the degree of correlation for each of the intersecting variables. Again, the point is to emphasis that you can perform analysis outside of Spark if your sample size is reasonable, and the exact functionality you need is not available in the version of Spark you are running.

require(ggplot2)
library(reshape2)
cormatrix <- round(cor(samp),2)
cormatrix_melt <- melt(cormatrix)
head(cormatrix_melt)
ggplot(data = cormatrix_melt, aes(x=Var1, y=Var2, fill=value)) + geom_raster()

Take a look at the following tips:

  • Sample when possible. Use the sample_bin methodology and filter command liberally. Sampling will speed up analysis both for the analysis phase and for the development/testing phase.
  • Once testing has been completed on a smaller segment, it can be scaled up to a much larger population with confidence.
  • Preprocess the data so that you can subselect potentially interesting sub segments.
  • Cache analysis when it makes sense.
  • If performance becomes a factor, try a larger number of partitions in your data.
  • For larger number crunching, bring back a representative sample to local R.

In this chapter, we learned the basics of exploring Spark data, using some Spark-specific commands that allowed us to filter, group, and summarize our Spark data.

We also learned about the ability to visualize data directly in Spark, along with learning how to run R functions such as ggplot against data.

We learned about some strategies for working with Spark data, such as performing intelligent filtering and sampling.

Finally, we demonstrated that often we need to extract some Spark data back into local R if we want the flexibility to use some of our usual tools that may not be supplied natively in the Spark environment.

In the next chapter, we will delve into the various predictive models that you can use that are specific to large datasets.