In this analysis we will use SparkR machine learning capabilities in order to try to predict property value in relation to other variables in the 2013 American Community Survey dataset. You can also check the associated Jupyter notebook. By doing so we will show the current limitations of SparkR’s MLlib and also those of linear methods as a predictive method, no matter how much data we have.
The whole point of R on Spark is to introduce Spark scalability into R data analysis pipelines. With this idea in mind, we have seen how SparkR introduces data types and functions that are very similar to what we are used to when using regular R libraries. The next step in our series of notebooks will deal with its machine learning capabilities. While building a linear model we want also to check the significance of each of the variables involved in building such a predictor for property value.
This article is part of our series on Introduction to Apache Spark with R that you can find on GitHub.
Creating a SparkSQL context and loading data
In order to explore our data, we first need to load it into a SparkSQL data frame. But first we need to init a SparkSQL context. The first thing we need to do is to set up some environment variables and library paths as follows. Remember to replace the value assigned to
SPARK_HOME with your Spark home folder.
Now we can load the
SparkR library as follows.
Attaching package: ‘SparkR’ The following objects are masked from ‘package:stats’: filter, na.omit The following objects are masked from ‘package:base’: intersect, rbind, sample, subset, summary, table, transform
And now we can initialise the Spark context as in the official documentation. In our case we are use a standalone Spark cluster with one master and seven workers. If you are running Spark in local node, use just
master='local'. Additionally, we require a Spark package from Databricks to read CSV files (more on this in the previous notebook).
Launching java with spark-submit command /home/cluster/spark-1.5.0-bin-hadoop2.6/bin/spark-submit --packages com.databricks:spark-csv_2.11:1.2.0 sparkr-shell /tmp/RtmpmF2Hmf/backend_port6c9817062e87
And finally we can start the SparkSQL context as follows.
Now that we have our SparkSQL context ready, we can use it to load our CSV data into data frames. We have downloaded our 2013 American Community Survey dataset files in notebook 0, so they should be stored locally. Remember to set the right path for your data files in the first line, ours is
Now let’s read into a SparkSQL dataframe. We need to pass four parameters in addition to the
- The file path.
csvfiles have a header with the column names.
- Indicate that we want the library to infer the schema.
- And the source type (the Databricks package in this case).
And we have two separate files for both, housing and population data. We need to join them.
Let’s check that we have everything there by counting the files and listing a few of them.
Preparing our data
We need to convert
ST (or any other categorical variable) from a numeric variable into a factor.
Additionally, we need either to impute values or to remove samples with null values in any of our predictors or desponse. For the response (
VALP) we will use just those samples with actual values.
Let’s count the remaining samples.
Preparing a train / test data split
We don’t have a split function in SparkR, but we can use
sample in combination with the
SERIALNO column in order to prepare two sets of IDs for training and testing.
Unfortunately SparkR doesn’t support negative %in% expressions, so we need to do this in two steps. First we add a flag to the whole dataset indicating that a sample belongs to the test set.
And then we use that flag to subset out the train dataset as follows.
However this approach is not very scalable since we are collecting all the test IDs and passing them over to build the new flag column. What if we have a much larger test set? Hopefully futre versions of SparkR will come up with a proper
Training a linear model
In order to train a linear model, we call
glm with the following parameters:
- A formula: sadly,
SparkR::glm()gives us an error when we pass more than eight variables using
+in the formula.
- The dataset we want to use to train the model.
- The type of model (gaussian or binomial).
This doesn’t differ much from the usual R
glm command, although right now is more limited.
The list of variables we have used includes:
RMSPor number of rooms.
ACRthe lot size.
INSPor insurance cost.
TAXPor taxes cost.
ELEPor electricity cost.
GASPor gas cost.
STthat is the state code.
REGIONthat identifies the region.
Sadly, the current version of
SparkR::summary() doesn’t provide significance starts. That makes model interpretation and selection very difficult. But at least we know how each variables influences a property value. For example, the Midwest region decreases property value, while the West increases it, etc. In order to interpret that we need to have a look at our data dictionary.
In any case, since we don’t have significance starts, we can iterate through adding/removing variables and calculating the R2 value. In our case we ended up with the previous model.
Evaluating our model using the test data
First of all let’s obtain the average value for
VALP that we will use as a reference of a base predictor model.
Let’s now predict on our test dataset as follows.
Let’s add the squared residuals and squared totals so later on we can calculate R2.
In regression, the R2 coefficient of determination is a statistical measure of how well the regression line approximates the real data points. An R2 of 1 indicates that the regression line perfectly fits the data.
A value of 0.41 doesn’t speak very well about our model.
We still need to improve our model if we really want to be able to predict property values. However there are some limitations in the current SparkR implementation that stop us from doing so. Hopefully these limitations won’t be there in further versions. Moreover, we are using a linear model, and the relationships between our predictors and the target variable might not be linear at all.
But right now, in Spark v1.5, the R machine learning capabilities are still very limited. We are missing a few things, such as:
- Accepting more than 8 variables in formulas using
- Having significance stars that help model interpretation and selection.
- Having other indicators (e.g. R2) in summary objects so we don’t have to calculate them ourselves.
- Being able to create more complex formulas (e.g. removing intercepts using 100 + …) so we don’t get negative values, etc.
- Although we have a
samplemethod, we are missing a
splitone that we can use to easier have train/test splits.
- Being able to use more powerful models (or at least models that deal better with non linearities), and not just linear ones.