PivotalR: A Package for Machine Learning on Big Data

PivotalR is an R package that provides a front-end to PostgreSQL and all PostgreSQL-like databases such as Pivotal Inc.’s Greenplum Database (GPDB) (Pivotal Inc., 2013a), HAWQ (Pivotal Inc., 2013b). When running on the products of Pivotal Inc., PivotalR utilizes the full power of parallel computation and distributive storage, and thus gives the normal R user access to big data. PivotalR also provides the R wrapper for MADlib. MADlib is an open-source library for scalable in-database analytics. It provides data-parallel implementations of mathematical, statistical and machine-learning algorithms for structured and unstructured data. Thus PivotalR also enables the user to apply machine learning algorithms onto big data.


Introduction
In recent years, Big Data has become an important research topic and a very realistic problem in industry. The amount of data that we need to process is exploding, and the ability of analyzing big data has become the key factor in competition. Big data sets do not fit into computer's memory and it would be really slow if the big data sets were processed sequentially. On the other hand, most contributed packages of R are still strictly sequential, single machine, and they are restricted to small data sets that can be loaded into memory. As computing shifts irreversibly to parallel architectures and big data, there is a risk for the R community to become irrelevant. Some efforts have been invested into developing packages that give R users and developers the access to some of the parallel distributive platforms. Some examples include dplyr (Wickham and Francois, 2013), RHadoop (Revolution Analytics Company, 2012) (including plyrmr, rmr, rhdfs, rhbase), RHIPE (Guha et al., 2012), RHive (NexR, 2013), teradataR (Teradata Corporation, 2012) etc.
In this paper we introduce the package PivotalR (Pivotal Inc., 2013d), which provides an R front-end with data.frame oriented API for R users to access big data stored in distributive databases or Hadoop distributive file system (HDFS) (The Apache Software Foundation, 2013). In this sense, PivotalR is close to the still under development dplyr package, which has a data.frame oriented API and multiple back-ends including several SQL database systems. PivotalR puts more emphasis on machine learning by providing a wrapper for MADlib (Pivotal Inc., 2013c), which is an open-source library of scalable in-database machine learning algorithms. Actually PivotalR offers more than what MADlib has. It adds functionalities that do not exist in MADlib, for example, the support for categorical variables. PivotalR makes it easier to work on big data sets in databases.
This package is especially useful for users who are not familiar with SQL language, because the functions and syntax for the manipulation of tables are very similar to those for data.frame manipulation defined natively in R. Thus the learning curve for the package is very smooth. PivotalR is also very useful for users who are familiar with SQL language, because it brings the graphical and analytical functionalities of R to the processing of big data stored in databases.
PivotalR is contributed to the open-source community by the Predictive Analytics Team at Pivotal Inc. In order to gain the power of distributive storage and parallel computation, the users need to have a distributive database system installed, for example the Greenplum Database or HAWQ. PivotalR also supports the open-source database system PostgreSQL. Therefore PivotalR benefits R users by providing an easy-to-access interface for manipulating data tables stored in PostgreSQL database system and a combination of the powers of R and MADlib, which lets the user directly apply machine learning algorithms onto the big data stored in databases.
It is worth mentioning that PivotalR provides the access to data stored on HDFS by supporting HAWQ (Pivotal Inc., 2013b), which is the SQL query engine on HDFS created by Pivotal Inc.
The user does not need to worry about the restriction of memory size even if the data size is very big, because PivotalR minimizes the amount of data transferred between the database and R. The user manipulates the data from R but the data itself stays in the database.
The work flow of using PivotalR is the following. First, the user uses "db.connect" to connect to a database. Then, "db.data.frame" can be used to create a wrapper for a data table in the database. Minimal information about the table is kept in the wrapper, and no data is loaded into the memory. The user can easily operate on the "db.data.frame" wrapper object and any operation creates a "db.Rquery" object, which is just a wrapper for a series of operations and contains a SQL query string (see the section of Manipulation of Data Tables in Database). During this data preparation step, no data is loaded. In the next step, the user can either call "lookat" function to view a sample of the operation result, or call one of the MADlib wrapper functions to execute a machine learning algorithm. Both choices initiates computation in the connected database. Usually the computation result is small and can be loaded into memory for further processing. In some cases, the result is also big, for example, the MADlib wrapper for ARIMA produces the residuals for each row of the data. In such cases, a table is created in the database to store the result and a wrapper is automatically created in R, and the user can use the same work flow to analyze the result table.
From the above work flow, one can see that all the actual computation is done in the database. So the performance depends on the database. For the Greenplum database or HAWQ, all computation is done in a parallel and distributive way. Especially the MADlib machine learning functions are all implemented to fully utilize the parallel and distributive power of the databases. There are some operations that cannot be done in a parallel way, for example the ordered aggregate, but they have not been implemented in PivotalR yet. For the Postgres database, even though the computation is not in parallel, the user can still use PivotalR to easily access the data stored in the database, which might be too big to load into memory. Actually the performance on Postgres is not bad at all. In our performance tests in Postgres database, PivotalR's ARIMA wrapper function for MADlib is faster than R's own "arima" function when applied onto large data sets.
It is worth mentioning that the Greenplum database (GPDB) (Pivotal Inc., 2013a) has a community edition, which is free (but not open-source) and has all the functionalities except the technical support from Pivotal Inc.
At the time of writing, the version of PivotalR on CRAN is 0.1.8.
In this paper, we briefly introduce the usage of PivotalR. First in the next section we explain the architecture of PivotalR. Then we use various examples to illustrate the usage and work flow of PivotalR.

