Learning Models over Relational Data using Sparse Tensors and Functional Dependencies
Mahmoud Abo Khamis, Hung Q. Ngo, XuanLong Nguyen, Dan Olteanu, and Maximilian Schleich

TL;DR
This paper presents a unified framework and system for efficient relational data analytics using sparse tensors and functional dependencies, enabling faster and accurate statistical model training over databases.
Contribution
It introduces a theoretical framework combining database theory and linear algebra for structure-aware learning, and implements the AC/DC system demonstrating significant performance improvements.
Findings
AC/DC achieves comparable accuracy to existing tools.
AC/DC is up to 1000 times faster in typical applications.
AC/DC handles large datasets without memory or timeouts.
Abstract
Integrated solutions for analytics over relational databases are of great practical importance as they avoid the costly repeated loop data scientists have to deal with on a daily basis: select features from data residing in relational databases using feature extraction queries involving joins, projections, and aggregations; export the training dataset defined by such queries; convert this dataset into the format of an external learning tool; and train the desired model using this tool. These integrated solutions are also a fertile ground of theoretically fundamental and challenging problems at the intersection of relational and statistical data models. This article introduces a unified framework for training and evaluating a class of statistical learning models over relational databases. This class includes ridge linear regression, polynomial regression, factorization machines, and…
| Retailer | Favorita | Yelp | |
| Relations | 4 | 5 | 5 |
| Variables | 21 | 14 | 26 |
| Categorical Variables | 4 | 10 | 6 |
| Tuples in Database | 87M | 125M | 8.7M |
| Size of Database | 1.5GB | 2.5GB | 0.2GB |
| Tuples in Join Result | 86M | 125M | 360M |
| Size of Join Result | 18GB | 7GB | 40GB |
| #values in Listing Representation | 2.302G | 1.735G | 2.835G |
| #values in Factorized Representation | 166M | 372M | 71.9M |
| Compression ( Factorized/Listing ) | 13.91 | 4.66 | 39.43 |
| Retailer v1 | Retailer v2 | Favorita v1 | Favorita v2 | Yelp | ||
| Join Computation (PSQL) | 447.76 | 447.76 | 255.16 | 255.16 | 195.26 | |
| Factorized Computation of Count over Join | 19.90 | 19.90 | 36.45 | 36.45 | 21.07 | |
| Linear Regression | ||||||
| Features (continuous+categorical) | 16 + 49 | 16+3,661 | 4 + 482 | 4 + 4,482 | 21 + 1,068 | |
| Number of Entries in Sparse Tensor | 1,149 | 69,777 | 42,504 | 455,889 | 46,401 | |
| MADLib (ols) | Encode | 0.19 | 8.46 | 532.52 | 545.42 | 61.79 |
| Learn | 1,124.84 | 86,400.00 | 13,951.44 | 86,400.00 | 44,307.88 | |
| TensorFlow (ftrl) | Join+Shuffle+Export | 2,266.76 | 2,266.76 | 1,417.87 | 1,417.87 | 1,110.41 |
| (1 epoch, batch size 100K) | Learn | 3,420.91 | 3,408.34 | 3,649.73 | 3,648.52 | 5,763.88 |
| AC/DC | Aggregate | 40.09 | 118.47 | 115.02 | 1,022.44 | 42.89 |
| Converge | 0.11 | 285.92 | 0.94 | 22.20 | 0.14 | |
| Speedup of AC/DC over | MADlib | 27.99 | 1,031.13 | |||
| TensorFlow | 159.76 | |||||
| Polynomial Regression degree | ||||||
| Features (continuous+categorical) | 121+980 | 121+65,996 | 7+42,016 | 7+451,403 | 211+41,559 | |
| Number of Entries in Sparse Tensor | 72,790 | 2,517,600 | 498,641 | 6,616,551 | 6,478,164 | |
| MADlib (ols) | Encode | 0.19 | 8.46 | 532.52 | 545.42 | 61.79 |
| Learn | 86,400.00 | 86,400.00 | 86,400.00 | 86,400.00 | 86,400.00 | |
| AC/DC | Aggregate | 122.88 | 334.35 | 324.99 | 7,549.99 | 3,650.47 |
| Converge | 21.92 | 621.69 | 45.34 | 1,063.88 | 203.64 | |
| Speedup of AC/DC over | MADlib | |||||
| Factorization Machine degree rank | ||||||
| Features (continuous+categorical) | 107+980 | 107+65,996 | 5+42,016 | 5+451,403 | 192+41,559 | |
| Number of Entries in Sparse Tensor | 70,515 | 2,465,443 | 497,786 | 6,607,696 | 6,454,053 | |
| libFM (MCMC) | Join+Ex/Import+Encode | 3,368.06 | 3,368.06 | 3,214.79 | 3,214.79 | 2,719.48 |
| (300 iterations) | Learn | 86,400.00 | 86,400.00 | 86,400.00 | 86,400.00 | 67,829.59 |
| AC/DC | Aggregate | 124.17 | 324.492 | 351.68 | 7,856.88 | 3,633.93 |
| (300 iterations) | Converge | 0.67 | 42.74 | 2.60 | 25.38 | 265.94 |
| Speedup of AC/DC over | libFM | |||||
Peer Reviews
No public reviews on file for this paper yet. If you reviewed it on a platform where reviews are public (OpenReview, ICLR, NeurIPS, ICML), you can paste yours below so the community can read it here.
Videos
No videos yet. Explain this paper in a talk, walkthrough, or lecture? Add one.
\xpatchcmd→
[1]\boldsymbol{}{#1}$
Learning Models over Relational Data using Sparse Tensors and Functional Dependencies
Mahmoud Abo Khamis
RelationalAI, Inc
Hung Q. Ngo
RelationalAI, Inc
XuanLong Nguyen
University of Michigan
Dan Olteanu
University of Oxford
Maximilian Schleich
University of Oxford
Abstract
Integrated solutions for analytics over relational databases are of great practical importance as they avoid the costly repeated loop data scientists have to deal with on a daily basis: select features from data residing in relational databases using feature extraction queries involving joins, projections, and aggregations; export the training dataset defined by such queries; convert this dataset into the format of an external learning tool; and train the desired model using this tool. These integrated solutions are also a fertile ground of theoretically fundamental and challenging problems at the intersection of relational and statistical data models.
This article introduces a unified framework for training and evaluating a class of statistical learning models over relational databases. This class includes ridge linear regression, polynomial regression, factorization machines, and principal component analysis. We show that, by synergizing key tools from database theory such as schema information, query structure, functional dependencies, recent advances in query evaluation algorithms, and from linear algebra such as tensor and matrix operations, one can formulate relational analytics problems and design efficient (query and data) structure-aware algorithms to solve them.
This theoretical development informed the design and implementation of the AC/DC system for structure-aware learning. We benchmark the performance of AC/DC against R, MADlib, libFM, and TensorFlow. For typical retail forecasting and advertisement planning applications, AC/DC can learn polynomial regression models and factorization machines with at least the same accuracy as its competitors and up to three orders of magnitude faster than its competitors whenever they do not run out of memory, exceed 24-hour timeout, or encounter internal design limitations.
1 Introduction
Although both disciplines of databases and statistics occupy foundational roles for the emerging field of data science, they are largely seen as complementary. Most fundamental contributions made by statisticians and machine learning researchers are abstracted away from the underlying infrastructure for data management. However, there is undoubtedly clear value in tight integration of statistics and database models and techniques. This is receiving an increasing interest in both academia and industry [2, 42, 61]. This is motivated by the realization that in many practical cases data used for training resides inside relational databases and bringing the analytics closer to the data saves non-trivial time usually spent on data import/export at the interface between database systems and statistical packages [38]. A complementary realization is that large chunks of statistical machine learning code can be expressed as relational queries and computed using database techniques [27, 43, 66, 24].
The problem of solving analytics over databases naturally lends itself to a systematic investigation using the toolbox of concepts and techniques developed by the database theorist, and by synergizing ideas from both relational and statistical data modeling. One can exploit database schema information, functional dependencies, state-of-the-art query evaluation algorithms, and well-understood complexity analysis.
Contributions
Our conceptual contribution is the introduction of a framework for training and evaluating a class of statistical learning models over relational databases. This class, commonly used in retail-planning and forecasting applications [11], includes ridge linear regression, polynomial regression, factorization machines, and principal component analysis. In such applications, the training dataset is the result of a feature extraction query over the database. Typical databases include weekly sales data, promotions, and product descriptions. A retailer would like to compute a parameterized model, which can predict, for instance, the additional demand generated for a given product due to promotion [50]. The feature extraction query is commonly a natural join of the database relations, yet it may join additional relations derived from the input ones using aggregation. The features correspond to database attributes, their categorical values, or aggregates over them. As is prevalent in practical machine learning, the models are trained using a first-order optimization algorithm such as batch or stochastic gradient descent, in part because their convergence rates are dimension-free (for well-behaved objectives). This is a crucial property given the high-dimensionality of our problem as elaborated next.
The main computational challenge posed by analytics over databases is the large number of records and of features in the training dataset. There are two types of features: continuous (quantitative) such as price and sales; and categorical (qualitative) such as colors, cities, and countries.111Most of the raw features we observed in datasets for retail applications are categorical. In several domains, such as statistical arbitrage [45], it is common to derive many continuous features from categorical features. While continuous features allow for aggregation over their domains, categorical features cannot be aggregated together. To accommodate the latter, the state-of-the-art approach is to one-hot encode their active domain: each value in the active domain of an attribute is encoded by an indicator vector whose dimension is the size of the domain. For instance, the colors in the domain can be represented by indicator vectors for red, for green, and for blue. The one-hot encoding amounts to a relational representation of the training dataset with one new attribute per distinct category of each categorical feature and with wide tuples whose values are mostly 0. This entails huge redundancy due to the presence of the many 0 values. The one-hot encoding also blurs the usual distinction between schema and data, since the schema can become as large as the input database.
Closely related to the computational challenge is a cultural challenge: the feasibility of a tight integration of analytics and databases may be called into question. In terms of pure algorithmic performance, why would such an approach be more efficient than the common approach that decouples the computation of the training dataset from the learning task, given the widely available plethora of tools and techniques for the latter?
Our answer to these challenges is that, for a large class of feature extraction queries, it is possible to train a model in time sub-linear in the output size of the feature extraction query! This makes our approach competitive regardless of the learning techniques used by the mainstream approaches that first materialize the training dataset, including those that use sampling and stochastic gradient descent to only process a subset of the training dataset.
More concretely, our approach entails three database-centric technical contributions.
First, we exploit join dependencies and their factorization in the training dataset to asymptotically improve the per-iteration computation time of a gradient descent algorithm.
Second, we exploit functional dependencies present in the database to reduce the dimensionality of the underlying optimization problem by only optimizing for those parameters that functionally determine the others and by subsequently recovering the functionally determined parameters using their dependencies.
Third, we address the shortcomings of one-hot encoding by expressing the sum-product aggregates used to compute the gradient and point evaluation as functional aggregate queries (FAQs) [8]. The aggregates over continuous features are expressed as FAQs without free (i.e., group-by) variables and their computation yields scalar values. In contrast, aggregates over categorical features originating from a set of database attributes are expressed as FAQs with free variables . The tuples in the result of such FAQs are combinations of categorical values that occur in the training dataset. The ensemble of FAQs defining the gradient form a sparse tensor representation and computation solution with lower space and time complexity than solutions based on one-hot encoding. In particular, the complexity of our end-to-end solution can be arbitrarily smaller than that of materializing the result of the feature extraction query.
The above three technical contributions led to the design and implementation of AC/DC, a gradient descent solver for polynomial regression models and factorization machines over databases. To train such models of up to 66K features over the natural join of all relations from a real-world dataset of up to 86M tuples, AC/DC needs up to 15 minutes on eight cores of a commodity machine. AC/DC is up to 1,031 times faster than its competitors MadLib [38], libFM [64], and TensorFlow [1] whenever they do not exceed memory limitation, 24-hour timeout, or internal design limitations.
Figure 1 depicts schematically the workflows of our approach and the mainstream approach for solving optimization problems. The mainstream approach materializes the result of the feature extraction query, exports it out of the database and imports it as the training dataset in the ML tool, where the desired model is learned. We call it structure-agnostic since it does not exploit the relational structure of the underlying training dataset to avoid learning over the full materialization of the training dataset. In contrast, our structure-aware approach avoids this materialization and has the following steps: (1) it defines a set of aggregates needed to compute the gradient of the objective function for the desired model; (2) it optimizes these aggregates over the feature extraction query and under dependencies holding in the database and join dependencies defined by the feature extraction query; (3) it computes these aggregates in bulk using factorization techniques and exploiting subexpressions common among them; and (5) it uses a gradient descent solver to compute the model parameters based on the computed aggregates.
This article brings together and extends two lines of our prior work: The theoretical development of model reparameterization under functional dependencies and of factorized learning [5] and a preliminary report on the design and implementation of AC/DC [4]. The extensions concern the treatment of PCA, simplified proof for model reparameterization under functional dependencies, different experiments, and a classification of the existing landscape of structure-aware versus structure-agnostic approaches to analytics.
Organization
The structure of the paper follows our contributions. Section 2 introduces preliminary notions needed throughout the article. Section 3 describes our unified framework for structure-aware analytics. Section 4 introduces our sparse tensor representation and computation approach for square loss problems (learning polynomial regression models and factorization machines) and principal component analysis together with its complexity analysis. Section 5 shows how to exploit functional dependencies to reduce the dimensionality of learned models. Section 6 discusses the design and implementation of the AC/DC system for learning models over relational databases. Section 7 presents our experimental findings. Section 8 overviews several strands of related work. Finally, Section 9 lists promising directions for future work. Further preliminaries and proofs of some theorems are deferred to the electronic appendix.
2 Preliminaries
We use the following notational conventions: bold face letters, e.g., , , , , denote vectors or matrices, and normal face letters, e.g., , , , denote scalars. For any positive integer , denotes the set . For any set and positive integer , denotes the collection of all -subsets of . Let be a finite set and Dom be any domain, then is a tuple indexed by , whose components are in Dom. If and are disjoint, and given tuples and , the tuple is interpreted naturally as the tuple .
The tuple is the all-[math] tuple indexed by . If , then the tuple is the characteristic vector of the subset , i.e., if , and [math] if .
2.1 Feature Extraction Query
We consider the setting where the training dataset used as input to machine learning is the result of a query called feature extraction query, over a relational database . This query is typically the natural join of the relations in the database. It is also common to join in further relations that are derived from the input relations by aggregating some of their columns. These further relations provide derived features, which add to the raw features readily provided by the input relations.
We use standard notation for query hypergraphs. Let denote the hypergraph of the join query , where is the set of variables occurring in and is the set of hyperedges with one hyperedge per set of variables in a relation symbol in the body of . We denote by the subset of variables selected as features, and let . The features in corresponding to qualitative attributes are called categorical, while those corresponding to quantitative attributes are continuous. Let be the size of the largest input relation in . Each tuple contains a scalar response (regressand) and a tuple encoding features (regressors).
Example 1**.**
Consider the following natural join query that is a simplified version of a feature extraction query:
[TABLE]
Relation Sales records the number of units of a given sku (stock keeping unit) sold at a store on a particular day. The retailer is a global business, so it has stores in different cities and countries. One objective is to predict the number of blue units to be sold next year in the Fall quarter in Berlin. The response is the continuous variable , is the set of all variables, and , all of which are categorical except and .∎
2.2 Matrix calculus
We introduce basic concepts of matrix calculus and the following operations: the Kronecker/tensor product ; the Hadamard product ; the Khatri-Rao product ; and the Frobenius inner product of two matrices , which reduces to the vector inner product when the matrices have one column each. We defer further preliminaries on matrix calculus to Appendix A and connection of tensor computation and the FAQ framework [8] to Appendix B.
Basics
We list here common identities we often use in the paper; for more details see the Matrix Cookbook [60]. We use denominator layout for differentiation, i.e., the gradient is a column vector. Let be a matrix, and be vectors, where and are independent of , and and are functions of then
[TABLE]
The Product Cookbook: Tensor product, Kronecker product, and Khatri-Rao product
Next, we discuss some identities regarding tensors. We use to denote the tensor product. When taking tensor product of two matrices, this is called the Kronecker product, which is not the same as the outer product for matrices, even though the two are isomorphic maps. If is an matrix and is a matrix, then the tensor product is an matrix whose entry is . In particular, if is an -dimensional vector and is an -dimensional vector, then is an -dimensional vector whose entry is ; this is not an matrix as in the case of the outer product. This layout is the correct layout from the definition of the tensor (Kronecker) product. If is matrix, then denote the tensor power .
Definition 1** (Tensor product).**
Let and be tensors of order and respectively, i.e., functions and . The tensor product is the multilinear function
[TABLE]
A matrix is a tensor of order .
Definition 2** (Khatri-Rao product).**
Let and be two matrices each with columns. We use to denote the matrix with columns, where the th column of is the tensor product of the th column of with the th columns of . The operator is a (special case of) the Khatri-Rao product [40], where we partition the input matrices into blocks of one column each. More elaborately, if has columns , and has columns ,then one can visualize the operator as follows:
[TABLE]
(Note and do not need to have the same number of rows.)
Definition 3** (Hadamard product).**
Let and be two matrices, then the Hadamard product is an matrix, where each element is given by .
3 Problem formulation
This section introduces a general formulation for a range of machine learning tasks and then lays out a versatile mathematical representation suitable for the in-database treatment of these tasks.
3.1 Continuous features
We start with a standard formulation in machine learning, where all model features are numerical.
The training dataset , which is defined by a feature extraction query over a relational database, consists of tuples of a feature vector and a response .
In case of continuous features, is the vector of raw input features, or equivalently the variables in the feature extraction query. We denote by the vector of so-called parameters. Let be an integer. We define feature and parameter maps as follows.
The feature map transforms the raw input vector into an -vector of “monomial features” . Each component is a multivariate monomial designed to capture the interactions among dimensions of input . In particular, we write , where degree represents the level of participation of input dimension in the -th monomial feature.
The parameters produce the coefficients associated with features via parameter map , . Each component is a multivariate polynomial of .
A large number of machine learning tasks learn a functional quantity of the form , where the parameters are obtained by solving with
[TABLE]
is a loss function, e.g., square loss, and is a regularizer, e.g., - or -norm of . For square loss and -regularization, becomes:
[TABLE]
Example 2**.**
The ridge linear regression (LR) model with response and regressors has , parameters . For convenience, we set corresponding to the bias parameter . Then, , , and . The inner product becomes and Equation (7) becomes ∎
Example 3**.**
The degree- polynomial regression () model with response and regressors has parameters , where is a tuple of non-negative integers such that . In this case, , while the components of are given by .∎
Example 4**.**
In contrast to polynomial regression models, factorization machines [65] factorize the space of model parameters to better capture data correlations. The degree- rank- factorization machines () model with regressors and regressand has parameters consisting of for and for and . Training corresponds to minimizing the following :
[TABLE]
This loss function follows Equation (7) with , , and the maps
[TABLE]
∎
Example 5**.**
Classification methods such as support vector machines (SVM), logistic regression and Adaboost also fall under the same optimization framework, but with different choices of loss and regularizer . Typically, . Restricting to binary class labels , the loss function , where , takes the form for SVM, for logistic regression and for Adaboost.∎
Example 6**.**
Various unsupervised learning techniques can be expressed as iterative optimization procedures according to which each iteration is reduced to an optimization problem of the generic form given above. For example, the Principal Component Analysis (PCA) requires solving the following optimization problem to obtain a principal component direction
[TABLE]
where is the (empirical) correlation matrix of the given data. Although there is no response/class label , within each iteration of the above iteration, for a fixed , there is a loss function acting on feature vector and parameter vector , along with a regularizer . Specifically, we have , , , where the Frobenius inner product is now employed. In addition, .∎
3.2 Categorical features
The active domain of a categorical feature/variable is a set of possible values or categories, e.g., vietnam, england, and usa are possible categories of the categorical feature country. Categorical features constitute the vast majority of features we observed in machine learning applications.
It is common practice to one-hot encode categorical variables [36]. Whereas a continuous variable such as salary is mapped to a scalar value , a categorical variable such as country is mapped to an indicator vector – a vector of binary values indicating the category that the variable takes on. For example, if the active domain of country consists of vietnam, england, and usa, then . If a tuple in the training dataset has country = “england”, then for that tuple.
In general, the feature vector has the form , where each component is an indicator vector if is a categorical variable and a scalar otherwise. Similarly, each component of the parameter vector becomes a matrix, or a vector if the matrix has one column.
3.3 Tensor product representation
We accommodate both continuous and categorical features in our problem formulation (7) by replacing arithmetic product by tensor product in the component functions of the parameter map and the feature map . Specifically, monomials now take the form
[TABLE]
with degree vector . For each , the set consists of features that participate in the interaction captured by the (hyper-) monomial . Let denote the set of categorical variables and the subset of categorical variables in . For , represents many monomials, one for each combination of the categories, where denotes the projection of onto variable . Due to one-hot encoding, each element in the vector for a categorical variable is either [math] or , and for . Hence, can be simplified as follows:
[TABLE]
Note that we use instead of boldface since each variable is continuous.
Example 7**.**
For illustration, consider a query that extracts tuples over schema from the database, where country and color are categorical variables, while are continuous variables. Moreover, there are two countries vietnam and england, and three colors red, green, and blue in the training dataset . Consider three of the possible feature functions:
[TABLE]
Under the one-hot encoding, the schema of the tuples becomes:
[TABLE]
Equation (9) says that the functions and are actually encoding functions:
[TABLE]
∎
We elaborate the tensor product representation for the considered learning models.
Example 8**.**
In linear regression, parameter is a vector of vectors: . Since our inner product is Frobenius, when computing we should be multiplying, for example, with correspondingly. ∎
Example 9**.**
In polynomial regression, the parameter is a vector of tensors (i.e., high-dimensional matrices). Consider for instance the second order term . When both and are continuous, is just a scalar. Now, suppose is country and is color. Then, the model has terms , , and so on. All these terms are captured by the Frobenius inner product . The component is a matrix whose number of entries is the number of pairs (country, color) that appear together in some tuple in the training dataset. This number can be much less than the product of the numbers of countries and of colors in the input database.∎
Example 10**.**
Consider the model from Example (4), but now with categorical variables. From the previous examples, we already know how to interpret the linear part of the model when features are categorical. Consider a term in the quadratic part such as . When and are categorical, the term becomes ∎
4 Database-centric problem reformulation
In this section, we show how we reformulate the square loss optimization problems (learning polynomial regression and factorization machine models) and PCA to encode their data-intensive components as FAQs. The ensemble of these FAQs form a sparse tensor representation and computation solution with lower space and time complexity than solutions based on one-hot encoding.
4.1 Solution for square loss problems
We introduce our approach to learning statistical models for the setting of square loss function and -norm as in (7). We use a gradient-based optimization algorithm that employs the first-order gradient information to optimize the loss function . It repeatedly updates the parameters by some step size in the direction of the gradient \mbox{\boldmath\nabla}J(\vec{\theta}) until convergence. To guarantee convergence, it uses backtracking line search to ensure that is sufficiently small to decrease the loss for each step. Each update step requires two computations: (1) Point evaluation: Given , compute the scalar ; and (2) Gradient computation: Given , compute the vector \mbox{\boldmath\nabla}J(\vec{\theta}). In particular, we use the batch gradient descent (BGD) algorithm with the Armijo line search condition and the Barzilai-Borwein step size adjustment [14, 28], as depicted in Algorithm 1. Quasi-Newton optimization algorithms (e.g., L-BFGS) and other common line search conditions are also applicable in our framework. We refer the reader to the excellent review article [31] for additional details on fast implementations of gradient-descent optimization methods.
Continuous features
We first consider the case without categorical features. We rewrite the square-loss function (7) to factor out the data-dependent part of the point evaluation and gradient computation. Recall that, for , denotes the th component function of the vector-valued function , and is a multivariate monomial in .
Theorem 4.1**.**
Let be the function in (7). Define the matrix , the vector , and the scalar by
[TABLE]
Then,
[TABLE]
Note that is a matrix, and is an matrix. Statistically, is related to the covariance matrix, to the correlation between the response and the regressors, and to the empirical second moment of the response variable. Theorem 4.1 allows us to compute the two key steps of BGD without scanning through the data again, because the quantities can be computed efficiently in a preprocessing step inside the database as aggregates over the feature extraction query .
Example 11**.**
Consider the query in Example 1, where the set of features is {sku, store, day, color, quarter, city, country, , } and unitsSold is the response variable. In this query , and thus for a model we have parameters. Consider two indices and to the component functions of and , where and . Then we can compute the entry with the following SQL query:
[TABLE]
∎
When is the identity function, i.e., the model is linear, as is the case in PR (and thus LR) model, (16) and (17) become particularly simple:
Corollary 4.2**.**
In a linear model (i.e., ),
[TABLE]
Let \mathbf{d}=\mbox{\boldmath\nabla}J(\vec{\theta}). Then,
[TABLE]
The Armijo condition becomes:
[TABLE]
The significance of (21) is as follows. In a typical iteration of BGD, we have to backtrack a few times (say times) for each value of . If we were to recompute using (18) each time, then the runtime of Armijo backtracking search is , even after we have already computed and . Now, using (21), we can compute in advance the following quantities (in this order): , , , , , , . Then, each check for inequality (21) can be done in -time, for a total of -times. Once we have determined the step size , (20) allows us to compute the next gradient (i.e., the next ) in , because we have already computed for line search.
To implement BGD, we need to compute four quantities efficiently: the matrix in (13), the vector in (14), point evaluation in (16), and the gradient in (17). The covariance matrix and the correlation vector only have to be computed once in a pre-processing step. The gradient is computed at every iteration, which includes several point evaluations as we perform line search.222In our implementation, each iteration typically involves - backtracking steps. We do not need to compute the second moment because optimizing is the same as optimizing . Before describing how those four quantities can be computed efficiently, we discuss how we deal with categorical features.
Categorical features via sparse tensors
The more interesting, more common, and also considerably challenging situation is in the presence of categorical features. We next explain how we accommodate categorical features in the computation of and .
Example 12**.**
In Example 7, the matrix is of size instead of after one-hot encoding. However, many of those entries are [math], for instance ():
[TABLE]
The reason is that the indicator variables and act like selection clauses and . More concretely, we can rewrite the entry as an aggregate over a more selective query. For instance, the entry that corresponds to the product of functions and from Example 7 can be rewritten as follows:
[TABLE]
where .∎
Extrapolating straightforwardly, if we were to write down in the one-hot encoded feature space, then the entries under one-hot encoding got unrolled into many entries. Let and be the set of categorical variables for and as defined in Section 3.3. Then, is in fact a tensor of dimension , because
[TABLE]
Similarly, each component of defined in (14) is a tensor of dimension , because is a tensor in the categorical case. The following follows immediately.
Theorem 4.3**.**
Theorem 4.1 remains valid even when some features are categorical.
Note that the outer product in (22) specifies the matrix layout of , and so is a block matrix, each of whose blocks is . Furthermore, if we were to layout the tensor as a vector, we can also write it as
[TABLE]
The previous example demonstrates that the dimensionalities of and can be very large. Fortunately, the tensors are very sparse, and a sparse representation of them can be computed with functional aggregate queries (in the FAQ-framework [8]) as shown in Proposition 4.4 below. We next illustrate the sparsity.
Example 13**.**
We extend the Example 11 for entries in Sigma with categorical variables. Consider two indices and to the component functions of and , where and . Suppose the query result states that the retailer has stores in countries. Then, the full dimensionality of the tensor is , because by definition it was defined to be
[TABLE]
Recall that and are both indicator vectors. The above tensor has the following straightforward interpretation: for every triple , where is a store and and are cities, this triple entry of the tensor counts the number of data points for this particular combination of store and cities (divided by ). Most of these -entries are [math]. For example, if then the count is zero. Thus, we can concentrate on computing entries of the form :
[TABLE]
Better yet, since store functionally determines city, the number of entries in the query output is bounded by . Using relations to represent sparse tensor results in massive space saving.
We can also succinctly represent entries in that are composed of continuous and categorical variables. Consider the entry that corresponds to dimensions and . We can compute this entry with the following SQL query:
[TABLE]
∎
4.2 Solution for Principal Component Analysis
We next consider principal component analysis (PCA) over the training dataset defined by a feature extraction query. We focus on the problem of computing the top- principal components, which correspond to the eigenvectors of the covariance matrix. Once computed, the principal components are then used to transform the data to a lower dimensional space. We show that the solution to this problem requires similar computations as our solution for square loss problems in Section 4.1.
Continuous features
We first consider the case with continuous features only. Let be the vector of means for each variable in the feature extraction query, and the centered covariance matrix. The top- eigenvectors and the corresponding eigenvalues can be computed one at a time using the min-max theorem based on the Rayleigh quotient [67]:
[TABLE]
We compute the optimal solution for the top eigenvector using a gradient-based optimization algorithm, which optimizes the following loss function by alternating between performing gradient ascent with respect to and gradient descent with respect to until convergence:
[TABLE]
The gradient optimization steps can then be done with Algorithm 1, where the gradient of for the two subproblems is given by:
[TABLE]
The subsequent eigenvectors are computed with the same optimization procedure but over an updated covariance matrix that subtracts all previously computed principal components. The iteration step assumes we already computed the covariance matrix , the eigenvector , and the eigenvalue for . The step then computes the eigenvector and the eigenvalue over the covariance matrix
[TABLE]
Once we computed the top- eigenvectors , the projection of a training sample onto the lower -dimensional space is given by the inner product .
As for the square-loss problems, we can compute once, and then compute the eigenvectors without scanning the data again. If the data is centered in a preprocessing step, then the computation of for PCA is identical to (13) for the case of linear regression. If the data is not centered, we can compute the covariance matrix with the following reformulation:
[TABLE]
Thus, we can compute the covariance matrix by first computing the matrix from (13) where and then subtracting to center the data.
The gradient with respect to for PCA requires the same computation over as the gradient for linear regression models (c.f. (19)).
Categorical features via sparse tensors
PCA is based on the analysis of variance between variables, and therefore it cannot be computed directly over categorical data. It can however be meaningful to compute PCA over one-hot encoded categorical data, which would provide insights into the variance of the frequency of the co-occurrence of categories for different categorical variables. We can compute PCA over one-hot encoded categorical variables efficiently by computing it over the sparse representation of the covariance matrix, which is a variant of the sparse tensor representation of the matrix that we introduced for the case of square-loss problems.
One difference between the square loss problems and PCA is that PCA requires its features to be linearly independent. This property is not satisfied by one-hot encoding, because it is possible to derive the indicator value for one category based on a linear combination of the indicator values for all other categories. For this reason, it is common practice to do one-hot encoding of the categorical variables for all but one category. In our problem formulation, this means that for a categorical variable , we encode the corresponding component as an indicator vector whose size is the number of its categories minus one, so that we one-hot encode over all but the last category of . This encoding is often referred to as dummy encoding in many data science tools.
Another difference is the requirement to center the data. For categorical data, it is not desirable to center the data in a preprocessing step, as this would require a one-hot encoding of the input relations. To avoid the materialization of the one-hot encoding, we compute the non-centered matrix first, and then subtract , as shown in (30). The sparse representation of the covariance matrix is then a block matrix, where each entry is defined as:
[TABLE]
The vector of means has the same dimension as , where for each categorical variable the component is the vector of frequencies for all but one category in the domain of :
[TABLE]
The vector can be computed efficiently as a SQL count query with group-by variable . We drop the group with the lowest count and divide the count for each other group by .
The resulting matrix has the same structure as the sparse tensor that is computed for linear regression problems. In fact, the quantity in (31) is simply the centered variant of the expression in (22) for the case where . The centering of the as well as updating the matrix for subsequent eigenvectors can be expressed as group-by aggregate queries and computed without materializing the quantities and .
Example 14**.**
Consider the entry where and . We can compute the centered entry in the covariance matrix based on the non-centered entry and the frequency vectors for store and city. The non-centered entry is computed with the SQL query in Example 13,
Let and be the relational encoding of the frequency vectors for store and respectively city. The relations store tuples that give for each city and respectively store the corresponding frequency that is denoted by val. We can then compute the entry in the centered covariance matrix without materializing the product of and with the following SQL query:
[TABLE]
Let and be the relational encodings of the components in that correspond to store and respectively city. We can compute the updated entry based on (29) without materializing the product of and with the following query:
[TABLE]
∎
The eigenvectors and eigenvalues can be computed on top of the sparse representation of the covariance matrix without touching the input database, and the gradient with respect to the eigenvectors requires similar computation as the gradient for square loss problems. We next show how we can compute the sparse tensor representation.
4.3 Efficient computation of the sparse tensor representation
We consider the problem of computing the sparse tensor representation for a given optimization problem. For square-loss problems the sparse tensor captures the quantities and , and for PCA we compute the non-centered covariance matrix (referred to as for uniformity), which is then centered in a subsequent step as shown in Example 14.
An immediate approach to computing this representation is to first materialize the result of the feature extraction query using an efficient query engine, e.g., a worst-case optimal join algorithm, and then compute the entries in the representation as aggregates over the query result. This approach, however, is suboptimal, since the listing representation of the query result is highly redundant and not necessary for the computation of the aggregates.
We employ two orthogonal observations to avoid this redundancy.
First, we use the FAQ [8] and FDB [55] frameworks for factorized computation of aggregates over joins. In a nutshell, factorized aggregate computation unifies three powerful ideas: worst-case optimal join processing, query plans defined by fractional hypertree decompositions of join queries, and pushing aggregates past joins.
Second, we exploit the observation that in the computation of many distinct tensors have identical sparse representations. For instance, the tensor from Example 13 corresponding to and has the same sparse representation as any of the following tensors: . This is because store and city are categorical features and taking any power of the binary values in their indicator vectors does not change these values. Furthermore, any of the two features can be in and/or .
The time complexity of computing the representation can be lower than that of materializing the result of the feature extraction query . Let denote the size (i.e., number of tuples) of the sparse representation of the tensor. Let denote the FAQ*-width* of the FAQ-query333We show in the proof of Proposition 4.4 in Appendix D how to express and as FAQ-queries. that expresses the aggregate over ; fhtw be the fractional hypertree width of ; and be the fractional edge cover number 444Due to space limitation, these width notions are defined in Appendix C. of . Let be the input database and . Let be the size of the largest input relation in , which means that . Recall that is the set of query variables in , is the set of relations in , and is the number of features. The time to compute the sparse tensor representation can be bounded as follows.
Proposition 4.4**.**
The tensors and can be sparsely represented by FAQ-queries with group-by variables and , respectively. They can be computed in time
[TABLE]
In case all features in are continuous, i.e., for all , then [8] and the overall runtime becomes . When some features are categorical, we can also bound the width and tensor size.
Proposition 4.5**.**
Let be the maximum number of categorical variables for any . Then, and , .
For any query with , there are infinitely many database instances for which
[TABLE]
Our precomputation step takes strictly sub-output-size runtime for infinitely many queries and database instances. If we were to compute on a training dataset with categorical variables one-hot encoded, then the complexity would raise to , where is the degree of the polynomial regression model or factorization machine.
4.4 Point evaluation and gradient computation
We introduce two ideas for efficient point evaluation and gradient computation.
First, we employ a sparse representation of tensors in the parameter space. We need to evaluate the component functions of , which are polynomial. In the example, for instance, we evaluate expressions of the form
[TABLE]
The result is a -way tensor whose CP-decomposition (a sum of rank- tensors) is already given by (34)! There is no point in materializing the result of and we instead keep it as is. Assuming distinct cities and distinct stores in the training dataset , if we were to materialize the tensor, then we would end up with an -sized result for absolutely no gain in computational and space complexity, while the space complexity of the CP-decomposition is only . This is a prime example of factorization of the parameter space.
Second, we explain how to evaluate (16) and (17) with our sparse tensor representation. The same techniques can also be applied to evaluate (26) and (27) for PCA. There are two aspects of our solution worth spelling out: (1) how to multiply two tensors, e.g., and , and (2) how to exploit that some tensors have the same representation to speed up the point evaluation and gradient computation.
To answer question (1), we need to know the intrinsic dimension of the tensor . In order to compute in Example 13, we need to multiply with for and . In a linear model, . In this case, when computing we marginalize away one city dimension of the tensor, while keeping the other two dimensions store, city. This is captured by the following query:
[TABLE]
where the tensors and map and respectively to aggregate values. In words, is computed by a group-by aggregate query where the group-by variables are precisely the variables in .
For question (2), we use the CP-decomposition of the parameter space as discussed earlier. Suppose now we are looking at the tensor where and . Note that this tensor has the identical representation as the above tensor, but it is a different tensor. In a model, we would want to multiply this tensor with the component function defined in (34) above. We do so by multiplying it with each of the terms , one by one for , and then add up the result. Multiplying the tensor with the first term corresponds precisely to the following query:
[TABLE]
where the tensors , , and map , , and respectively to aggregate values. Finally, to answer question (2), note that for the same column (i.e., the same component function ), there can be multiple tensors which have identical sparse representations. (This holds especially in models of degree .)
In such cases, we have queries for point evaluation and gradient computation with identical from-where blocks but different select-group-by clauses, because the tensors have different group-by variables. Nevertheless, all such queries can share computation as we can compute the from-where clause once for all of them and then scan this result to compute each specific tensor. This analysis gives rise to the following straightforward (and conservative) estimates.
For each , let denote the degree and denote the number of terms in the polynomial (a component function of ). Recall that is the number of parameters.
Proposition 4.6**.**
Point evaluation (16) and gradient computation (17) can be computed in time , and respectively .
The times for point evaluation and gradient computation are: and respectively for the model; and respectively for the model; and and respectively for PCA. Recall that the case for PCA is similar to that of LR, or equivalently .
Overall, there are a couple of remarkable facts regarding the overall runtime of our approach. Without loss of generality, suppose the number of iterations of BGD is bounded. (This bound is typically dimension-free, dependent on the Lipschitz constant of .) Then, from Proposition 33, there are infinitely many queries for which the overall runtime of BGD is unboundedly better than the output size. First, our approach is faster than even the data-export step of the mainstream approach that uses an external tool to train the model. Second, it is often well-agreed upon that SGD is faster than BGD. However, a single iteration of SGD requires iterating through all data tuples, which takes time at least the output size. In particular, by training the model using BGD in the factorized form, BGD can be unboundedly faster than a single iteration of SGD.
4.5 Diagram of our structure-aware approach revisited
Figure 2 refines Figure 1 and depicts key ideas behind the performance improvements of our structure-aware framework over structure-agnostic learning approaches.
In structure-agnostic learning, a query engine takes the input relations (of size ) and joins them into a potentially much larger output relation of size , which might in turn get blown up even more inside the machine learning tool. In our structure-aware framework, the input query, the input relations, and function are first translated into FAQ [8], which is a language that is suitable for aggregate query specification and optimization. In particular, each entry (and ) of our target matrix (and vector ) is expressed as the answer to an FAQ query (or ). All those queries are fed into an FAQ query optimizer. The optimizer factorizes each query into small sub-queries and solves them individually. Each sub-query results in a relation of size , which can be much smaller than the size of the data matrix . By solving the FAQ queries , we obtain and , which are all that is needed as input for the convergence step in a batch gradient descent solver.
5 FD-Aware Optimization
In this section, we show how to exploit functional dependencies among variables to reduce the dimensionality of the optimization problem by eliminating functionally determined variables and re-parameterizing the model. We compute the quantities (, ) on the subset of features that are not functionally determined, and then solve the lower-dimensional optimization problem. Finally, we recover the parameters in the original space in closed form. Exploiting functional dependencies drastically reduces the computation time for (, ) and the gradient.
5.1 Introduction to the main ideas
Consider a query with categorical variables country and city. For simplicity, assume that there are only two countries “vietnam” and “england”, and cities “saigon”, “hanoi”, “oxford”, “leeds”, and “bristol”. Under one-hot encoding, the corresponding features are encoded as indicators , , , , , , . Since city country is a functional dependency (FD), for a given tuple in the training dataset, the following hold:
[TABLE]
The first identity states that if a tuple has “vietnam” as the value for country (), then its value for city can only be either “saigon” or “hanoi”, i.e., is either or , respectively. The second identity is explained similarly.
How do we express the identities such as (35) and (36) in a formal manner in terms of the input vectors and ? We can extract in a preprocessing step from the database a relation of the form with city as primary key. Let and be the number of cities and countries, respectively. The predicate is the sparse representation of a matrix of size , such that if is an indicator vector for saigon, then is an indicator for vietnam. In this language, identities (35) and (36) can written simply as . For example, in the above particular example , , and
[TABLE]
This relationship suggests a natural idea: replace any occurrence of statistics by its functionally determining quantity . Since these quantities are present only in the loss function via inner products , such replacements result in a (typically) linear reparameterization of the loss. What happens next is less obvious, due to the presence of the nonlinear penalty function . Depending on the specific structure of FDs and the choice of , many parameters associated with redundant statistics, which do not affect the loss , can be optimized out directly with respect to the transformed penalty.
The remainder of this subsection is a gentle introduction of our idea in the presence of one simple FD in the LR model. Consider a query in which city and country are two of the categorical features and functionally determine one another via a matrix such that for all . We exploit this fact to “eliminate” as follows.
[TABLE]
Define a new parameter vector (note that there is no ), and two functions , :
[TABLE]
Then, we can reparameterize in terms of by
[TABLE]
Note how has disappeared from the loss term, but it still remains in the penalty term. We now “optimize out” by observing that
[TABLE]
By setting (41) to [math] we obtain in terms of :
[TABLE]
where is the order- identity matrix and similarly for . We can thus express and its gradient completely in terms of :
[TABLE]
(Appendix E.1 contains formal proofs of the above claims.) The gradient of the loss term is computed using the matrix and the vector with respect to the pair of reduced dimensionality. The matrix is a rank- update to the identity matrix , strictly positive definite and thus invertible. The inverse can be obtained using database aggregate queries; for numerical stability, one may compute its Cholesky decomposition which can also be expressed by aggregate queries. These “linear algebra via aggregate queries” computations are possible because our matrices admit a database interpretation, cf.Section 5.6.
5.2 Functional dependencies (FDs)
Composite FDs lead to more complex identities. For instance, the FD (guest, hotel, date) room leads to the identity . Let be a relation on attributes guest, hotel, date, and room, encoding this dependency, i.e., has a compound key . Then, corresponding to there is a matrix of dimension for which . Our results can be extended to the case of composite FDs, yet with a great notational burden; for the sake of clarity, we only state the results for simple FDs.
Definition 4**.**
An FD is simple if its left-hand side is one variable.
Let a query in which there are disjoint groups of features, among other features. The th group is , where is a feature, a set of features, and is an FD. We shall refer to these as groups of simple FDs.
Example 15**.**
In a typical feature extraction query for retailer customers, we have groups (in addition to other features): the first group contains week month quarter year, and thus = week and = month, quarter, year . In the second group, = sku and type, color, size, … (a rather large group). In the third group store and city, country, region . ∎
For each feature , let denote the matrix for which . For the sake of brevity, we also define a matrix (the identity matrix of dimension equal to the active domain size of attribute ), so the equality holds for every .
The linear relationship holds even if the variables are not categorical. For example, consider the FD sku price (assuming every stock-keeping unit has a fixed sale-price). The relationship is modeled with a matrix , where the entry corresponding to a sku is its price. Then, for any indicator vector .
Definition 5** (FD-reduced pairs of functions).**
Given a pair of functions and in our problem setting. Recall that ’s are defined in Section 3.3, while ’s are given in Definition 4. Define
[TABLE]
( is the set of component functions of containing at least one functionally determined variable.)
The group of simple FDs induces an FD-reduced pair of functions and as follows: The component functions of are obtained from the component functions of by removing all component functions for . Similarly, is obtained from by removing all component functions for which . Naturally, define the covariance matrix and the correlation vector as in (13) and (14), but with respect to .
We next generalize the above technique to speedup the training of and FaMa under an arbitrary collection of simple FDs.
5.3 Polynomial regression under FDs
Recall the -model formulated in Example 3. Consider the set of all tuples of non-negative integers such that . For any and , define In the model we have , , and . If a feature, say , is non-categorical, then . If we knew , then and thus there is no need to have terms for which . A similar situation occurs when is a categorical variable. To see this, let us consider a simple query where , and all four variables are categorical. Suppose the model has a term corresponding to . The term of indexed by tuple is of the form
[TABLE]
For the dimensionality to match up, is a 3rd-order tensor, say indexed by . The above expression can be simplified as
[TABLE]
where the equality holds due to the fact that is idempotent. In particular, we only need the entries indexed by of . Equivalently, we write:
[TABLE]
Multiplying on the left by the matrix has precisely the same effect as selecting out only entries from the tensor . More generally, in the model we can assume that all the indices satisfy the condition that whenever is categorical. (This is in addition to the degree requirement that .)
Given groups of FDs represented by , let , , , , and . For every non-empty subset , define . Given a natural number , and a non-empty set with size , define the collection
[TABLE]
For every tuple with and every , define the following matrices, which play the same role as in Section 5.1:
[TABLE]
Note that the matrices can be further factorized as each of its terms is a tensor product, but we refrain from doing so here to avoid heavy notational complexity in the proofs and the theorem statement. See (96) and (97) in the appendix for examples of what we mean by factorization of these matrices. The following theorem reparameterizes for () to become . While is a vector indexed by tuples , the new parameters are indexed by integer tuples .
Theorem 5.1**.**
Let the -model with parameters , and groups of simple FDs , . Define the reparameterization:
[TABLE]
Then, minimizing is equivalent to minimizing the function
[TABLE]
where
[TABLE]
(Recall and from Definition 5.)
The proof of this theorem (Appendix E.2) is technically involved. is defined above with respect to the FD-reduced pair of functions and a reduced parameter space of . Its gradient is simple to compute, since
[TABLE]
Moreover, once a minimizer of is obtained, we can compute a minimizer of by setting
[TABLE]
Theorem 5.1 might be a bit difficult to grasp at first glance due to its generality. To give the reader a sense of how the theorem is applied in specific instances, Appendix E.4 and E.5 present two specializations of the theorem for (ridge) linear regression (), and degree-2 polynomial regression ().
5.4 Factorization machines under FDs
We now turn our attention to .
Theorem 5.2**.**
Consider the FaMa model of degree , rank , parameters and groups of simple FDs , . Let ,
[TABLE]
and the following reparameterization:
[TABLE]
Then, minimizing is equivalent to minimizing the function where
[TABLE]
(Recall , and from Definition 5.)
In order to optimize with respect to , the following proposition provides a closed form formulae for the relevant gradient.
Proposition 5.3**.**
The gradient of defined in (53) can be computed using , and
[TABLE]
Then,
[TABLE]
Suppose that the minimizer of has been obtained, then a minimizer of is available in closed form:
[TABLE]
This section shows that our technique applies to a non-linear model too. It should be obvious that a similar reparameterization works for for any . There is some asymmetry in the reparameterization of st-order parameters and nd-order parameters in Theorem 5.2, because we can solve a system of linear equation with matrix inverses, but we don’t have closed form solutions for quadratic equations.
5.5 Principal Component Analysis under FDs
In this section, we show how to exploit functional dependencies to reduce the number of dimensions of the input to PCA by computing the top- eigenvectors and eigenvalues over the lower dimensional covariance matrix without the functionally determined features. We show that the eigenvalues of the lower dimensional problem are identical to those of the original problem, while the original eigenvectors can be derived from the solution to the lower dimensional problem.
Recall the functional dependencies of the form , the sets of functionally determined variables and of all other variables, as in Section 5.2. Also, recall that each is an -dimensional vector, and for each categorical variable , the component is an indicator vector.
We define to be the vector of size , which is obtained by removing all components from that correspond to functionally determined variables (i.e., all for which ). Similar to (30) and (32), we can express the -dimensional vector of means and the covariance matrix over :
[TABLE]
The covariance matrix can be computed directly over the input database as in Example 14. The effect of computing a covariance matrix over instead of is that its sparse tensor representation does not require the computation of any aggregate over a functionally determined variable.
For each functionally determined variable , the FD induces a mapping from a component in to a component in . We define to be the rank- matrix of all such mappings, so that and each index maps to . For a variable , let be its domain size if is categorical or one otherwise. Take two such variables and . Then, if the entry is the identity matrix . If and there is no functional dependency between them, then the entry is the matrix of zeros. In case there is a functional dependency , the entry is the matrix that encodes this functional dependency. For instance, in case and , the entry is the matrix whose entries are one if the -th city is located in the -th country, or zero otherwise (as exemplified in (37) in Section 5.1, and generalized as matrices in Section 5.2). We can compute a sparse representation of the matrix as a collection of group-by queries over the input relations, and without materializing the result of the feature extraction query.
The following lemma shows that the eigenvalues of the covariance matrix are preserved under FDs while the eigenvectors are subject to a simple transformation.
Lemma 5.4**.**
For some , let be the top- (positive-valued) eigenvalues of matrix and be the corresponding eigenvectors. Then are also the top- eigenvalues of . Moreover, the eigenvectors of are
[TABLE]
Proof.
First note that and . For any eigen-pair of , it holds by definition. Thus, . Multiplying both sides by to the left, we obtain . Hence, is an eigen-pair of . Since is full-ranked, the set of positive eigenvalues of is identical to that of . Moreover, let be any of the eigen-pairs of in which , then the corresponding eigenvector of may be obtained by the identity: , which yields . This gives to conclude the proof. ∎
5.6 Linear algebra with database queries
To apply the above results, we need to solve several computational primitives. The first primitive is to compute the matrix inverse and its product with another vector. This task can be done by either explicitly computing the inverse, or computing the Cholesky decomposition of the matrix . We next explain how both of these tasks can be done using database queries.
Maintaining the matrix inverse with rank- updates
Using Sherman-Morrison-Woodbury formula [35], we can incrementally compute the inverse of the matrix as follows. Let be some subset and suppose we have already computed the inverse for . We now explain how to compute the inverse for . For concreteness, let the matrix map city to country. For each country country, let denote the -vector where there is a for each city the country has. For example, Then, And thus, starting with , we apply the Sherman-Morrison-Woodbury formula for each country, such as:
[TABLE]
This update can be done with database aggregate queries, because is a sum of entries in where both and are cities in cuba; is the sum of columns of corresponding to cuba; and is exactly .
Overall, each update (56) can be done in -time, for an overall runtime of . This runtime should be contrasted with Gaussian-elimination-based inverse computation time, which is . When the FDs form a chain, the blocks are nested inside one another, and thus each update is even cheaper as we do not have to access all entries.
Maintaining a Cholesky decomposition with rank- update
Maintaining a matrix inverse can be numerically unstable. It would be best to compute a Cholesky decomposition of the matrix, since this strategy is numerically more stable. There are known rank- update algorithms [30, 23], using strategies similar to the inverse rank- update above. A further common computational primitive is to multiply a tensor product with a vector, such as in (also expressible as aggregate queries).
5.7 Discussion
Diagram of our structure-aware learning in the presence of FDs
Figure 3 depicts the enhancements that we introduce to our framework in order to take advantage of FDs in the input database instance and reduce our previous runtime even further (but still compute the same as before).
As explained earlier, computing each entry of the matrix and of the vector requires solving an FAQ query. However, by utilizing FDs we can filter out many of those entries as unneeded for later stages, thus significantly reducing the number of FAQ queries that we have to solve. After the filtering process, and shrink down to and , which we compute and feed to gradient-descent (GD). We also filter the function down to and feed the latter to GD. Now, we run GD in the space of (instead of the original higher-dimensional space of ). During each iteration of GD, in order to compute the objective function and its gradient \mbox{\boldmath\nabla}\overline{J}(\vec{\gamma}), we need to use the matrices that represent the functional dependencies. And after GD finishes, we have to convert the resulting optimal solution back into the original space to get . Such conversion also requires the FD-matrices .
Impact of FDs on model complexity
The prevalence of FDs presents new challenges from both computational and statistical viewpoints. On the one hand, a reasonable and well-worn rule of thumb in statistics dictates that one should always eliminate features that are functionally dependent on others, because this helps reduce both computation and model’s complexity, which in turn leads to reduced generalization error (as also noted in [44]). On the other hand, the statistical effectiveness of such a rule is difficult to gauge when the nature of dependence goes beyond linearity. In such scenarios, it might be desirable to keep some redundant variables, but only if they help construct simpler forms of regression/classification functions, leading to improved approximation ability for the model class.
It is, however, difficult to know a priori which redundant features lead to simple functions. Therefore, the problem of dimensionality reduction cannot be divorced from the model class under consideration. While this remains unsolved in general, in this work we restricted ourselves to specific classes of learning models, the complexity of which may still be varied through regularization via (non-linear) penalties. Within a regularized parametric model class, we introduced dimensionality reduction techniques (variable elimination and re-parameterization) that may not fundamentally change the model’s capacity. The reduction in the number of parameters may still help reduce the variance of parameter estimates, leading to improved generalization error guarantees.
Impact of FDs on computational complexity
Model reparameterization under FDs does not lower the data complexity from Proposition 4.4 for the computation of the sparse tensor representation. Under a simple FD , the number of categories of the functionally determined categorical variable cannot exceed that of the functionally determining categorical variable . This means that by avoiding the computation of aggregates involving , the data complexity for the computation of the sparse tensor representation with both and is the same as with only.
Computing less aggregates means however a reduction in the query complexity. In case only variables functionally determine the entire set of variables, the dimensionality of for is , which is much smaller than the dimensionality of . This reduction can be significant: In one of our experiments with on the Retailer dataset v4, there is a reduction from 46M to 36M entries in the sparse tensor representation of and . Proposition E.1 in Appendix E.3 provides the corresponding version of Corollary 21 with respect to .
This reduction in the query complexity comes at a price: The gradient solver has a new data-dependent computation in the regularizer. For instance, under the functional dependency used in Section 5.1, where is a matrix that maps between cities and countries in the input database. Computing this linear algebra expression takes time as explained in Section 5.6, where and are the number of cities (categories for the city categorical feature) and respectively countries. Assuming these quantities are small, the reduction in the number of aggregates vastly dominates the modest increase in the complexity of the additional linear algebra expression. Figure 7 in Section 7 indeed shows that using one single functional dependency for Retailer leads to a performance speedup.
6 The Design and Implementation of AC/DC
In this section, we present the design of AC/DC, which is our implementation of the algorithms and optimizations for the end-to-end computation of square loss problems presented in the previous sections. AC/DC computes each entry in the sparse tensor representation of the problem as an aggregate over the feature extraction join query, following the SQL encoding developed in previous sections, e.g., Examples 11 and 13. Two key optimizations used by AC/DC for the computation of these aggregates are: (1) Factorized computation of aggregates over the feature extraction query, with low complexity (Section 6.1); and (2) Massively shared computation across the aggregates (Section 6.2). AC/DC also exploits functional dependencies to reduce the dimensionality of the problem. By design, AC/DC does not achieve the complexity bound from Proposition 4.4. This is because it would need different query plans for different subsets of the aggregates. Instead, it uses one query plan for all these aggregates. This increases the opportunity to share computation across the aggregates, which proved much more beneficial for the overall performance.
6.1 Factorized aggregate computation
Factorized aggregate computation relies on a variable order for the query to avoid redundant computation. In this paper, we assume that we are given a variable order. Prior work discusses the query optimization problem of finding good orders [13, 8].
Variable Orders. State-of-the-art query evaluation uses relation-at-a-time query plans. We use variable-at-a-time query plans, which we call variable orders. These are partial orders on the variables in the query, capture the join dependencies in the query, and dictate the order in which we solve each join variable. For each variable, we join all relations with that variable. Our choice is motivated by the complexity of join evaluation: Relation-at-a-time query plans are provably suboptimal, whereas variable-at-a-time query plans can be chosen to be optimal [53].
For a query , a variable depends on a variable if both are in the schema of a relation in .
Definition 1** (adapted from [56]).**
A variable order for a join query is a pair , where is a rooted forest with one node per variable in , and is a function mapping each variable to a set of variables in . It satisfies the following constraints:
- •
For each relation in , its variables lie along the same root-to-leaf path in .
- •
For each variable , is the subset of its ancestors in on which the variables in the subtree rooted at depend.
Without loss of generality, we use variables orders that are trees instead of forests. We can convert a forest into a tree by adding to each relation the same dummy join variable that takes a single value. For a variable in the variable order , is the set of all ancestor variables of in . The set of variables in (schema of a relation ) is denoted by ( respectively) and the variable at the root of is denoted by .
Example 16**.**
Figure 6(a) shows a variable order for the natural join of relations , , and . Then, and , i.e., has ancestors and , yet it only depends on . Given , the variables and are independent of each other. For queries with group-by variables, we choose a variable order where these variables sit above the other variables [13]. ∎
Figure 4 presents the AC/DC algorithm for factorized computation of SQL aggregates over the feature extraction query . The backbone of the algorithm without the code in boxes explores the factorized join of the input relations over a variable order of . As it traverses in depth-first preorder, it assigns values to the query variables. The assignments are kept in varMap and used to compute aggregates by the code in boxes.
The relations are sorted following a depth-first pre-order traversal of . Each call takes a range of tuples in each relation . Initially, these ranges span the entire relations. Once the root variable in is assigned a value from the intersection of possible -values from the input relations, these ranges are narrowed down to those tuples with value for .
To compute an aggregate over the variable order rooted at , we first initialize the aggregate to zeros. This is needed since the aggregates might have been used earlier for different assignments of ancestor variables in . We next check whether we previously computed the aggregate for the same assignments of variables in , denoted by context, and cached it in a map . Caching is useful when is strictly contained in , since this means that the aggregate computed at does not need to be recomputed for distinct assignments of variables in . In this case, we probe the cache using as key the assignments in varMap of the variables: . If we have already computed the aggregates over that assignment for , then we can just reuse the previously computed aggregates and avoid recomputation.
If is a group-by variable, then we compute a map from each -value to a function of and aggregates computed at children of , if any. If is not a group-by variable, then we compute a map from the empty value to such a function; in this latter case, we could have just computed the aggregate instead of the map though we use the map for uniformity. In case there are group-by variables under , the computation at returns maps whose keys are tuples over all these group-by variables in .
Example 17**.**
Consider a feature extraction query with the variable order in Figure 6(a). We first compute the assignments for as . For each assignment , we then find assignments for variables under within the narrow ranges of tuples that contain . The assignments for in the context of are given by . For each , the assignments for and are given by and . Since depends on and not on , the assignments for under a given are repeated for every occurrence of with assignments for . The assignments for given are computed as .
Consider the aggregate . The count at each variable is computed as the sum over all value assignments of of the product of the counts at the children of in ; if is a leaf in , the product at children is considered 1. For our variable order, this computation is captured by the following factorized expression:
[TABLE]
where is cached the first time we encounter the assignment for and reused for all subsequent occurrences of this assignment under assignments for .
Summing all -values in the result of for a variable is done similarly, with the difference that at the variable in we compute the sum of the values of weighted by the product of the counts of their children. For instance, the aggregate is computed over our variable order by the following factorized expression:
[TABLE]
To compute the aggregate , we compute for each assignment for instead of marginalizing away . The result is a map from -values to values of . ∎
A good variable order may include variables that are not explicitly used in the optimization problem. This is the case of join variables whose presence in the variable order ensures a good factorization. For instance, if we remove the variable from the variable order in Figure 6(a), the variables are no longer independent and we cannot factorize the computation over and . AC/DC exploits the conditional independence enabled by , but computes no aggregate over if this is not required in the problem.
The complexity bound in Proposition 4.4 is achieved by factorizing the computation of each aggregate in over a variable order that has all group-by variables for this aggregate above all other variables. Thus, different aggregates can be computed over different variable orders.
6.2 Shared computation of aggregates
Section 6.1 explains how to factorize the computation of one aggregate in , , and over the join of database relations. In this section we show how to share the computation across aggregates.
Example 18**.**
We consider the factorized expression of the aggregates and over :
[TABLE]
We can share computation across the expressions (57) to (60) since they are similar. For instance, given an assignment for , all these aggregates need . Similarly, for a given assignment for , the aggregates (58) and (60) can share the computation of the sum aggregate over . For assignments and , expressions (58) and (59) can share the computation of the sum aggregate over . ∎
To share as much computation as possible between aggregates, AC/DC computes all aggregates together over a single variable order, which significantly improves the data locality of the aggregate computation. This approach does not follow Proposition 4.4 that assumes that each aggregate is computed over its respective best variable order. AC/DC thus decidedly sacrifices the goal of achieving the lowest-known complexity for individual aggregates for the sake of sharing as much computation as possible across these aggregates.
Aggregate Decomposition and Registration.
For a model of degree and a set of variables , we have aggregates of the form , possibly with a group-by clause, such that , , and all categorical variables are turned into group-by variables. The reason for is due to the matrix used to compute the gradient of the loss function (17), which pairs any two features of degree up to . Each aggregate is thus defined uniquely by a monomial ; we may discard the variables with exponent 0. For instance, the monomial for is CE while for is ACE.
Aggregates can be decomposed into shareable components. Consider a variable order , with root and subtrees to . We can decompose any aggregate to be computed over into aggregates such that aggregate [math] is for and aggregate is for . Then is computed as the product of its components. Each of these aggregates is defined by the projection of the monomial of onto or . The aggregate is then pushed down the variable order and computed over the subtree . If the projection of the monomial is empty, then the aggregate to be pushed down is , which computes the size of the join defined by . If several aggregates push the same aggregate to the subtree , this is computed only once for all of them.
The decomposed aggregates form a hierarchy whose structure is that of the underlying variable order . The aggregates at a variable are denoted by . All aggregates are to be computed at the root of , then fewer are computed at each of its children and so on. This structure is the same regardless of the input data and can be constructed before data processing. We therefore construct at compile time for each variable in an aggregate register that is an array of all aggregates to be computed over the subtree of rooted at . This register is used as an index structure to facilitate the computation of the actual aggregates. More precisely, an entry for an aggregate in the register of is labeled by the monomial of and holds an array of indices of the components of located in the registers at the children of in and in the local register of . Figure 5 depicts this construction.
The hierarchy of registers forms an index structure that is used by AC/DC to compute the aggregates. This index structure is stored as one contiguous array in memory, where the entry for an aggregate in the register comes with an auxiliary array with the indices of ’s aggregate components. The aggregates are ordered in the register so that we increase sequential access, and thus cache locality, when updating them.
Example 19**.**
Let us compute a regression model of degree over a dataset defined by the join of the relations , and . We assume that and are categorical features, and all other variables are continuous. The quantities (,,) require the computation of the following aggregates: , for each variable , and for each pair of variables and .
Figure 6(a) depicts a variable order for the natural join of three relations, and Figure 6(b) illustrates the aggregate register that assigns a list of aggregates to each variable in . The aggregates are identified by their respective monomials (the names in the register entries). The categorical variables are shown in bold. Since they are treated as group-by variables, we do not need aggregates whose monomials include categorical variables with exponents higher than 1. Any such aggregate is equivalent to the aggregate whose monomial includes the categorical variable with degree 1 only.
The register for the root of has all aggregates needed to compute the model. The register has all aggregates from defined over the variables in the subtree of rooted at . The variables , , and are leaf nodes in , so the monomials for the aggregates in the registers , , and are the respective variables only. We use two additional registers and , which hold the aggregates corresponding to projections of the monomials of the aggregates in , and respectively , onto , respectively . For a leaf node , the registers and are the same.
A path between two register entries in Figure 6(b) indicates that the aggregate in the register above uses the result of the aggregate in the register below. For instance, each aggregate in is computed by the product of one aggregate from , , and . The fan-in of a register entry thus denotes the amount of sharing of its aggregate: All aggregates from registers above with incoming edges to this aggregate share its computation. For instance, the aggregates with monomials AB, AC, and AD from share the computation of the aggregate with monomial A from as well as the count aggregate from . Their computation uses a sequential pass over the register . This improves performance and access locality as can be stored in cache and accessed to compute all these aggregates. ∎
Aggregate Computation.
Once the aggregate registers are in place, we can ingest the input database and compute the aggregates over the join of the database relations following the factorized structure given by a variable order. The algorithm in Figure 4 does precisely this. Section 6.1 explained the factorized computation of a single aggregate over the join. We explain here the case of several aggregates organized into the aggregate registers. This is stated by the pseudocode in the red boxes.
Each aggregate is uniformly stored as a map from tuples over their categorical variables to payloads that represent the sums over the projection of its monomial on all continuous variables. If the aggregate has no categorical variables, the key is the empty tuple.
For each possible -value , we first compute the array that consists of the projections of the monomials of the aggregates onto . If is categorical, then we only need to compute the 0 and 1 powers of . If is continuous, we need to compute all powers of from 0 to . If is not a feature used in the model, then we only compute a trivial count aggregate.
We update the value of each aggregate using the index structure depicted in Figure 5 as we traverse the variable order bottom up. Assume we are at a variable in the variable order. In case is a leaf, the update is only a specific value in the local register . In case the variable has children in the variable order, the aggregate is updated with the Cartesian product of all its component aggregates, i.e., one value from and one aggregate for each child of . The update value can be expressed in SQL as follows. Assume the aggregate has group-by variables , which are partitioned across and its children. Assume also that ’s components are and . Recall that all aggregates are maps, which we may represent as relations with columns for keys and one column for payload. Then, the update to is:
[TABLE]
Further Considerations.
The auxiliary arrays that provide the precomputed indices of aggregate components within registers speed up the computation of the aggregates. Nevertheless, they still represent one extra level of indirection since each update to an aggregate would first need to fetch the indices and then use them to access the aggregate components in registers that may not be necessarily in the cache. We have been experimenting with an aggressive aggregate compilation approach that resolves all these indices at compile time and generates the specific code for each aggregate update. In experiments with linear regression, this compilation leads to a 4 performance improvements. However, the downside is that the AC/DC code gets much larger and the C++ compiler needs much more time to compile it. For higher-degree models, it can get into situations where the C++ compiler crashes. We are currently working on a hybrid approach that partially resolves the indices while maintaining a reasonable code size.
Point Evaluation, Gradient Computation and FD Optimization
For the computation of the point evaluation and gradient computation we use the optimizations we introduced in Section 4.4. Recall that two entries in can have the identical representation, which implies that a single aggregate can be used in distinct products over different components of . In order to avoid keep track of which aggregates correspond to which entries in , we construct for each aggregate a list of index pairs for each that require this aggregate. AC/DC then uses the index list and the aggregate computed at the root of the variable order to compute the queries for point evaluation and gradient computation that were presented in Section 4.4. Consider the matrix vector product , which is needed for gradient computation. Let be the root of the variable order . We compute by iterating over all aggregate maps , and for each index pair that is assigned to , we add to the ’th component of the product of and . If , we also add to ’s component of with the product of and .
For the FD optimization, it is required to construct the matrices that were introduced in Section 5.2. In AC/DC, we represent these matrices as maps that group the values for functionally determining variables by the values that they determine. The maps are sparse representations of matrices, and they are populated during the computation of the factorized aggregates over the variable order. We choose this representation because it allows for the efficient computation of the matrix , which is the basic building block the matrix from (47). The reparameterization of the regularizer requires the computation of the inverse of . Therefore, we store the matrix as a sparse matrix in the format used by the Eigen linear algebra library [34], and then use Eigen’s Sparse Cholesky Decomposition to compute the inverse of .
7 Experiments
We report on the performance of learning regression and factorization machine models over three real datasets used in retail and advertisement applications. We benchmark AC/DC against state-of-the-art competitors. AC/DC can compute the models up to faster, while the accuracy of AC/DC’s models is always at least as good as the competitor’s models. For all experiments, we assume that the model specification is given as input, and all systems compute the same model. We do not consider the orthogonal problem of finding the best model for a given analytics task.
7.1 Experimental setup
All experiments were performed on an Intel(R) Core(TM) i7-4770 3.40GHz/64bit/32GB with Ubuntu 18.04, g++7.4, and eight cores. We report wall-clock times by running each system once and then reporting the average of four subsequent runs with warm cache. We do not report the times to load the database into memory for the join. All relations are sorted by their join variables.
Competitors
We benchmark AC/DC against six competitors: MADlib [38] 1.16, libFM [64] 1.4.2, TensorFlow [1] 1.13.1, R [63] 3.4.4, scikit-learn [58] 0.20, and Python Statsmodels [68]. We evaluate the performance of learning the models over a training dataset, and then compute the root-mean-squared-error (RMSE) over a separate test dataset to compare the accuracy.
MADlib, R, scikit-learn, and Python StatsModels use ols (ordinary least squares) to compute the closed-form solution of regression models, and TensorFlow uses the LinearRegressor estimator with ftrl optimization [48], which is based on the conventional SGD optimization algorithm. TensorFlow was compiled from source to enable specialized optimizations that are native to our machine, including AVX optimizations. We use PostgreSQL 10.9 to compute the feature extraction query for libFM and TensorFlow. LibFM supports factorization machines.
AC/DC uses the gradient descent algorithm with the adaptive learning rate from Algorithm 1. For LR and PR models, we run the optimization algorithm until the RMSE over the training dataset changes by less than in three consecutive iterations. For FaMa models, we use 300 iterations.
The aggregate computation in AC/DC is parallelized on eight cores. Tensorflow also uses multiple threads by default. MADlib and libFM only use a single thread.
The competitors come with various limitations that affect their scalability. MADlib requires the explicit one-hot encoding of the input relations, for which we use its predefined functions.
LibFM requires as input a zero-suppressed encoding of the one-hot encoded join result. Computing this representation is an expensive intermediate step between exporting the query result from the database system and importing the data into libFM. We learn the FaMa models using the MCMC optimization algorithm with a fixed number of runs (300); its SGD implementation requires a fixed learning rate and does not converge.
TensorFlow uses a user-defined iterator interface to load a batch of tuples from the training dataset at a time. This iterator defines a mapping from input tuples to features and is called directly by the learning algorithm. To avoid the explicit one-hot encoding of the features, TensorFlow encodes categorical features using a hash function. Learning over batches requires a random shuffling of the input data, which in TensorFlow amounts to loading the entire dataset into memory. This failed for our experiments due to the large sizes of the datasets. We therefore shuffle the data in PostgreSQL instead and provide the shuffled input to TensorFlow. We benchmark TensorFlow for LR only as it does not provide functionality to create all pairwise interaction terms for PR and FaMa. The optimal batch size for our experiments is 100,000 tuples. Smaller batch sizes require loading too many batches, very large batches cannot fit into memory. Since TensorFlow uses a fixed number of iterations, we report the times to optimize with one epoch over the training dataset. This means that the algorithm learns over each data point in the training dataset once. Our experiments show that it is often necessary to optimize with several epochs to learn a good model.
R, scikit-learn, and Python Statsmodels fail to compute our models due to design limitations. R limits the number of values in their data frames to , which is insufficient to represent out datasets. Scikit-learn and Python Statsmodels both run out of memory for all considered models.
Datasets
We experimented with three real-world datasets: (1) Retailer [66] is used by a large retailer for forecasting user demand and sales; (2) Favorita [26] is a public dataset used for retail forecasting; and (3) Yelp is based on the Yelp Dataset Challenge [70] and used to predict ratings by a user for a business. The structure and size of these datasets is common in retail and advertising, where data is easily generated by sales transactions or click streams. The feature extraction query for each dataset is the natural join of the input relations. For each dataset, we consider a subset of the variables. Table 1 presents key characteristics for each dataset. It shows that the join result can be orders of magnitude larger than the input database.
Retailer has a star schema with one fact table Inventory, which keeps track of the number of inventory units for products (sku) in a store (locn) at a given date, and three dimension tables: (1) Location keeps additional information for each store, including its size in sqft and distances to three competitors; (2) Items provides identifiers for the item category, subcategory, category cluster, as well as the price for each sku; and (3) Weather keeps information about the weather conditions for each store at a given date (including maximum temperature, and whether it rained). We design two versions of our dataset. The version v1 includes all variables but sku, date, and locn as features, and has no functional dependencies. Version v2 extends v1 with the categorical variable sku, and exploits the functional dependency sku{category, subcategory, categoryCluster}. We learned LR, , and models that predict the amount of inventory units based on all other features. The test data constitutes the inventory in the last month in the dataset (approx. 2.2% of the data). This simulates the realistic usecase where the ML model predicts future inventory.
Favorita has a star schema with one fact table and 4 dimension tables. The fact table Sales stores the number of units sold for items for a given date and store, and an indicator whether or not the unit was on promotion at this time. Items keeps additional information about the skus, including the item class and whether it is perishable. Stores provides additional information about the stores, such as the city and state they are located in, and the type of store. Transactions gives the number of transactions at each store on a given date. Oil keeps the oil price for each date. Our models predict the number of units sold. We designed two variants for this dataset. Version v1 learns the model over all variables except sku and date, and version v2 extends v1 with sku. We exploit the functional dependency store{city, state, storetype} in both variants. The test data constitutes the sales for the last month in the dataset (approx. 1.2% of the data).
Yelp has a star schema with four relations: Review stores, for each review, the rating given by user, the review date, and the number of compliments it received (e.g, useful, funny, cool); Business keeps the location (city, state, coordinates), the average rating, and the total count of reviews for each business; User keeps aggregated statistics for each user, including the number of reviews they wrote, the number of compliments they received, and the average rating they gave to businesses; Attribute keeps attributes (e.g. as “open late”) for each business. One user can review many businesses and a business can have many attributes. The result of the feature extraction query is much larger than the input relations. Our models predict the rating that users give to businesses. The models are learned over all variables except the join keys, and exploit the functional dependency citystate. The test dataset is a random selection of approximately 2% of the reviews.
7.2 Summary of findings
Our findings on the performance comparison between AC/DC and the three competitors are given in Table 2. AC/DC is the fastest system in our experiments. It can compute the models over the input database orders of magnitude faster than its competitors whenever they do not exceed memory limitation, 24-hour timeout, or internal design limitations.
AC/DC learns models with at least as good accuracy as the competitors. In particular, AC/DC’s LR models have comparable accuracy to MADlib’s closed form solution (whenever MADlib does not time out), and consistently better accuracy than the models learned by TensorFlow (trained for one epoch). With additional features, AC/DC can learn more accurate models while the competitors either timeout or fail due to internal design limitations.
The performance gap between competitors and AC/DC is primarily due to the following optimizations supported by AC/DC:
It avoids the materialization of the join and the export-import step between database systems and statistical packages, which may take longer than the end-to-end learning of LR models in AC/DC. AC/DC performs the join together with the aggregates using one execution plan; 2. 2.
It factorizes the computation of the sparse tensor and the underlying join. The compression factor brought by join factorization is 13.9 for Retailer, for Favorita, and 21 for Yelp; 3. 3.
It massively shares the computation of many aggregates representing entries in the sparse tensor. For instance, there are up to 2.5M such sum aggregates for on Retailer v2 and they take 150K less time than computing the count aggregate 2.5M times, where the count takes 19.9 seconds as reported in Table 2; 4. 4.
It decouples the computation of the aggregates on the input data from the parameter convergence step and thus avoids scanning the join result for each iteration; 5. 5.
It avoids the upfront one-hot encoding that comes with higher asymptotic complexity and prohibitively large covariance matrices by only computing distinct, non-zero entries in the sparse tensor. For on Retailer v2, this leads to less aggregates to compute; 6. 6.
It exploits the functional dependencies in the input data to reduce the number of features of the model, which leads to an improvement factor of up to 2.3.
7.3 Further details
Categorical features
As we move from Retailer v1 to v2, we increase the number of categorical features by approx. for LR (from 49 to 3.7K) and for and (from 980 to 66K). This translates to a same-order increase in the number of aggregates: () more distinct non-zero aggregates in v2 vs v1 for LR (resp. and ). This increase only led to a decrease in performance of AC/DC of for LR and for . This sub-linear behavior is partly explained by the ability of AC/DC to process many aggregates much faster in bulk than individually: it takes 19.9 seconds for one count aggregate, but only 334 seconds to compute all 2.5M entries in the sparse tensors for on v2!
For MADlib, the performance decrease is at least for LR when moving from v1 to v2 and it times out after 24 hours for v2. MADlib also times out for all experiments. The performance of TensorFlow is largely invariant to the increase in the number of categorical features, since its internal mapping from tuples in the training dataset to the sparse representation of the features vector remains of similar size. Nevertheless, our system is consistently faster (often by orders of magnitude) than computing only a single epoch in TensorFlow. In addition, AC/DC computes the end-to-end models faster than PSQL takes to materialize and shuffle the design matrix that is the input to TensorFlow.
One-hot encoding vs.sparse encoding with group-by aggregates.
One-hot encoding categorical features leads to a large number of zero and/or redundant entries in the matrix. For instance, for on Retailer v2, the number of features is =66,117, and then the upper half of would have entries. Most of these are either zero or repeating, as exemplified in Section 4.3. In contrast, AC/DC’s sparse representation only considers 2.5M non-zero and distinct aggregates. The number of aggregates is thus reduced by a factor of !
MADlib and libFM require the data be one-hot encoded before learning. For MADlib, the static one-hot encoding took up to 545 seconds on Favorita. In addition to the one-hot encoding, libFM requires the input data to be represented in a zero-supressed sparse format. This data transformation took up to one hour in our experiments. TensorFlow one-hot encodes on the fly using hash functions during the learning phase, which cannot be reported separately.
When running over one-hot encoded input data, AC/DC exceeds the available memory for all models but the linear regression model for Retailer v1.
Effect of functional dependencies.
Figure 7 shows the performance breakdown for AC/DC with and without exploiting FDs. All other systems do not exploit FDs.
The FDs have a twofold effect on AC/DC: they can reduce the number of features and aggregates, which leads to better performance of the aggregation step; yet it requires a more expensive convergence step due to the more complex regularizer. For LR over Retailer v2, the aggregate step becomes faster, while the convergence step increases , offsetting the effect of the faster aggregate computation. The FDs for Favorita and Yelp have a relatively smaller effect on performance for LR (there are only 54 stores in Favorita, so the reduction in the number of aggregates is small).
For models, the FD brings an improvement by a factor of for Retailer. This is due to a 18% decrease in the number of categorical features, which leads to a 38% decrease in the number of group-by aggregates. For Favorita and Yelp, the performance improvement is 1.3 and respectively 1.2. For models, the effect of FDs is comparable to that of models.
Accuracy.
The RMSE of the LR models for Retailer and Favorita in AC/DC is within 1% of that for the closed form solutions computed in MADlib. By extending the models with the categorical variable sku (version for both datasets), the RMSE decreases by 21% for Retailer and by 6% for Favorita. MADlib fails to learn these more accurate models, because it times out after 24 hours.
For TensorFlow, the models are trained with a single epoch. The resulting models have a consistently higher RMSE than the corresponding model computed in AC/DC. In particular, for Retailer , the RMSE of the TensorFlow model is 31% higher. TensorFlow requires more epochs to achieve the same accuracy as AC/DC.
Extending the model with pairwise interactions can also improve the model accuracy. For Favorita , for instance, the RMSE of the model is lower than the RMSE of the LR model.
The FaMa models learned by AC/DC do not reach the same accuracy as the models, and would therefore require more than 300 iterations to converge to an accurate model. This is due to the non-linear structure of factorization machines.
8 Related work
Our work follows closely Chaudhuri’s manifesto on SQL-aware data mining systems from two decades ago [19] in two key aspects. First, the goal of our work is not to invent new machine learning models or data analysis techniques, but identify common data-centric steps across a broad class of learning algorithms and investigate their theoretical and systems challenges. We show that such steps can be encoded as SQL group-by aggregate queries, which are amenable to shared batch computation. Second, our approach performs data analysis not only over materialized relations but more importantly over feature extraction queries, whose results need not be materialized. This enables the interaction between the aggregates encoding the data-centric steps and the underlying queries (this is called ad-hoc mining in Chaudhuri’s terminology).
A reevaluation of Chaudhuri’s manifesto in today’s context brings forth two important technical changes. The first game-changer is represented by the recent development on query processing. This includes a new breed of worst-case optimal join algorithms, which support listing representation [52, 69] and factorized representation [56] of query results, and extensions to aggregate computation [13, 8, 55]. These algorithms exploit developments on (fractional) hypertree decompositions of relational queries [32, 33, 47]. These algorithms overshadow the traditional query plans in both asymptotic complexity [53] and practical performance [13, 54]. The second change is in the workload. Whereas SQL-aware data mining systems were mostly concerned with association rules, decision trees, and clustering, current workloads feature a broader spectrum of increasingly more sophisticated machine learning (ML) models, including polynomial regression models, factorization machines, principal component analysis, generalized linear models, generalized low-rank models, sum-product networks, and convolutional networks. In this article, we introduce a unified approach to learning polynomial regression models, factorization machines, and principal component analysis over non-materialized feature extraction queries with the lowest known complexity and best performance to date. There is also a more profound orthogonal change: There is more data readily available in all aspects of our society and there is more appetite in industry to monetize it by turning it into knowledge.
The current landscape for analytics solutions over multi-relational data can be categorized depending on the degree of integration of the data system, which hosts the data and supports data access via query primitives, with the ML library of models and learning algorithms.
By far the most common solutions provide no integration of the two systems, which are distinct tools on the technology stack: The data system exports the training dataset as one relation, commonly presented as a CSV file, and then the ML system imports it into its own format and learns the desired model.Such solutions are structure-agnostic as they disregard the rich structural information of the materialized training dataset, including the input database schema, database dependencies, and the structure of the feature extraction queries. Prime examples are the pairing of open-source data systems such as Spark [71] or MySQL/PostgreSQL with ML systems such as R [63], Python StatsModels [68], Python Scikit [58], MLpack [22], TensorFlow [1], SystemML [39, 15], MLLib [49], and DeepDist [51]. The advantage of this approach is that the two systems can be developed independently, with virtually any ML model readily available for use.
Two disadvantages of such common solutions are the expensive data export/import at the interface between the two systems and the materialization of the training dataset as a result of a feature extraction query over multi-relational data. The feature extraction query is computed inside the data system, its result exported and imported into the data format of the ML system, where the model is learned. Furthermore, the materialized training dataset may be much larger than the input data (cf.Table 1). This is exacerbated by the stark asymmetry between the two systems: Whereas data systems tend to scale to large datasets, this is not the case for ML libraries. Yet, such solutions expect by design that the ML libraries work on even larger inputs than the data systems! A further disadvantage is that these solutions inherit the limitations of both underlying systems. For instance, the R data frame can host at most values, which makes it impossible to learn models over large datasets, even if data systems can process them. Database systems can only handle up to a few thousand columns per relation, which is usually smaller than the number of features of the model.
The second class of systems features a loose integration, even though they remain structure-agnostic: The ML code migrates inside the space of the data system process, with each ML task being implemented by a distinct user-defined aggregate function (UDAF). Prime examples of this class are MADlib [38] and GLADE PF-OLA [62]. MADlib casts analytics as UDAFs that can be used in SQL queries and executed inside PostgreSQL. GLADE PF-OLA casts analytics as a special form of UDAFs called Generalized Linear Aggregates that can be executed using the GLADE distributed engine [21]. These UDAFs remain black boxes for the underlying query engine, which has to compute the feature extraction query and delegate the UDAF computation on top of the query result to the MADLib’s and GLADE PF-OLA’s specialized code. The advantage of this approach is that the expensive export/import step is avoided. The disadvantage is that each ML task has to be migrated inside the data system space, which comes with design and implementation overhead. A further step towards integration is exemplified by Bismarck [27], which provides a unified programming architecture for many ML tasks instead of one UDAF per task, with possible code reuse across UDAFs.
The third class of systems features a tight integration and are structure-aware: There is one execution strategy for both the feature extraction query and the subsequent learning task, with components of the latter possibly pushed past the joins in the former. Prime examples are Morpheus [43], Hamlet [44], and our prior system F [66] that support generalized linear models, Naïve Bayes classification, and respectively linear regression models with continuous features. This class also contains the recent efforts on in-database linear algebra [20] and on scaling linear algebra using existing distributed database systems [46] and the declarative language BUDS [29], whose compiler can perform deep optimizations of the user’s program. Our approach AC/DC generalizes F to non-linear models, categorical features, and model reparameterization under functional dependencies. A key aspect that sets apart AC/DC and its predecessor F from prior work is that they employ execution strategies for the mixed workload of queries and learning with complexity that may be asymptotically lower than that of query materialization alone. In particular, all machine learning approaches that require as input the materialization of the result of the feature extraction query are asymptotically suboptimal. This complexity gap translates into a performance gap, cf.Section 7.
Figure 1 sums up the difference between the first two classes that fall under structure-agnostic learning and the third class that broadly represents structure-aware learning. The inspiration for our work lies with factorized computation of aggregates over joins [13, 8], which avoids the materialization of joins, and with the LogicBlox system [50, 11], which has a unified system architecture and declarative programming language for hybrid database and optimization workloads.
Beyond the above classification, there are further directions of research looking at ML through database glasses: ML-aware query languages, the effect of dependencies on model training, sparse data representations, and implementations of gradient descent solvers.
Analytical tasks can be expressed to a varying degree within query languages possibly extended with new constructs. Very recent works investigate query languages for matrices [18] and a relational framework for classifier engineering [41]. They follow works on query languages with data mining capabilities [17, 57], also called descriptive or backward-looking analytics, and on in-database data mining solutions, such as frequent itemsets [59] and association rule mining [10]. Our rewriting of ML code into aggregates falls into this line of work as well. The additional fixpoint computation needed on top of the aggregate computation for convergence of the model parameters, which is intrinsic to gradient descent approaches, can be expressed as recursive queries [3].
Functional dependencies (FDs) can be used to avoid key-foreign key joins and reduce the number of features in Naïve Bayes classification and feature selection [44]. In this article we consider the effect of FDs on the reparameterization of regression models, where a non-trivial development is on the effect of FDs on the model’s non-linear regularization function, cf.Section 5. Our factorized learning approach exploits the join dependencies present in the training dataset, as defined by the feature extraction query. This follows prior work on factorized databases [13, 56].
State-of-the-art machine learning systems use a sparse representation of the input data to avoid redundancy introduced by one-hot encoding [64, 25]. In our setting, however, such systems require an additional data transformation step after the result of the feature extraction query is exported. This additional step is time consuming and makes the use of such systems inefficient in many practical applications. In statistics and machine learning, there is a rich literature on learning with sparse and/or multilinear structures [37]. Such methods complement our framework and it would be of interest to leverage and adapt them to our setting.
Finally, there is a large collection of gradient-based methods proposed in the optimization literature. The description of our approach assumes batch gradient descent (BGD), though our insights are applicable to other methods including Quasi-Newton algorithms. The main rationale for our choice is simplicity and good statistical properties. When combined with backtracking line search (as we do in this article) or second-order gradient estimation (as in Quasi-Newton methods), BGD is guaranteed to converge to a minimum with linear asymptotic convergence rate. A naïve computation of the gradient requires a full pass over the data, which can be inefficient in large-scale analytics. A popular alternative is stochastic gradient descent (SGD), which estimates the gradient with a randomly selected mini-batch of training samples. The convergence of SGD, however, is noisy, requires careful setting of hyperparameters, and does not achieve the linear asymptotic convergence rate of BGD [16]. In our setting, the entire BGD execution can be arbitrarily faster than one SGD iteration over the result of the feature extraction query. The reason is orthogonal to properties of the two gradient descent methods: The complexity of computing the sufficient statistics needed for convergence of model parameters can be asymptotically lower than the complexity of computing the training dataset.
9 Open Problems
Our in-database learning framework raises open questions on statistics, algorithm design, and optimization. We next sketch a few representative questions.
One research direction is to further extend the class of statistical models that can be trained efficiently by exploiting the structure of the underlying relational database. Our formulation (6) captures a common class of regression models (such as PR and FaMa), classification models (such as logistic and SVM), and unsupervised learning techniques (such as principal component analysis) which is done by changing the loss function . It remains open how to extend our formulation to capture latent variable models.
The aggregates defining , , point evaluation, and gradient computation are “multi-output” queries. They deserve a systematic investigation, from formulation to evaluation and complexity analysis. In practice, one often reserves a fragment of the training data for model validation. It is an interesting question to incorporate this data partitioning requirement into our framework.
Understanding how to adapt further optimization algorithms, such as coordinate descent or stochastic gradient, to our structure-aware framework is an important research direction. Furthermore, our FD-aware optimization is specific to the -norm in the penalty term. We would also like to understand the effect of other norms, e.g., , on model reparameterization under FDs.
Finally, we conjecture that the cost function may be easier to optimize with respect to the reduced set of parameters that are not functionally determined: As redundant variables are eliminated or optimized out, the cost function’s Hessian with respect to reduced parameters becomes less ill-conditioned, resulting in faster convergence behavior for gradient-based optimization techniques. The impact of FD-based dimensionality reduction, from both computational and statistical standpoints, have not been extensively studied for learning (nonlinear) models with categorical variables, which are precisely the kind discussed in our framework.
Acknowledgements
This project has received funding from the European Union’s Horizon 2020 research and innovation programme under grant agreement No 682588. XN is supported in part by grants NSF CAREER DMS-1351362, NSF CNS-1409303 and the Margaret and Herman Sokol Faculty Award.
Appendix A Matrix Calculus
We introduce matrix inversion formulas and identities regarding tensors and the various products introduced in Section 2.
We use the following matrix inversion formulas [35].
Proposition A.1**.**
We have
[TABLE]
whenever all dimensions match up and inverses on the right hand side exist. In particular, the following holds when , , , and is the all- matrix:
[TABLE]
Another special case is
[TABLE]
An even more special case is the Sherman-Morrison formula, where is just a vector . The matrix is typically called a rank- update of :
[TABLE]
Next, we discuss some identities involving tensor, Khatri-Rao, and Hadamard products.
Proposition A.2**.**
We have (if the dimensionalities match up correctly):
[TABLE]
If is a standard -dimensional unit vector, and are two matrices with columns each, and and are two -dimensional vectors, then
[TABLE]
Let be a standard -dimensional unit vector, be matrices with columns each. Then,
[TABLE]
We note in passing that the first five identities are very useful in our dimension reduction techniques by exploiting functional dependencies, while (70), (71), and (72) are instrumental in achieving computational reduction in our handling of categorical features.
Proof.
The identities (65), (66), (67), and (68) can be found in the Matrix Cookbook [60]. Identity (69) follows from (65) and (66). To see (70), note that
[TABLE]
where the last equality follows due to the following reasoning. Suppose for some , then and , where and are the th columns of and , respectively. Thus,
[TABLE]
Identities (71) and (72) are proved similarly, where (72) is a trivial generalization of (70). ∎
Appendix B Tensor computation and FAQ queries
Quite often we need to compute a product of the form , where , and are tensors, provided that their dimensionalities match up. For example, suppose is an matrix, a matrix, and a matrix (i.e. a vector). The result is a tensor. The brute-force way of computing is to compute first, taking -time, and then multiply the result with , for an overall runtime of . The brute-force algorithm is a horribly inefficient algorithm.
The better way to compute is to view this as an FAQ-expression [8] (a sum-product form): we think of as a function , as a function , and as a function . What we want to compute is the function
[TABLE]
This is a -cycle FAQ query:
We can pick between the following two evaluation strategies:
- •
Eliminate first, i.e., compute in time ; then, eliminate , i.e., compute in time . The overall runtime is thus .
- •
Eliminate first and then . The overall runtime is .
This is not surprising, since the problem is just matrix chain multiplication. In the language of FAQ evaluation, we want to pick the best tree decomposition and then compute a variable elimination order out of it [8]. We shall see later that a special case of the above that occurs often is when , the identity matrix. In that case, is the same as the atom , and thus it serves as a change of variables:
[TABLE]
In other words, we only have to marginalize out one variable instead of two. This situation arises, for example, in (50) and (51).
Appendix C overviews the InsideOut algorithm for FAQ queries and its complexity analysis.
Appendix C Widths for FAQ Queries and the InsideOut Algorithm
Background: Fractional edge cover number and output size bounds
In what follows, we consider a conjunctive query over a relational database instance . We use to denote the size of the largest input relation in . We also use to denote the output and to denote its size. We use the query and its hypergraph interchangeably.
Definition 6** (Fractional edge cover number ).**
Let be a hypergraph (of some query ). Let be any subset of vertices. A fractional edge cover of using edges in is a feasible solution to the following linear program:
[TABLE]
The optimal objective value of the above linear program is called the fractional edge cover number of in and is denoted by . When is clear from the context, we drop the subscript and use .
Given a conjunctive query , the fractional edge cover number of is where is the hypergraph of .
Theorem C.1** (AGM-bound [12, 33]).**
Given a full conjunctive query over a relational database instance , the output size is bounded by
[TABLE]
where is the fractional edge cover number of .
Theorem C.2** (AGM-bound is tight [12, 33]).**
Given a full conjunctive query and a non-negative number , there exists a database instance whose relation sizes are upper-bounded by and satisfies
[TABLE]
Worst-case optimal join algorithms [69, 52, 53, 6] can be used to answer any full conjunctive query in time
[TABLE]
Background: Tree decompositions, acyclicity, and width parameters
Definition 7** (Tree decomposition).**
Let be a hypergraph. A tree decomposition of is a pair where is a tree and assigns to each node of the tree a subset of vertices of . The sets , , are called the bags of the tree decomposition. There are two properties the bags must satisfy
- (a)
For any hyperedge , there is a bag , , such that .
- (b)
For any vertex , the set is not empty and forms a connected subtree of .
Definition 8** (acyclicity).**
A hypergraph is acyclic iff there exists a tree decomposition in which every bag is a hyperedge of .
When represents a join query, the tree in the above definition is also called the join tree of the query. A query is acyclic if and only if its hypergraph is acyclic.
For non-acyclic queries, we often need a measure of how “close” a query is to being acyclic. To that end, we use width notions of a query.
Definition 9** (-width of a hypergraph: a generic width notion [9]).**
Let be a hypergraph, and be a function that assigns a non-negative real number to each subset of . The -width of a tree decomposition of is . The -width of is the minimum -width over all tree decompositions of . (Note that the -width of a hypergraph is a Minimax function.)
Definition 10** (Treewidth and fractional hypertree width are special cases of -width).**
Let be the following function: , . Then the treewidth of a hypergraph , denoted by , is exactly its -width, and the fractional hypertree width of a hypergraph , denoted by , is the -width of .
From the above definitions, for any hypergraph . Moreover, if and only if is acyclic.
Background: Vertex/variable orderings and their equivalence to tree decompositions
Besides tree decompositions, there is another way to define acyclicity and width notions of a hypergraph, which is orderings of the hypergraph vertices. And just like we refer to queries and hypergraphs interchangeably, we also refer to query variables and hypergraph vertices interchangeably.
In what follows, we use to denote the number of vertices of the given hypergraph .
Definition 11** (Vertex ordering of a hypergraph).**
A vertex ordering of a hypergraph is simply a listing of all vertices in .
Definition 12** (Elimination sets of a vertex ordering ).**
Given a hypergraph and a vertex ordering , we define sets , called the elimination sets of , as follows: Let be the set of hyperedges of that contain . We define to be the union of all hyperedges in :
[TABLE]
If , then we are done. Otherwise, we remove vertex and all hyperedges in from and add back to a new hyperedge , thus turning into a hypergraph with vertices:
[TABLE]
The remaining elimination sets are defined inductively to be the elimination sets of the resulting hypergraph (whose vertices are now ).
When is clear from the context, we drop the superscript and use .
Proposition C.3** (Every vertex ordering has an “equivalent” tree decomposition [7]).**
Given a hypergraph , for every vertex ordering , there is a tree decomposition whose bags are the elimination sets of .
By applying the GYO elimination procedure [3] on the bags of any given tree decomposition, we can obtain an “equivalent” vertex ordering:
Proposition C.4** (Every tree decomposition has an “equivalent” vertex ordering [7]).**
Given a hypergraph , for every tree decomposition , there is a vertex ordering such that every elimination set of is contained in some bag of the tree decomposition .
FAQ-width of an FAQ query
Just like a conjunctive query, an FAQ query has a query hypergraph . But unlike conjunctive queries, an FAQ query also specifies an order of its variables, which is the order in which we aggregate over those variables in the given FAQ-expression. (For example, in expression (73), we sum over first, then over , and we keep and as free variables. Hence, the FAQ query in (73) specifies the variable order .) Such a variable order for the query can also be interpreted as a vertex order for the query’s hypergraph.
The InsideOut algorithm for answering FAQ queries is based on variable elimination. To eliminate variable/vertex , we have to solve a sub-problem consisting of a smaller FAQ query over the variables in the elimination set . This smaller query can be solved by an algorithm that is based on worst-case optimal join algorithms [69, 52, 53, 6]. From (74), this takes time 555To achieve this runtime, we need some additional ideas that are beyond the scope of this very brief introduction to FAQ. See [8] for more details.
[TABLE]
After eliminating , the remaining variables can be eliminated similarly. This variable elimination algorithm motivates the following width notion.
Definition 13** (FAQ-width of a given variable ordering ).**
Given an FAQ query with a variable ordering , we define the FAQ-width of , denoted by , to be
[TABLE]
By the above definition, the FAQ-width of a variable ordering is the same as the fractional hypertree width of the “equivalent” tree decomposition that is referred to in Proposition C.3.
Theorem C.5** (Runtime of [8]).**
Given an FAQ-query with a variable ordering , the algorithm answers in time
[TABLE]
where is the output size in the listing representation.
Let be an FAQ query with variable ordering . In many cases, there might be a different variable ordering such that if we were to permute the aggregates of in the order of instead of , we would obtain an FAQ-query that is “semantically-equivalent” to (i.e. that always returns the same answer as no matter what the input is). If this is the case, then we can run InsideOut on using the ordering instead of , which can lead to a better runtime if happens to be smaller than . We use to denote the set of all such “equivalent” orderings . (For a formal definition, see [8].) Therefore, it is best to consider all orderings in , pick the one with the smallest , and use it in InsideOut algorithm. This motivates the following definition.
Definition 14** (FAQ-width of an FAQ query).**
The FAQ-width of an FAQ query , denoted by , is the minimum one over all orderings in , i.e.
[TABLE]
Characterizing for an arbitrary given FAQ-query is a technically involved problem (see [8] for hardness background and a general solution). However, the FAQ queries that we need for our machine learning tasks are of a special form that makes the problem easier.: The aggregate operator that we use in such queries is the summation operator . We refer to those restricted FAQ queries as FAQ-SS queries (see [8]). Our FAQ-SS queries in this work have only two types of variables:
- •
Variables that we are summing over, e.g. variables and in (73).
- •
Free variables (i.e. Group-by variables), e.g. variables and .
Given an FAQ-SS query , contains every ordering that lists all free variables before the non-free variables. For example, for the FAQ-SS query in (73), contains all permutations of where come before .
Proposition C.6**.**
For any FAQ-SS query without free variables, we have , where is the hypergraph of .
Proof.
In this case, contains all possible orderings. By Proposition C.4, for every tree decomposition , there is an ordering such that . By Proposition C.3, for every ordering , there is a tree decomposition such that . Therefore, we have
[TABLE]
∎
Proposition C.7**.**
For any FAQ-SS query with free variables, we have , where is the hypergraph of .
Proof.
Find a tree decomposition of with minimal fhtw, i.e. where . WLOG let the free variables be . Construct another tree decomposition by extending all bags of with the variables , i.e. by defining for all . By Definition 7, is indeed a tree decomposition. And because , we have
[TABLE]
Moreover, since must have a bag that contains , the corresponding bag of contains all the free variables . We designate as the root of , and then we run GYO elimination procedure [3] on the bags of to construct a vertex ordering with . Moreover, if we choose to eliminate the vertices of the root at the end of GYO elimination (after all other vertices have already been eliminated), we can make the free variables appear before all other variables in , thus making sure that is indeed in and completing the proof. In particular, we apply GYO elimination as follows:
- •
If the tree contains only one node :
- –
We eliminate vertices in before eliminating .
- –
We remove from , thus making an empty tree.
- •
Otherwise, we pick a leaf node of (other than the root ). Let be the parent of in :
- –
If , then we remove node from along with the associated bag .
- –
Otherwise, must have a vertex that is not in . (Hence, by property (b) of Definition 7, is not in for all in other than .)
If is the only vertex in , then we remove node from along with the associated bag .
- *
Otherwise, we remove from .
- •
We repeat the above steps until becomes an empty tree.
∎
Appendix D Missing details from Section 4
Proof of Theorem 4.1.
We start with point evaluation:
[TABLE]
The gradient formula follows straightforwardly from (16) and the chain rule. ∎
Proof of Corollary 21.
From (18) we have
[TABLE]
∎
Proof of Proposition 4.4.
For any event , let denote the Kronecker delta, i.e. if holds, and otherwise. Recall that the input query has hypergraph , and there is an input relation for every hyperedge . Recall that we can write in the tensor form as shown in Eq. (23). Plugging in the definition of and from (9); and, let and , we have
[TABLE]
As illustrated in Example 13, the tensor is very sparse. For a fixed tuple , in fact, the tensor has only one entry, corresponding to the combination of values of the attributes in . Hence, is a function of the variables . In the FAQ-framework, the query representing can be expressed as a Sum-Product queries with free (i.e., group-by) variables , defined by:
[TABLE]
Similarly, the tensor can be sparsely represented by an aggregate query with group-by attributes , which is expressed as the Sum-Product query
[TABLE]
The overall runtimes for computing the above FAQ-queries follow from applying the InsideOut algorithm and Theorem C.5 [8]. ∎
Proof of Proposition 33.
The fact that follows from Proposition C.7. Since is a tensor of order at most , and each attribute’s active domain has size at most , it follows that . And, because the support of the tensor cannot be more than the output size.
Fix a query with . Consider a database instance for which (the output size of ) is . (The existence of such database instances is guaranteed by Theorem C.2.) From this (33) follows trivially. ∎
Proof of Proposition 4.6.
We first analyze the time it takes to compute expression (16), which is dominated by the quadratic form . To compute this quadratic form, for every pair we need to compute . This product is broken up into a sum of terms when we expand and out. Each of those terms is computed in time . The runtime for computing (17) is analyzed similarly. ∎
Appendix E Missing details from Section 5
In the proofs below, for each feature , denote the identity matrix whose dimension is the size of the effective domain of . This is not to be confused with the notation which is an order- identity matrix.
E.1 Missing rewriting steps in the example in Section 5.1
We first prove identity (42) formally. By setting the gradient in (41) to [math], we have . Hence, it remains to show the identity
[TABLE]
To see this, we apply the Sherman-Morrison-Woodbury identity (63) with and to get
[TABLE]
multiply both sides of (81) on the right by , we obtain
[TABLE]
We next show (43); to do so, it is sufficient to verify that
[TABLE]
For the sake of brevity, define so that . We compute each term on the left hand side separately:
[TABLE]
From here, we derive (82) by
[TABLE]
E.2 Proof of Theorem 5.1
Proof.
We start by breaking the loss term into two parts
[TABLE]
and rewrite the second part:
[TABLE]
Equality (85) follows from (72). Equality (86) follows from (65). Equality at (88) is a bit loaded. What goes on there is that we broke the sum over for which and into a nested triple sum. First of all, in order for , obviously must hold, so we group by those tuples first. The remaining mass can only be at most . Since all features in are categorical, from the above analysis we have , i.e., is a characteristic vector of a subset . Let . Then, in the second summation we group by . The third summation ranges over all choices of , , for which the total mass is at most . (Recall the definition of in (45).)
Next, in (89) we perform the reparameterization. Recall that is the characteristic vector of the set in the collection . The new parameter is indexed by the tuple whose support is , i.e., the set of all features except for the ones functionally determined by features in . After the reparameterization, the loss term is identical to the loss term of a model whose features are . This explains the collapsed pair used in the theorem.
Next, we explore the new parameter and how it affects the penalty term. Consider a fixed pair and such that and . The last condition is implicit for the set to exist for which and . Among all choices of , we single out and write
[TABLE]
Now we are ready to write the penalty term in terms of the new parameter and some “left-over” components of .
[TABLE]
Next, for every , we optimize out the parameter by noting that the new loss term does not depend on these parameters. To optimize them out, we compute
[TABLE]
Setting this partial derivative to [math], we obtain , which leads to
[TABLE]
Moving and grouping, we obtain
[TABLE]
Or, more compactly,
[TABLE]
Consequently, we can completely optimize out the remaining -components, solving for them in terms of the components of :
[TABLE]
Thus, for a fixed and , we can simplify the total squared normed involved:
[TABLE]
Finally, we write in terms of the new parameter to prove (49):
[TABLE]
∎
E.3 Alternative to Corollary 21
One big advantage of a linear model in terms of BGD is Corollary 21, where we do not have to redo point-evaluation for every backtracking step. After the reparameterization exploiting FD-based dimensionality reduction, Corollary 21 does not work as is, because we have changed the penalty terms. However, it is easy to work out a similar result in terms of the new parameter space; see The point of the following proposition is that we only need to compute intermediate results involving the covariance matrix once while backtracking. For each new value of , we will need to recompute the penalty’s objective , which is an inexpensive operation. If , we can even solve for directly.
Proposition E.1**.**
With respect to the new parameters (and new objective defined in (48)), the Armijo condition is equivalent to
[TABLE]
where \mathbf{d}=\mbox{\boldmath\nabla}\overline{J}(\vec{\gamma}). Furthermore, the next gradient of is also readily available:
[TABLE]
Proof.
Let \mathbf{d}=\mbox{\boldmath\nabla}\overline{J}(\vec{\gamma}). Then,
[TABLE]
∎
E.4 Specializing Theorem 5.1 to the LR model
This section specializes Theorem 5.1 to the LR-model. Let us first specialize expressions (45), (46). and (47), We start with (45). Since , the only valid choice of is [math], and . If , then iff for some . In other words, we can replace by itself. Next, consider (46): there is only one valid choice of – the all [math] vector – and for some , the matrix is exactly . Lastly, when the sum (47) becomes . We have the following corollary:
Corollary E.2**.**
Consider a LR model with parameters and groups of simple FDs , . Define the following reparameterization:
[TABLE]
Then, minimizing is equivalent to minimizing the function where , and matrix for each is given by
[TABLE]
is defined with respect to the FD-reduced pair of functions and a reduced parameter space of . Its gradient is very simple to compute, where we specialize (50):
[TABLE]
Moreover, once a minimizer of is obtained, following (51), we can compute a minimizer of by setting
[TABLE]
E.5 Specializing Theorem 5.1 to the model
In this section we explores Theorem 5.1 for the special case of degree-2 polynomial regression. This case is significant for three reasons. First, due to the explosion in the number of parameters, in practice one rarely runs polynomial regression of degree higher than . In fact, may be a sufficiently rich nonlinear regression model for many real-world applications. Second, this is technically already a highly non-trivial application of our general theorem. Third, this case shares some commonality with model to be described in the next section.
As before, we first specialize expressions (45), (46), and (47). To do so, we slightly change the indexing scheme of the model to simplify the presentation. In the general model, we use tuples with to index parameters. When the model is of degree , we explicitly write down the two types of indices: we use , instead of with , and we use with instead of when .
We start with (45). Since , two valid choices of are [math] and .
- •
when , for some . The set is the collection of singleton subsets of . Hence, this is similar to the linear regression situation.
- •
when , is either or . The set consists of all -subsets of for which contains one element from and one from . The set contains all singletons and -subsets of .
Next, consider (46): there are two valid choices for the pair :
- •
when , or . In that case, we have
[TABLE]
- •
when , for some ; and in this case we use to represent :
[TABLE]
Finally, we write down (47) explicitly; the valid indices for are , and (also recall the definition of in (93)):
[TABLE]
Corollary E.3**.**
Consider the model with groups of simple FDs , . Let
[TABLE]
be the original parameters, and . Define the following reparameterization:
[TABLE]
Then, minimizing is equivalent to minimizing the function where
[TABLE]
The gradient of is very simple to compute, by noticing that is defined with respect to the FD-reduced pair of functions and a reduced parameter space of . Its gradient can be computed by specializing (50):
[TABLE]
Moreover, once a minimizer of is obtained, following (51), we can compute a minimizer of by setting
[TABLE]
E.6 Proofs of results in Section 5.4
Proof of Theorem 5.2.
We begin with a similar derivation, where “relevant terms” of are the terms where contains a feature for some :
[TABLE]
The above derivation immediately yields the reparameterization given in the statement of the theorem, which we reproduce here for the sake of clarity:
[TABLE]
Note that we did not define for , . The reason we can do so, is because we can optimize out due to the following trick we have been using (as in the proof of Theorem 5.1). First, we rewrite all the terms in in terms of and , , :
[TABLE]
Since ,, does not depend on the loss term, we have
[TABLE]
By setting (102) to [math], we have for all , and thus
[TABLE]
which implies . Hence, the following always holds:
[TABLE]
Note also that,
[TABLE]
Due to the fact that , we can now write the penalty term in terms of the new parameter :
[TABLE]
∎
Proof of Proposition 5.3.
The goal is to derive the gradient of w.r.t the parameters . Since is a function of , , , the following is immediate:
[TABLE]
Next, we have to simplify to facilitate fast computation:
[TABLE]
Next, we derive the partial derivative w.r.t. for a fixed , ; in this computation we make use of (5) above:
[TABLE]
Lastly, we move on to the partial derivative w.r.t. for a fixed , , :
[TABLE]
In particular, we were able to reuse the computation of and to compute . There is, however, still one complicated term left to compute. We simplify to make its evaluation faster as follows.
[TABLE]
This completes the proof. ∎
The reference list from the paper itself. Each links out to its DOI / PubMed record.
- 1[1] M. Abadi, P. Barham, J. Chen, Z. Chen, A. Davis, J. Dean, M. Devin, S. Ghemawat, G. Irving, M. Isard, M. Kudlur, J. Levenberg, R. Monga, S. Moore, D. G. Murray, B. Steiner, P. A. Tucker, V. Vasudevan, P. Warden, M. Wicke, Y. Yu, and X. Zheng. Tensorflow: A system for large-scale machine learning. In OSDI , pages 265–283, 2016.
- 2[2] S. Abiteboul, M. Arenas, P. Barceló, M. Bienvenu, D. Calvanese, C. David, R. Hull, E. Hüllermeier, B. Kimelfeld, L. Libkin, W. Martens, T. Milo, F. Murlak, F. Neven, M. Ortiz, T. Schwentick, J. Stoyanovich, J. Su, D. Suciu, V. Vianu, and K. Yi. Research directions for principles of data management (dagstuhl perspectives workshop 16151). Dagstuhl Manifestos , 7(1):1–29, 2018.
- 3[3] S. Abiteboul, R. Hull, and V. Vianu. Foundations of Databases . Addison-Wesley, 1995.
- 4[4] M. Abo Khamis, H. Q. Ngo, X. Nguyen, D. Olteanu, and M. Schleich. AC/DC: In-database learning thunderstruck. In Data Management for End-To-End Machine Learning , DEEM’18, pages 8:1–8:10, 2018.
- 5[5] M. Abo Khamis, H. Q. Ngo, X. Nguyen, D. Olteanu, and M. Schleich. In-database learning with sparse tensors. In PODS , pages 325–340, 2018.
- 6[6] M. Abo Khamis, H. Q. Ngo, C. Ré, and A. Rudra. Joins via geometric resolutions: Worst-case and beyond. In PODS , pages 213–228, 2015.
- 7[7] M. Abo Khamis, H. Q. Ngo, and A. Rudra. FAQ: questions asked frequently. Co RR , abs/1504.04044, 2015.
- 8[8] M. Abo Khamis, H. Q. Ngo, and A. Rudra. FAQ: Questions asked frequently. In PODS , pages 13–28, 2016.