Architecture of PivotalR
As is shown in Fig. 1, PivotalR connects to the database through the RPostgreSQL (Conway et al., 2013) package. However, PivotalR does not directly call the functions in RPostgreSQL. Instead we create an abstraction layer to wrap the functions of RPostgreSQL, and the access to the database is done by calling the functions in the abstraction layer, which then call the functions in RPostgreSQL. This design makes it easier to add supports for other data storage platforms in the future. Right now, PivotalR only supports the connection to PostgreSQL, GPDB (Greenplum Database) and HAWQ. Through HAWQ, PivotalR can access the big data stored on HDFS.
In the future, PivotalR will add supports to other DBMS, Pivotal HD (Hadoop created by Pivotal Inc.) and Hadoop (MapReduce), but we have not decided about how to do that. This is why there are question markers in Fig. 1.
The layers that are built upon the table operations are the MADlib function wrappers and other functions, which will be covered in the subsequent sections.
A graphical user interface using the shiny (RStudio Inc., 2013) package is also implemented. Right now it only provides the graphical interface to the MADlib wrapper functions, but we have the plan to provide the graphical access to all functionalities of PivotalR in the future.
It is worth explaining more about how PivotalR operates on the tables. Before everything, the user needs to create a "db.data.frame" object, which is just a wrapper of the table. Any operation on this object is translated into an SQL query string. However, the SQL query is not executed at this point, and is instead stored in an object of class "db.Rquery" in R. When the user wants to execute the operation, he can call the function "preview" or "lookat" (or a shorthand "lk") to execute the operation and load part or all of the results into memory to view. The user can also choose to use "as.db.data.frame" to execute the SQL query and save the result into a new table. This design gives the user the freedom to choose when to load data into memory or create tables to store intermediate data in the process of a calculation. It also avoids the risk of accidentally loading big data into memory.
In order to realize the above design, we use a class hierarchy shown in Fig. 2. PivotalR uses S4 object-oriented programming extensively. All objects that are related to the data in the database Figure 1: The structure of PivotalR. PivotalR accesses the data storage through an abstraction layer which wraps the functions that can directly access the database. Other types of data storages will be supported in the future. Right now it only supports connections to PostgreSQL, GPDB and HAWQ. Table operations functions are built upon the data accessing layer. They have the exact same interface as R's "data.frame" operation functions. MADlib function wrappers and other functions are built upon the table operations. The graphical user interface makes the package easier to use. belong to subclasses of an abstract class named "db.object".

Figure 2:
The class hierarchy of PivotalR. This is not a UML figure. The square blocks represent the S4 classes. The arrows represent the conversion between the classes. The dashed arrows represent the various operations that convert the classes. The MADlib wrapper functions and preview/lookat function operate on both db.data.frame class and db.Rquery class.
As has been mentioned, the class "db.data.frame" is a wrapper of data objects stored in the connected database. When it is created by the command "db.data.frame", no actual data stored in the data table in the database is transferred from the database to R. This object just contains some basic information about the data object in the database, such as dimensions and column names. "db.data.frame" has two sub-classes, "db.table" and "db.view", which are wrappers for tables and views respectively.
> library(PivotalR) > conn.id <-db.connect(port = 14526, dbname = "madlib", host = + "localhost") Created a connection to database with ID 1 > x <-db.data.frame("abalone") The command "db.connect" in the abstraction layer is used to connect to one or multiple databases. It has an optional parameter that lets the user select which package he wants to use to connect to the databases, although only RPostgreSQL is supported right now. The returned value of "db.connect" is an integer which represents the database connection. PivotalR can connect to multiple databases at the same time. Thus it is possible to train a machine learning model using the data from database 1 and then make predictions using the data from database 2. One can use "db.disconnect" to disconnect a connection and "db.list" to list all active connections.
Any operation on an object of the class "db.data.frame" produces an object of the class "db.Rquery". An object of the class "db.Rquery" resides entirely on the R side, and is a wrapper of operations on a "db.data.frame" object. Most operations on a "db.Rquery" object produces another "db.Rquery" object. Essentially, a "db.Rquery" object is just a container of a string of SQL query, which can be viewed using the command "content". The command "as.db.data.frame" creates a table in the database using the results of the SQL query contained in a "db.Rquery" object and then creates a "db.data.frame" wrapper that points to this table.
"preview" (or its alias "lookat" and "lk") transfers the data from the database into R's memory. By default it fetches 100 rows of data from the table in the database and convert the data into "data.frame" in R. The MADlib wrappers can be applied onto both "db.data.frame" and "db.Rquery" objects. When a MADlib wrapper function is applied onto a "db.Rquery" object, a temporary table is created using as.db.data.frame. MADlib is an in-database library and we have to convert "db.Rquery" into an object inside the database so that we could apply MADlib functions onto it. This temporary table is dropped after the computation is done.
The design of PivotalR minimizes the amount of data that needs to be transferred between the database and R. The only function that transfers data from the database is "preview.
As long as a "key" is specified when the user calls "db.data.frame" function, the syntax A[3,4] can be used. Here the first number "3" means that the key column has the value of 3. Therefore, lk(A[3,4],-1) may return multiple values. This is different from the behavior of "data.frame", where A[3,4] returns the element on 3-rd row and 4-th column. This difference is related to the lack of intrinsic order in the database tables, which will be discussed in the following.
The operations on "db.obj" objects mimic those on "data.frame". However, there is important difference between "db.obj" and "data.frame".
The rows of a "data.frame" object have an intrinsic order, which makes the operations that involve two "data.frame" objects easier to define. For example, it is straightforward to define the subtraction of two columns of two different "data.frame" objects by matching the order of the rows as long as they have the same number of rows.
On the other hand, the tables in the database do not have an intrinsic order for the rows. Thus, most operations like subtraction, addition etc. can only be defined for columns belonging to the same table. However, this is usually not a problem. Whenever the user wants to do an operation that involves two tables, he/she should first call the function "merge" to create a new table (actually a "db.Rquery" object) from the two tables and at the same time explicitly specify how to match the rows of the two different tables. Then, the user can easily do operations on the new table. While R's "data.frame" implicitly uses the intrinsic order of the rows to match the rows from two different data.frames, this needs to be explicitly done for "db.data.frame" objects. For example, > x <-db.data.frame("abalone") > y <-db.data.frame("abalone") > z <-merge(x, y, by = NULL) # cross join two tables > names(z) [1] "id_x" "sex_x" "length_x" "diameter_x" "height_x" [6] "whole_x" "shucked_x" "viscera_x" "shell_x" "rings_x" [11] "id_y" "sex_y" "length_y" "diameter_y" "height_y" [16] "whole_y" "shucked_y" "viscera_y" "shell_y" "rings_y" > z$sex_x == z$sex_y # This is a db.Rquery object The data frame 'abalone' is lazy-loaded in PivotalR. It is used as an example data here. One can use as.db.data.frame to transfer this data set into a table in the database and at the same time create a wrapper for the table > x <-as.db.data.frame(abalone, conn.id=1) The data in the data.frame abalone is stored into the table in database madlib on localhost ! All the subsequent operations will be applied onto the table wrapper x. A sample of the data is shown in the following, where sort is used to create a sorting operation on the original table. At last, I want to reiterate that all these operations done on "db.data.frame" are not executed immediately. Instead a "db.Rquery" object is produced. The user can convert it into a real table using as.db.data.frame.

MADlib Wrapper Functions
In the next, we show some examples of MADlib wrapper functions. As is shown in Fig. 2, all MADlib wrapper functions can be applied onto "db.obj" objects. Because the connection information is already contained in "db.obj" objects, we do not need to specify "conn.id" in the MADlib wrapper functions.
First, we show several examples of linear regression. Basically, PivotalR's "madlib.lm" uses the same formula syntax as "lm". Because MADlib's linear regression supports fitting separate linear regression models on sub-groups of the data, which are grouped by one or multiple columns, "madlib.lm" allows "|" in the formula, which means that the model is fit on a subset of the data conditioned on the value of the variables after "|". > ## fit one different model to each group of data with the same sex > fit <-madlib.lm(rings~. -id | sex, data = x) sex has 3 distinct values, and thus fit is a list of 3 elements. Each element is the linear regression model for a subset of the data. The mean square error can be easily computed > ## apply the model onto data in another database > lookat(mean((x$rings -predict(fit, x))^2)) # mean square error rings_madlib_predict_opr_opr_avg 1 4.647291 We can plot a random sample of the fitting values together with the real values, as is shown in Fig. 3. We can also select one model from the fitting result to plot, as is shown in the comments of the following snippets.
> v <-x > v$sex <-as.factor(v$sex) # specify which column to pivot > f <-madlib.lm(rings~.   Because extractAIC method is implemented for the result of madlib.lm and madlib.glm, one can use R's step function for feature selection. fit <-madlib.glm(rings<10~., data = x, family = "binomial") step(fit) This is a good example of how R's analytical functionalities can be combined with MADlib.
In the next example, we use the bootstrap aggregate method to fit a linear model to the data.

Support for Array Columns
Both Greenplum database and Postgres database have an upper limit for the number of columns in a data table. The upper limit depends on the column data types, but is usually around 1600. If the big data set has more features, the only workaround is to use an array column to encapsulate all the features, because there is no limit for how many elements an array can contain.
PivotalR has the full support for such array columns, as is shown in the next example.

Handling of NULL Values
PivotalR makes it very easy to filter NULL values from a table. Here we show an example using the data "null.data" comes with PivotalR. 'null.data' has lots of NULL value. However, we can easily filter out all the NULL values.

Quickly Creating Prototypes of Machine Learning Algorithms
One of the goals of PivotalR is to help data scientists quickly create prototypes for parallel machine learning algorithms that can run in distributive databases. Although PivotalR is still at an early stage of development, we already invest some effort into this. The idea is to implement some basic operations that forms the build blocks for most machine learning algorithms.
For example, we implemented the function crossprod, which computes the operation X T Y. X and Y are wrappers created by "db.data.frame" for tables that represent matrices. X has m rows (observations) and n columns (features). The assumption here is that m can be very large but the number of features n is small. Thus results of X T X and X T Y are both small and can be loaded into memory for further calculations. The big data computation only involves the computations of X T X and X T Y in the database. Another example is the implementation of PCA for a matrix Z. Again we assume that the number of columns n is not large and the product Z T Z is small enough to be loaded into memory. PivotalR implements "scale", which is used together with crossprod in this example.  # table to speed up computation m <-lookat(crossprod(z)) # one scan of the table to compute Z^T * Z d <-delete(z) # delete the intermediate table res <-eigen(m) # only this computation is in R n <-attr(y, "row.number") # save the computation to count rows ## return the result list(val = sqrt(res$values/(n-1)), # eigenvalues vec = res$vectors, # columns of this matrix are eigenvectors center = attr(y, "scaled:center"), scale = attr(y, "scaled:scale")) } dat <-db.data.frame("madlibtestdata.pca_mat_600_100", conn.id = 2) q <-pca(dat[,-1])

GUI of PivotalR
As a front-end to both the database and MADlib, PivotalR also provides a graphical user interface (GUI) to let users that are not familiar with data science have an easy access to the functionalities. The GUI is written using the package shiny, which provides a very nice web application framework to create graphical user interface.
The GUI is launched by the command pivotalr after the connection to the databases have been created. Fig. 4 and Fig. 5 show the graphical user interface. Fig. 4 shows the screen shot for the summary of various properties for all columns of a table. The actual computation is done through MADlib's "summary" function, which has a wrapper function "madlib.summary" in PivotalR. Fig. 5 shows the computation result of linear regression. The actual computation is done through MADlib's linregr_train function, which has a wrapper function "madlib.lm".
The GUI of PivotalR is based upon the package shiny, which is a web application framework. Therefore the command pivotalr launches a web application. One can run the GUI on the server and connect to it using his web browser.
The GUI of PivotalR is still at its early development stage. Many functionalities, especially the various operations on data tables, cannot be done through GUI. However, we expect to improve the GUI gradually in the future releases.

Future Work
MADlib has a wide variety of machine learning functions. At the time of writing, the version of PivotalR on CRAN is 0.1.8, and it implements 5 wrapper functions: linear regression, logistic regression, ARIMA, elastic net regularization, and the data table summary function. In the future, all MADlib functions will have their wrappers in PivotalR. This is our highest priority right now.
As to the shiny interface of PivotalR, we are still exploring the possibilities of streamlining the machine learning work flow and making it compatible with a graphical interface. This by itself is a big project, but it has a lower priority in our road-map.
The support for other platforms, like Hadoop or other database systems, is also on our road-map, but has a relatively low priority too.