You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@madlib.apache.org by ri...@apache.org on 2015/11/15 20:43:37 UTC
[2/3] incubator-madlib git commit: SVM: Add regression and update
grouping support
SVM: Add regression and update grouping support
JIRA: MADLIB-913, MADLIB-914
This closes #1, #2
Authors:
Xiaocheng Tang <xi...@gmail.com>
Rahul Iyer <ra...@gmail.com>
Changes:
- Added regression support for SVM
- Refactored GroupIterationController to simplify state types
- Fixed multiple issues for SVM, L1, L2
- Add desp to unique_string()
- Closing #2 in this commit since that PR is rejected
Project: http://git-wip-us.apache.org/repos/asf/incubator-madlib/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-madlib/commit/f62ecdba
Tree: http://git-wip-us.apache.org/repos/asf/incubator-madlib/tree/f62ecdba
Diff: http://git-wip-us.apache.org/repos/asf/incubator-madlib/diff/f62ecdba
Branch: refs/heads/master
Commit: f62ecdbae3e00495ab7a3dd6b3c46f6284586447
Parents: a184a8a
Author: Xiaocheng Tang <xt...@pivotal.io>
Authored: Sun Nov 15 11:25:24 2015 -0800
Committer: Rahul Iyer <ri...@pivotal.io>
Committed: Sun Nov 15 11:25:24 2015 -0800
----------------------------------------------------------------------
CMakeLists.txt | 2 -
src/modules/convex/linear_svm_igd.cpp | 58 +--
src/modules/convex/task/l1.hpp | 77 ++--
src/modules/convex/task/l2.hpp | 63 +--
src/modules/convex/task/linear_svm.hpp | 50 ++-
src/ports/postgres/modules/svm/svm.py_in | 347 ++++++++++------
src/ports/postgres/modules/svm/svm.sql_in | 139 ++++---
.../postgres/modules/svm/test/linear_svm.sql_in | 321 ++++++++++++++-
.../modules/utilities/control_composite.py_in | 23 --
.../utilities/in_mem_group_control.py_in | 399 +++++++++++++------
.../postgres/modules/utilities/utilities.py_in | 25 +-
11 files changed, 1053 insertions(+), 451 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/incubator-madlib/blob/f62ecdba/CMakeLists.txt
----------------------------------------------------------------------
diff --git a/CMakeLists.txt b/CMakeLists.txt
index c00b79f..c5f40f4 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -103,8 +103,6 @@ if(CMAKE_COMPILER_IS_GNUCXX)
if(APPLE)
set(CMAKE_INCLUDE_SYSTEM_FLAG_CXX "-isystem ")
endif(APPLE)
-elseif(CMAKE_C_COMPILER_ID MATCHES "Clang")
- set(CMAKE_CXX_FLAGS "-stdlib=libstdc++")
endif(CMAKE_COMPILER_IS_GNUCXX)
# force a `m4_' prefix to all builtins
http://git-wip-us.apache.org/repos/asf/incubator-madlib/blob/f62ecdba/src/modules/convex/linear_svm_igd.cpp
----------------------------------------------------------------------
diff --git a/src/modules/convex/linear_svm_igd.cpp b/src/modules/convex/linear_svm_igd.cpp
index 2fb171e..56254b9 100644
--- a/src/modules/convex/linear_svm_igd.cpp
+++ b/src/modules/convex/linear_svm_igd.cpp
@@ -53,12 +53,10 @@ linear_svm_igd_transition::run(AnyType &args) {
// For other tuples: args[0] holds the computation state until last tuple
GLMIGDState<MutableArrayHandle<double> > state = args[0];
- const double lambda = args[6].getAs<double>();
- const bool isL2 = args[7].getAs<bool>();
- const int nTuples = args[8].getAs<int>();
-
- // initilize the state if first tuple
+ // initialize the state if first tuple
if (state.algo.numRows == 0) {
+ LinearSVM<GLMModel, GLMTuple >::epsilon = args[9].getAs<double>();;
+ LinearSVM<GLMModel, GLMTuple >::is_svc = args[10].getAs<bool>();;
if (!args[3].isNull()) {
GLMIGDState<ArrayHandle<double> > previousState = args[3];
state.allocate(*this, previousState.task.dimension);
@@ -66,20 +64,20 @@ linear_svm_igd_transition::run(AnyType &args) {
} else {
// configuration parameters
uint32_t dimension = args[4].getAs<uint32_t>();
- double stepsize = args[5].getAs<double>();
-
state.allocate(*this, dimension); // with zeros
- state.task.stepsize = stepsize;
}
// resetting in either case
state.reset();
- if (isL2) {
- state.algo.loss += L2<GLMModel>::loss(state.task.model, lambda);
- L2<GLMModel>::gradient(state.task.model, lambda, state.algo.gradient);
- } else {
- state.algo.loss += L1<GLMModel>::loss(state.task.model, lambda);
- L1<GLMModel>::gradient(state.task.model, lambda, state.algo.gradient);
- }
+ state.task.stepsize = args[5].getAs<double>();
+ const double lambda = args[6].getAs<double>();
+ const bool isL2 = args[7].getAs<bool>();
+ const int nTuples = args[8].getAs<int>();
+ L1<GLMModel>::n_tuples = nTuples;
+ L2<GLMModel>::n_tuples = nTuples;
+ if (isL2)
+ L2<GLMModel>::lambda = lambda;
+ else
+ L1<GLMModel>::lambda = lambda;
}
// Skip the current record if args[1] (features) contains NULL values,
@@ -89,25 +87,23 @@ linear_svm_igd_transition::run(AnyType &args) {
} catch (const ArrayWithNullException &e) {
return args[0];
}
- if (args[2].isNull()) { return args[0]; }
+ if (args[2].isNull())
+ return args[0];
// tuple
using madlib::dbal::eigen_integration::MappedColumnVector;
GLMTuple tuple;
tuple.indVar.rebind(args[1].getAs<MappedColumnVector>().memoryHandle(),
- state.task.dimension);
- tuple.depVar = args[2].getAs<bool>() ? 1. : -1.;
+ state.task.dimension);
+ tuple.depVar = args[2].getAs<double>();
// Now do the transition step
// apply IGD with regularization
- if (isL2) {
- L2<GLMModel>::scaling(state.algo.incrModel, lambda, nTuples, state.task.stepsize);
- LinearSVMIGDAlgorithm::transition(state, tuple);
- } else {
- LinearSVMIGDAlgorithm::transition(state, tuple);
- L1<GLMModel>::clipping(state.algo.incrModel, lambda, nTuples, state.task.stepsize);
- }
- // objective function and its gradient
+ L2<GLMModel>::scaling(state.algo.incrModel, state.task.stepsize);
+ LinearSVMIGDAlgorithm::transition(state, tuple);
+ L1<GLMModel>::clipping(state.algo.incrModel, state.task.stepsize);
+ // evaluate objective function and its gradient
+ // at the old model - state.task.model
LinearSVMLossAlgorithm::transition(state, tuple);
LinearSVMGradientAlgorithm::transition(state, tuple);
@@ -153,9 +149,17 @@ linear_svm_igd_final::run(AnyType &args) {
// Aggregates that haven't seen any data just return Null.
if (state.algo.numRows == 0) { return Null(); }
+ state.algo.loss += L2<GLMModel>::loss(state.task.model);
+ state.algo.loss += L1<GLMModel>::loss(state.task.model);
+ L2<GLMModel>::gradient(state.task.model, state.algo.gradient);
+ L1<GLMModel>::gradient(state.task.model, state.algo.gradient);
+
// finalizing
LinearSVMIGDAlgorithm::final(state);
-
+ elog(NOTICE, "loss = %e, |gradient| = %e, |model| = %e\n",
+ (double) state.algo.loss,
+ state.algo.gradient.norm(),
+ state.task.model.norm());
return state;
}
http://git-wip-us.apache.org/repos/asf/incubator-madlib/blob/f62ecdba/src/modules/convex/task/l1.hpp
----------------------------------------------------------------------
diff --git a/src/modules/convex/task/l1.hpp b/src/modules/convex/task/l1.hpp
index 31e3e96..efd1fcc 100644
--- a/src/modules/convex/task/l1.hpp
+++ b/src/modules/convex/task/l1.hpp
@@ -23,33 +23,42 @@ class L1 {
public:
typedef Model model_type;
+ static double lambda;
+
+ static int n_tuples;
+
static void gradient(
- const model_type &model,
- const double &lambda,
- model_type &gradient);
+ const model_type &model,
+ model_type &gradient);
static void clipping(
- model_type &incrModel,
- const double &lambda,
- const int &n_tuples,
- const double &stepsize);
+ model_type &model,
+ const double &stepsize);
static double loss(
- const model_type &model,
- const double &lambda);
+ const model_type &model);
};
template <class Model>
+double
+L1<Model>::lambda = 0.;
+
+template <class Model>
+int
+L1<Model>::n_tuples = 1;
+
+template <class Model>
void
L1<Model>::gradient(
- const model_type &model,
- const double &lambda,
- model_type &gradient) {
- for (Index i = 0; i < model.size(); i++) {
- if (model(i) > 0) {
- gradient(i) += lambda;
- } else if (model(i) < 0) {
- gradient(i) -= lambda;
+ const model_type &model,
+ model_type &gradient) {
+ if (lambda != 0.) {
+ for (Index i = 0; i < model.size(); i++) {
+ if (model(i) > 0) {
+ gradient(i) += lambda;
+ } else if (model(i) < 0) {
+ gradient(i) -= lambda;
+ }
}
}
}
@@ -57,30 +66,30 @@ L1<Model>::gradient(
template <class Model>
void
L1<Model>::clipping(
- model_type &incrModel,
- const double &lambda,
- const int &n_tuples,
- const double &stepsize) {
- // implement the Clipping method mentioned in Tsuruoka et al. 2009
- double clip_boundry = lambda / n_tuples * stepsize;
- for (Index i = 0; i < incrModel.size(); i++) {
- if (incrModel(i) > clip_boundry) {
- incrModel(i) -= clip_boundry;
- } else if (incrModel(i) < - clip_boundry) {
- incrModel(i) += clip_boundry;
- } else { incrModel(i) = 0.; }
+ model_type &model,
+ const double &stepsize) {
+ if (lambda != 0.) {
+ // implement the Clipping method mentioned in Tsuruoka et al. 2009
+ double clip_boundry = lambda / n_tuples * stepsize;
+ for (Index i = 0; i < model.size(); i++) {
+ if (model(i) > clip_boundry) {
+ model(i) -= clip_boundry;
+ } else if (model(i) < - clip_boundry) {
+ model(i) += clip_boundry;
+ } else { model(i) = 0.; }
+ }
}
}
template <class Model>
double
L1<Model>::loss(
- const model_type &model,
- const double &lambda) {
+ const model_type &model) {
double s = 0.;
- for (Index i = 0; i < model.size(); i++) {
- s += std::abs(model(i));
- }
+ if (lambda != 0.)
+ for (Index i = 0; i < model.size(); i++) {
+ s += std::abs(model(i));
+ }
return lambda * s;
}
http://git-wip-us.apache.org/repos/asf/incubator-madlib/blob/f62ecdba/src/modules/convex/task/l2.hpp
----------------------------------------------------------------------
diff --git a/src/modules/convex/task/l2.hpp b/src/modules/convex/task/l2.hpp
index fa054c2..a2e7f2f 100644
--- a/src/modules/convex/task/l2.hpp
+++ b/src/modules/convex/task/l2.hpp
@@ -24,64 +24,67 @@ public:
typedef Model model_type;
typedef Hessian hessian_type;
+ static double lambda;
+ static int n_tuples;
+
static void gradient(
- const model_type &model,
- const double &lambda,
- model_type &gradient);
+ const model_type &model,
+ model_type &gradient);
static void scaling(
- model_type &incrModel,
- const double &lambda,
- const int &n_tuples,
- const double &stepsize);
+ model_type &model,
+ const double &stepsize);
static void hessian(
- const model_type &model,
- const double &lambda,
- hessian_type &hessian);
+ const model_type &model,
+ hessian_type &hessian);
static double loss(
- const model_type &model,
- const double &lambda);
+ const model_type &model);
};
template <class Model, class Hessian>
+double
+L2<Model, Hessian>::lambda = 0.;
+
+template <class Model, class Hessian>
+int
+L2<Model, Hessian>::n_tuples = 1;
+
+template <class Model, class Hessian>
void
L2<Model, Hessian>::gradient(
- const model_type &model,
- const double &lambda,
- model_type &gradient) {
- gradient += 2 * lambda * model;
+ const model_type &model,
+ model_type &gradient) {
+ // 1/2 * lambda * || w ||^2
+ gradient += lambda * model;
}
template <class Model, class Hessian>
void
L2<Model, Hessian>::scaling(
- model_type &incrModel,
- const double &lambda,
- const int &n_tuples,
- const double &stepsize) {
- double wscale = 1 - 2 * lambda / n_tuples * stepsize;
- if (wscale > 0) { incrModel *= wscale; }
- else { incrModel.setZero(); }
+ model_type &model,
+ const double &stepsize) {
+ double wscale = 1 - lambda / n_tuples * stepsize;
+ if (wscale > 0) { model *= wscale; }
+ else { model.setZero(); }
}
template <class Model, class Hessian>
void
L2<Model, Hessian>::hessian(
- const model_type &model,
- const double &lambda,
- hessian_type &hessian) {
+ const model_type &model,
+ hessian_type &hessian) {
int n = model.size();
- hessian += 2 * lambda * hessian.Identity(n, n);
+ hessian += lambda * hessian.Identity(n, n);
}
template <class Model, class Hessian>
double
L2<Model, Hessian>::loss(
- const model_type &model,
- const double &lambda) {
- return lambda * model.norm();
+ const model_type &model) {
+ // 1/2 * lambda * || w ||^2
+ return lambda * model.norm()*model.norm() / 2;
}
} // namespace convex
http://git-wip-us.apache.org/repos/asf/incubator-madlib/blob/f62ecdba/src/modules/convex/task/linear_svm.hpp
----------------------------------------------------------------------
diff --git a/src/modules/convex/task/linear_svm.hpp b/src/modules/convex/task/linear_svm.hpp
index 8ecf982..136d73b 100644
--- a/src/modules/convex/task/linear_svm.hpp
+++ b/src/modules/convex/task/linear_svm.hpp
@@ -16,6 +16,7 @@ namespace convex {
// Use Eigen
using namespace madlib::dbal::eigen_integration;
+
template <class Model, class Tuple>
class LinearSVM {
public:
@@ -25,6 +26,9 @@ public:
independent_variables_type;
typedef typename Tuple::dependent_variable_type dependent_variable_type;
+ static double epsilon;
+ static bool is_svc;
+
static void gradient(
const model_type &model,
const independent_variables_type &x,
@@ -48,6 +52,12 @@ public:
};
template <class Model, class Tuple>
+double LinearSVM<Model, Tuple >::epsilon = 0.;
+
+template <class Model, class Tuple>
+bool LinearSVM<Model, Tuple >::is_svc = false;
+
+template <class Model, class Tuple>
void
LinearSVM<Model, Tuple>::gradient(
const model_type &model,
@@ -55,10 +65,18 @@ LinearSVM<Model, Tuple>::gradient(
const dependent_variable_type &y,
model_type &gradient) {
double wx = dot(model, x);
- if (1 - wx * y > 0) {
- double c = -y; // minus for "-loglik"
- gradient += c * x;
- } else { gradient += 0. * x; }
+ if (is_svc) {
+ if (1 - wx * y > 0) {
+ double c = -y; // minus for "-loglik"
+ gradient += c * x;
+ }
+ }
+ else {
+ double wx_y = wx - y;
+ double c = wx_y > 0 ? 1. : -1.;
+ if (c*wx_y - epsilon > 0.)
+ gradient += c * x;
+ }
}
template <class Model, class Tuple>
@@ -69,10 +87,18 @@ LinearSVM<Model, Tuple>::gradientInPlace(
const dependent_variable_type &y,
const double &stepsize) {
double wx = dot(model, x);
- if (1. - wx * y > 0.) {
- double c = -y; // minus for "-loglik"
- model -= stepsize * c * x;
- } else { }
+ if (is_svc) {
+ if (1. - wx * y > 0.) {
+ double c = -y; // minus for "-loglik"
+ model -= stepsize * c * x;
+ }
+ }
+ else {
+ double wx_y = wx - y;
+ double c = wx_y > 0 ? 1. : -1.;
+ if (c*wx_y - epsilon > 0.)
+ model -= stepsize * c * x;
+ }
}
template <class Model, class Tuple>
@@ -82,7 +108,13 @@ LinearSVM<Model, Tuple>::loss(
const independent_variables_type &x,
const dependent_variable_type &y) {
double wx = dot(model, x);
- double distance = 1. - wx * y;
+ double distance = 0.;
+ if (is_svc) {
+ distance = 1. - wx * y;
+ }
+ else {
+ distance = fabs(wx - y) - epsilon;
+ }
return distance > 0. ? distance : 0.;
}
http://git-wip-us.apache.org/repos/asf/incubator-madlib/blob/f62ecdba/src/ports/postgres/modules/svm/svm.py_in
----------------------------------------------------------------------
diff --git a/src/ports/postgres/modules/svm/svm.py_in b/src/ports/postgres/modules/svm/svm.py_in
index 3ca1d7d..c543a4a 100644
--- a/src/ports/postgres/modules/svm/svm.py_in
+++ b/src/ports/postgres/modules/svm/svm.py_in
@@ -32,19 +32,22 @@ def _compute_svm(args):
"""
{schema_madlib}.linear_svm_igd_step(
({col_ind_var})::FLOAT8[],
- CASE WHEN ({col_dep_var}) IS NULL THEN NULL
- WHEN ({col_dep_var}) = {mapped_value_for_negative} THEN FALSE
- ELSE TRUE
- END,
+ ({col_dep_var_trans})::FLOAT8,
{rel_state}.{col_grp_state},
{n_features}::INT4,
{stepsize}::FLOAT8,
{lambda}::FLOAT8,
{is_l2}::BOOLEAN,
- {col_n_tuples}
+ {col_n_tuples},
+ ({select_epsilon})::FLOAT8,
+ {is_svc}::BOOLEAN
)
""")
- it.kwargs['stepsize'] *= it.kwargs['decay_factor']
+ it.info()
+ if it.kwargs['decay_factor'] > 0:
+ it.kwargs['stepsize'] = it.kwargs['stepsize'] * it.kwargs['decay_factor']
+ else:
+ it.kwargs['stepsize'] = it.kwargs['init_stepsize'] / (it.iteration + 1)
has_converged = it.test(
"""
{iteration} >= {max_iter}
@@ -56,14 +59,12 @@ def _compute_svm(args):
# ---------------------------------------------------
-# Function to run the SVM classification algorithm
-def svm_classification(schema_madlib, source_table, model_table,
- dependent_varname, independent_varname,
- kernel_func, kernel_params, grouping_col,
- optim_params, reg_params, verbose, **kwargs):
+def svm(schema_madlib, source_table, model_table,
+ dependent_varname, independent_varname, kernel_func,
+ kernel_params, grouping_col, params, is_svc,
+ verbose, **kwargs):
"""
Executes the linear support vector classification algorithm.
-
"""
# verbosing
verbosity_level = "info" if verbose else "error"
@@ -77,20 +78,6 @@ def svm_classification(schema_madlib, source_table, model_table,
"SVM error: invalid independent_varname ('" + str(independent_varname) +
"') for source_table (" + source_table + ")!")
- # map dependent variables
- dep_labels=plpy.execute("""
- SELECT {dep} AS y
- FROM {tbl}
- WHERE ({dep}) IS NOT NULL
- GROUP BY ({dep})
- ORDER BY ({dep})
- """.format(dep=dependent_varname, tbl=source_table))
- _dep_var_mapping = ["'" + d['y'] + "'" if isinstance(d['y'], basestring)
- else str(d['y']) for d in dep_labels]
- if len(_dep_var_mapping) != 2:
- plpy.error("SVM error: Only binary classification is supported. "
- "Found more than two dependent variable values ({0})".
- format(str(_dep_var_mapping)))
dep_type = get_expr_type(dependent_varname, source_table)
if '[]' in dep_type:
plpy.error("SVM error: dependent_varname cannot be of array type!")
@@ -117,18 +104,17 @@ def svm_classification(schema_madlib, source_table, model_table,
grouping_str1 = "" if not grouping_col else grouping_col + ","
grouping_str2 = "1 = 1" if not grouping_col else grouping_col
- args = {'rel_args': unique_string(),
- 'rel_state': unique_string(),
- 'col_grp_iteration': unique_string(),
- 'col_grp_state': unique_string(),
- 'col_grp_key': unique_string(),
- 'col_n_tuples': unique_string(),
+ args = {
+ 'rel_args': unique_string(desp='rel_args'),
+ 'rel_state': unique_string(desp='rel_state'),
+ 'col_grp_iteration': unique_string(desp='col_grp_iteration'),
+ 'col_grp_state': unique_string(desp='col_grp_state'),
+ 'col_grp_key': unique_string(desp='col_grp_key'),
+ 'col_n_tuples': unique_string(desp='col_n_tuples'),
'state_type': "double precision[]",
'rel_source': source_table,
'col_ind_var': independent_varname,
- 'col_dep_var': dependent_varname,
- 'mapped_value_for_negative': _dep_var_mapping[0]
- }
+ 'col_dep_var': dependent_varname}
args.update(locals())
# variables defined above cannot be moved below this line
# -------------------------------------------------------
@@ -144,7 +130,8 @@ def svm_classification(schema_madlib, source_table, model_table,
kernel_func = next(x for x in supported_kernels if x.startswith(kernel_func))
except StopIteration:
# next() returns a StopIteration if no element found
- plpy.error("SVM Error: Invalid kernel function: {0}. Supported kernel functions are ({1})"
+ plpy.error("SVM Error: Invalid kernel function: {0}. "
+ "Supported kernel functions are ({1})"
.format(kernel_func, ','.join(sorted(supported_kernels))))
if grouping_col:
@@ -160,10 +147,45 @@ def svm_classification(schema_madlib, source_table, model_table,
"Some predefined keyword(s) ({0}) are not allowed!".format(
', '.join(intersect)))
- optim_params_dict = _extract_optim_params(schema_madlib, optim_params)
- reg_params_dict = _extract_reg_params(schema_madlib, reg_params)
- args.update(optim_params_dict)
- args.update(reg_params_dict)
+ args.update(_extract_params(schema_madlib, params))
+ args.update(_process_epsilon(is_svc, args))
+
+ if not is_svc:
+ # transform col_dep_var to binary (1 or -1) if classification
+ args.update({
+ 'col_dep_var_trans': dependent_varname,
+ 'mapping': 'NULL',
+ 'method': 'SVR'})
+ else:
+ # dependent variable mapping
+ dep_labels=plpy.execute("""
+ SELECT {dependent_varname} AS y
+ FROM {source_table}
+ WHERE ({dependent_varname}) IS NOT NULL
+ GROUP BY ({dependent_varname})
+ ORDER BY ({dependent_varname})""".format(**locals()))
+ dep_var_mapping = ["'" + d['y'] + "'" if isinstance(d['y'], basestring)
+ else str(d['y']) for d in dep_labels]
+ if len(dep_var_mapping) != 2:
+ plpy.error("SVM error: Classification currently only supports binary output")
+
+ col_dep_var_trans = (
+ """
+ CASE WHEN ({col_dep_var}) IS NULL THEN NULL
+ WHEN ({col_dep_var}) = {mapped_value_for_negative} THEN -1.0
+ ELSE 1.0
+ END
+ """
+ .format(col_dep_var=dependent_varname,
+ mapped_value_for_negative=dep_var_mapping[0])
+ )
+
+ args.update({
+ 'mapped_value_for_negative': dep_var_mapping[0],
+ 'col_dep_var_trans': col_dep_var_trans,
+ 'mapping': dep_var_mapping[0] + "," + dep_var_mapping[1],
+ 'method': 'SVC'})
+
args['stepsize'] = args['init_stepsize']
args['is_l2'] = True if args['norm'] == 'l2' else False
@@ -173,7 +195,6 @@ def svm_classification(schema_madlib, source_table, model_table,
n_iters_run = _compute_svm(args)
# organizing results
- args['mapping'] = _dep_var_mapping[0] + "," + _dep_var_mapping[1]
groupby_str = "GROUP BY {grouping_col}, {col_grp_key}".format(**args) if grouping_col else ""
using_str = "USING ({col_grp_key})".format(**args) if grouping_col else "ON TRUE"
model_table_query = """
@@ -188,8 +209,9 @@ def svm_classification(schema_madlib, source_table, model_table,
n_tuples_including_nulls - (result).num_rows_processed
AS num_rows_skipped,
NULL AS __random_feature_data,
- ARRAY[{mapping}]::{dep_type}[] AS _dep_var_mapping
- FROM (
+ ARRAY[{mapping}]::{dep_type}[] AS dep_var_mapping
+ FROM
+ (
SELECT
{schema_madlib}.internal_linear_svm_igd_result(
{col_grp_state}
@@ -198,7 +220,8 @@ def svm_classification(schema_madlib, source_table, model_table,
FROM {rel_state}
WHERE {col_grp_iteration} = {n_iters_run}
) rel_state_subq
- JOIN (
+ JOIN
+ (
SELECT
{grouping_str1}
count(*) AS n_tuples_including_nulls,
@@ -214,14 +237,15 @@ def svm_classification(schema_madlib, source_table, model_table,
using_str=using_str, **args)
plpy.execute(model_table_query)
- if type(args['lambda']) is list:
+ if isinstance(args['lambda'], list):
args['lambda_str'] = '{' + ','.join(str(e) for e in args['lambda']) + '}'
else:
args['lambda_str'] = str(args['lambda'])
+
plpy.execute("""
CREATE TABLE {summary_table} AS
SELECT
- 'svm'::text AS method,
+ '{method}'::text AS method,
'__MADLIB_VERSION__'::text AS version_number,
'{source_table}'::text AS source_table,
'{model_table}'::text AS model_table,
@@ -230,17 +254,19 @@ def svm_classification(schema_madlib, source_table, model_table,
'linear'::text AS kernel_func,
NULL::text AS kernel_params,
'{grouping_text}'::text AS grouping_col,
- 'init_stepsize={init_stepsize}, ' ||
+ 'init_stepsize={init_stepsize}, ' ||
'decay_factor={decay_factor}, ' ||
- 'max_iter={max_iter}, ' ||
+ 'max_iter={max_iter}, ' ||
'tolerance={tolerance}'::text AS optim_params,
'lambda={lambda_str}, ' ||
- 'norm={norm}, ' ||
+ 'norm={norm}, ' ||
'n_folds={n_folds}'::text AS reg_params,
count(*)::integer AS num_all_groups,
0::integer AS num_failed_groups,
sum(num_rows_processed)::bigint AS total_rows_processed,
- sum(num_rows_skipped)::bigint AS total_rows_skipped
+ sum(num_rows_skipped)::bigint AS total_rows_skipped,
+ '{epsilon}'::double precision AS epsilon,
+ '{eps_table}'::text AS eps_table
FROM {model_table};
""".format(grouping_text="NULL" if not grouping_col else grouping_col,
**args))
@@ -258,7 +284,7 @@ def svm_predict(schema_madlib, model_table, new_data_table, id_col_name,
@param output_table Name of table to store the results
"""
# suppress warnings
- with MinWarning("error"):
+ with MinWarning("warning"):
# model table
input_tbl_valid(model_table, 'SVM')
cols_in_tbl_valid(model_table, ['coef'], 'SVM')
@@ -272,6 +298,7 @@ def svm_predict(schema_madlib, model_table, new_data_table, id_col_name,
# read necessary info from summary
summary = plpy.execute("""
SELECT
+ method,
dependent_varname,
independent_varname,
kernel_func,
@@ -279,6 +306,7 @@ def svm_predict(schema_madlib, model_table, new_data_table, id_col_name,
grouping_col
FROM {summary_table}
""".format(**locals()))[0]
+ method = summary['method']
dependent_varname = summary['dependent_varname']
independent_varname = summary['independent_varname']
kernel_func = summary['kernel_func']
@@ -292,98 +320,175 @@ def svm_predict(schema_madlib, model_table, new_data_table, id_col_name,
_assert(is_var_valid(new_data_table, independent_varname),
"SVM error: independent_varname ('" + independent_varname +
"') is invalid for new_data_table (" + new_data_table + ")!")
- if id_col_name is None:
- plpy.error("SVM error: id_col_name is NULL!")
+ _assert(id_col_name is not None, "SVM error: id_col_name is NULL!")
_assert(is_var_valid(new_data_table, id_col_name),
"SVM error: id_col_name ('" + id_col_name +
"') is invalid for new_data_table (" + new_data_table + ")!")
output_tbl_valid(output_table, 'SVM')
+ if method.upper() == 'SVC':
+ pred_query = """
+ CASE WHEN {schema_madlib}.array_dot(
+ coef::double precision [],
+ {independent_varname}::double precision []) >= 0
+ THEN dep_var_mapping[2]
+ ELSE dep_var_mapping[1]
+ END
+ """.format(schema_madlib=schema_madlib,
+ independent_varname=independent_varname)
+ elif method.upper() == 'SVR':
+ pred_query = """
+ {schema_madlib}.array_dot(
+ coef::double precision [],
+ {independent_varname}::double precision [])
+ """.format(schema_madlib=schema_madlib,
+ independent_varname=independent_varname)
+ else:
+ plpy.error("SVM error: Invalid 'method' value in summary table. "
+ "'method' can only be SVC or SVR!")
if grouping_col != "NULL":
sql = """
CREATE TABLE {output_table} AS
SELECT
{id_col_name} AS id,
- CASE WHEN {schema_madlib}.array_dot(coef, {independent_varname}) >= 0
- THEN _dep_var_mapping[2]
- ELSE _dep_var_mapping[1]
- END AS prediction,
+ {pred_query} AS prediction,
{model_table}.{grouping_col} as grouping_col
- FROM {model_table}
- JOIN {new_data_table}
- ON {model_table}.{grouping_col} = {new_data_table}.{grouping_col}
- WHERE not {schema_madlib}.array_contains_null({independent_varname})
- ORDER BY grouping_col, id
+ FROM
+ {model_table}
+ JOIN
+ {new_data_table}
+ ON {model_table}.{grouping_col} = {new_data_table}.{grouping_col}
+ WHERE
+ not {schema_madlib}.array_contains_null({independent_varname})
+ ORDER BY
+ grouping_col, id
""".format(**locals())
else:
sql="""
CREATE TABLE {output_table} AS
SELECT
{id_col_name} AS id,
- CASE WHEN {schema_madlib}.array_dot(coef, {independent_varname}) >= 0
- THEN _dep_var_mapping[2]
- ELSE _dep_var_mapping[1]
- END AS prediction
- FROM {model_table}, {new_data_table}
- WHERE not {schema_madlib}.array_contains_null({independent_varname})
+ {pred_query} as prediction
+ FROM
+ {model_table},
+ {new_data_table}
+ WHERE
+ not {schema_madlib}.array_contains_null({independent_varname})
""".format(**locals())
-
plpy.execute(sql)
-def _extract_optim_params(schema_madlib, optim_params, module='SVM'):
- default_dict = dict(init_stepsize=0.01, decay_factor=0.9, max_iter=100, tolerance=1e-3)
- optim_params_types = dict(init_stepsize=float, decay_factor=float, max_iter=int, tolerance=float)
- optim_params_dict = extract_keyvalue_params(optim_params,
- optim_params_types,
- default_dict)
-
- if optim_params_dict['init_stepsize'] <= 0:
- plpy.error("{0} error: init_stepsize must be positive!".format(module))
- if optim_params_dict['decay_factor'] <= 0 or optim_params_dict['decay_factor'] > 1:
- plpy.error("{0} error: decay_factor must be in (0,1]!".format(module))
- if optim_params_dict['max_iter'] <= 0:
- plpy.error("{0} error: max_iter must be positive!".format(module))
- if optim_params_dict['tolerance'] < 0:
- plpy.error("{0} error: tolerance must be non-negative!".format(module))
-
- return optim_params_dict
-
-
-def _extract_reg_params(schema_madlib, reg_params, module='SVM'):
- default_dict = {'lambda': 0.01, 'norm': 'L2', 'n_folds': 0}
- reg_params_types_lambda_scalar = {'lambda': float, 'norm': str, 'n_folds': int}
- reg_params_types_lambda_list = {'lambda': list, 'norm': str, 'n_folds': int}
- try:
- reg_params_dict = extract_keyvalue_params(reg_params,
- reg_params_types_lambda_scalar,
- default_dict)
- is_lambda_list = False
- except ValueError:
- reg_params_dict = extract_keyvalue_params(reg_params,
- reg_params_types_lambda_list,
- default_dict)
- is_lambda_list = True
-
- if reg_params_dict['n_folds'] < 0:
- plpy.error("{0} error: n_folds must be non-negative!".format(module))
+def _process_epsilon(is_svc, args):
+ eps_table = args['eps_table']
+ grouping_col = args['grouping_col']
+ grouping_str = args['grouping_str']
+ col_grp_key = args['col_grp_key']
+ rel_source = args['rel_source']
+ rel_epsilon = ''
+ select_epsilon = ''
+ as_rel_source = '_src'
+
+ epsilon = args['epsilon']
+ if is_svc or not grouping_col or not eps_table:
+ if eps_table:
+ plpy.warning('SVM: ignoring the input epsilon table!')
+ select_epsilon = str(epsilon)
+ else:
+ rel_epsilon = unique_string(desp='rel_epsilon')
+ input_tbl_valid(eps_table, 'SVM')
+ _assert(is_var_valid(eps_table, grouping_col),
+ "SVM error: invalid column names ('" + str(grouping_col) +
+ "') for eps_table (" + eps_table + ")!")
+ plpy.execute("""
+ DROP TABLE IF EXISTS {rel_epsilon};
+ CREATE TEMPORARY TABLE {rel_epsilon} AS (
+ SELECT
+ {col_grp_key},
+ coalesce(epsilon, {epsilon}) AS epsilon
+ FROM
+ (
+ SELECT array_to_string(ARRAY[{grouping_str}], ',') AS
+ {col_grp_key}
+ FROM {rel_source}
+ GROUP BY {grouping_col}
+ ) q1
+ LEFT JOIN
+ (
+ SELECT array_to_string(ARRAY[{grouping_str}], ',') AS
+ {col_grp_key},
+ epsilon
+ FROM {eps_table}
+ ) q2
+ USING ({col_grp_key})
+ );
+ """.format(**locals()))
+
+ select_epsilon = """SELECT epsilon
+ FROM
+ {rel_epsilon}
+ WHERE
+ {rel_epsilon}.{col_grp_key} = {as_rel_source}.{col_grp_key}
+ """.format(rel_epsilon=rel_epsilon, as_rel_source=as_rel_source,
+ col_grp_key=col_grp_key)
+
+ return {'select_epsilon': select_epsilon,
+ 'epsilon': epsilon,
+ 'rel_epsilon': rel_epsilon,
+ 'as_rel_source': as_rel_source}
+
+
+def _extract_params(schema_madlib, params, module='SVM'):
+ # NOTICE: the type of values in params_default should be consistent with
+ # the types specified in params_types
+ params_default = {'init_stepsize': 0.01,
+ 'decay_factor': 0.9,
+ 'max_iter': 100,
+ 'tolerance': 1e-10,
+ 'lambda': 1.0,
+ 'norm': 'L2',
+ 'n_folds': 0,
+ 'epsilon': 0.01,
+ 'eps_table': ''}
+
+ params_types = {'init_stepsize': float,
+ 'decay_factor': float,
+ 'max_iter': int,
+ 'tolerance': float,
+ 'lambda': list,
+ 'norm': str,
+ 'n_folds': int,
+ 'epsilon': float,
+ 'eps_table': str}
+
+ params_vals = extract_keyvalue_params(params,
+ params_types,
+ params_default)
+
+ if params_vals['n_folds'] < 0:
+ plpy.error("SVM error: n_folds must be non-negative")
# FIXME
- if reg_params_dict['n_folds'] > 1:
- plpy.error("{0} error: cross-validation not implemented!".format(module))
+ _assert(params_vals['n_folds'] <= 1,
+ "SVM error: cross-validation has not been implemented")
# validate lambda
- if not is_lambda_list and reg_params_dict['lambda'] < 0:
- plpy.error("{0} error: lambda must be non-negative!".format(module))
- if is_lambda_list:
- if len(reg_params_dict['lambda']) != 1:
+ if hasattr(params_vals['lambda'], '__len__'):
+ # this check should be removed after cross validation is added
+ if len(params_vals['lambda']) != 1:
plpy.error("{0} error: lambda must be a scalar or of length 1 when n_folds is 0 or 1".format(module))
- # good for only not CV
- reg_params_dict['lambda'] = reg_params_dict['lambda'][0]
- if reg_params_dict['lambda'] < 0:
- plpy.error("{0} error: lambda must be non-negative!".format(module))
-
- reg_params_dict['norm'] = reg_params_dict['norm'].lower()
- if reg_params_dict['norm'] != 'l1' and reg_params_dict['norm'] != 'l2':
- plpy.error("{0} error: norm must be either L1 or L2!".format(module))
-
- return reg_params_dict
+ params_vals['lambda'] = params_vals['lambda'][0]
+ _assert(params_vals['lambda'] >= 0,
+ "SVM error: lambda must be non-negative!")
+ params_vals['norm'] = params_vals['norm'].lower()
+ _assert(params_vals['norm'] == 'l1' or params_vals['norm'] == 'l2',
+ "SVM error: norm must be either L1 or L2")
+ _assert(params_vals['init_stepsize'] > 0,
+ "SVM error: init_stepsize must be positive")
+ _assert(params_vals['decay_factor'] <= 1,
+ "SVM error: decay_factor must be <= 1")
+ _assert(params_vals['max_iter'] > 0,
+ "SVM error: max_iter must be positive")
+ _assert(params_vals['tolerance'] >= 0,
+ "SVM error: tolerance must be non-negative")
+ _assert(params_vals['epsilon'] >= 0,
+ "SVM error: epsilon cannot be less than 0")
+ return params_vals
http://git-wip-us.apache.org/repos/asf/incubator-madlib/blob/f62ecdba/src/ports/postgres/modules/svm/svm.sql_in
----------------------------------------------------------------------
diff --git a/src/ports/postgres/modules/svm/svm.sql_in b/src/ports/postgres/modules/svm/svm.sql_in
index 166c877..047b364 100644
--- a/src/ports/postgres/modules/svm/svm.sql_in
+++ b/src/ports/postgres/modules/svm/svm.sql_in
@@ -11,7 +11,6 @@
*
*/
/* ----------------------------------------------------------------------- */
-
m4_include(`SQLCommon.m4')
/**
@@ -370,9 +369,6 @@ File svm.sql_in documenting the training function
@endinternal
*/
------------------
-
-
DROP TYPE IF EXISTS MADLIB_SCHEMA.linear_svm_result CASCADE;
CREATE TYPE MADLIB_SCHEMA.linear_svm_result AS (
@@ -389,13 +385,16 @@ CREATE TYPE MADLIB_SCHEMA.linear_svm_result AS (
CREATE OR REPLACE FUNCTION MADLIB_SCHEMA.linear_svm_igd_transition(
state double precision[],
ind_var double precision[],
- dep_var boolean,
+ dep_var double precision,
previous_state double precision[],
dimension integer,
stepsize double precision,
reg double precision,
is_l2 boolean,
- n_tuples integer)
+ n_tuples integer,
+ epsilon double precision,
+ is_svc boolean
+)
RETURNS double precision[] AS 'MODULE_PATHNAME'
LANGUAGE C IMMUTABLE
m4_ifdef(`__HAS_FUNCTION_PROPERTIES__', `NO SQL');
@@ -413,7 +412,6 @@ RETURNS double precision[] AS 'MODULE_PATHNAME'
LANGUAGE C IMMUTABLE STRICT
m4_ifdef(`__HAS_FUNCTION_PROPERTIES__', `NO SQL');
-
/**
* @internal
* @brief Perform one iteration of the incremental gradient
@@ -421,22 +419,28 @@ m4_ifdef(`__HAS_FUNCTION_PROPERTIES__', `NO SQL');
*/
DROP AGGREGATE IF EXISTS MADLIB_SCHEMA.linear_svm_igd_step(
/*+ ind_var */ double precision[],
- /*+ dep_var */ boolean,
+ /*+ dep_var */ double precision,
/*+ previous_state */ double precision[],
/*+ dimension */ integer,
/*+ stepsize */ double precision,
/*+ reg */ double precision,
/*+ is_l2 */ boolean,
- /*+ n_tuples */ integer);
+ /*+ n_tuples */ integer,
+ /*+ epsilon */ double precision,
+ /*+ is_svc */ boolean
+);
CREATE AGGREGATE MADLIB_SCHEMA.linear_svm_igd_step(
/*+ ind_var */ double precision[],
- /*+ dep_var */ boolean,
+ /*+ dep_var */ double precision,
/*+ previous_state */ double precision[],
/*+ dimension */ integer,
/*+ stepsize */ double precision,
/*+ reg */ double precision,
/*+ is_l2 */ boolean,
- /*+ n_tuples */ integer) (
+ /*+ n_tuples */ integer,
+ /*+ epsilon */ double precision,
+ /*+ is_svc */ boolean
+ ) (
STYPE=double precision[],
SFUNC=MADLIB_SCHEMA.linear_svm_igd_transition,
m4_ifdef(`__POSTGRESQL__', `', `prefunc=MADLIB_SCHEMA.linear_svm_igd_merge,')
@@ -458,19 +462,7 @@ LANGUAGE c IMMUTABLE STRICT
m4_ifdef(`__HAS_FUNCTION_PROPERTIES__', `NO SQL');
-
-
-
-
-
-
-
-
-
------------------
-
-
-CREATE OR REPLACE FUNCTION MADLIB_SCHEMA.svm_classification(
+CREATE OR REPLACE FUNCTION MADLIB_SCHEMA.svm_regression(
source_table text,
model_table text,
dependent_varname text,
@@ -478,16 +470,17 @@ CREATE OR REPLACE FUNCTION MADLIB_SCHEMA.svm_classification(
kernel_func text,
kernel_params text,
grouping_col text,
- optim_params text,
- reg_params text,
+ params text,
verbose bool)
RETURNS void AS $$
-PythonFunction(svm, svm, svm_classification)
+ # indent according to PythonFunction
+ global is_svc
+ is_svc = False
+ PythonFunction(svm, svm, svm)
$$ LANGUAGE plpythonu VOLATILE
m4_ifdef(`__HAS_FUNCTION_PROPERTIES__', `MODIFIES SQL DATA');
--- all default value handling implemented in Python
-CREATE OR REPLACE FUNCTION MADLIB_SCHEMA.svm_classification(
+CREATE OR REPLACE FUNCTION MADLIB_SCHEMA.svm_regression(
source_table text,
model_table text,
dependent_varname text,
@@ -495,15 +488,78 @@ CREATE OR REPLACE FUNCTION MADLIB_SCHEMA.svm_classification(
kernel_func text,
kernel_params text,
grouping_col text,
- optim_params text,
- reg_params text)
+ params text)
+RETURNS void AS $$
+ SELECT MADLIB_SCHEMA.svm_regression($1, $2, $3, $4, $5, $6, $7, $8, NULL);
+$$ LANGUAGE sql VOLATILE
+m4_ifdef(`__HAS_FUNCTION_PROPERTIES__', `MODIFIES SQL DATA');
+
+CREATE OR REPLACE FUNCTION MADLIB_SCHEMA.svm_regression(
+ source_table text,
+ model_table text,
+ dependent_varname text,
+ independent_varname text,
+ kernel_func text,
+ kernel_params text,
+ grouping_col text)
+RETURNS void AS $$
+ SELECT MADLIB_SCHEMA.svm_regression($1, $2, $3, $4, $5, $6, $7, NULL);
+$$ LANGUAGE sql VOLATILE
+m4_ifdef(`__HAS_FUNCTION_PROPERTIES__', `MODIFIES SQL DATA');
+
+CREATE OR REPLACE FUNCTION MADLIB_SCHEMA.svm_regression(
+ source_table text,
+ model_table text,
+ dependent_varname text,
+ independent_varname text,
+ kernel_func text,
+ kernel_params text)
RETURNS void AS $$
- SELECT MADLIB_SCHEMA.svm_classification($1, $2, $3, $4, $5, $6, $7, $8, $9, NULL);
+ SELECT MADLIB_SCHEMA.svm_regression($1, $2, $3, $4, $5, $6, NULL);
$$ LANGUAGE sql VOLATILE
m4_ifdef(`__HAS_FUNCTION_PROPERTIES__', `MODIFIES SQL DATA');
+CREATE OR REPLACE FUNCTION MADLIB_SCHEMA.svm_regression(
+ source_table text,
+ model_table text,
+ dependent_varname text,
+ independent_varname text,
+ kernel_func text)
+ RETURNS void AS $$
+ SELECT MADLIB_SCHEMA.svm_regression($1, $2, $3, $4, $5, NULL);
+$$ LANGUAGE sql VOLATILE
+m4_ifdef(`__HAS_FUNCTION_PROPERTIES__', `MODIFIES SQL DATA');
+CREATE OR REPLACE FUNCTION MADLIB_SCHEMA.svm_regression(
+ source_table text,
+ model_table text,
+ dependent_varname text,
+ independent_varname text)
+ RETURNS void AS $$
+ SELECT MADLIB_SCHEMA.svm_regression($1, $2, $3, $4, NULL);
+$$ LANGUAGE sql VOLATILE
+m4_ifdef(`__HAS_FUNCTION_PROPERTIES__', `MODIFIES SQL DATA');
+-----------------
+
+CREATE OR REPLACE FUNCTION MADLIB_SCHEMA.svm_classification(
+ source_table text,
+ model_table text,
+ dependent_varname text,
+ independent_varname text,
+ kernel_func text,
+ kernel_params text,
+ grouping_col text,
+ params text,
+ verbose bool)
+RETURNS void AS $$
+ # indent according to PythonFunction
+ global is_svc
+ is_svc = True
+ PythonFunction(svm, svm, svm)
+$$ LANGUAGE plpythonu VOLATILE
+m4_ifdef(`__HAS_FUNCTION_PROPERTIES__', `MODIFIES SQL DATA');
+-- all default value handling implemented in Python
CREATE OR REPLACE FUNCTION MADLIB_SCHEMA.svm_classification(
source_table text,
model_table text,
@@ -512,14 +568,12 @@ CREATE OR REPLACE FUNCTION MADLIB_SCHEMA.svm_classification(
kernel_func text,
kernel_params text,
grouping_col text,
- optim_params text)
+ params text)
RETURNS void AS $$
SELECT MADLIB_SCHEMA.svm_classification($1, $2, $3, $4, $5, $6, $7, $8, NULL);
$$ LANGUAGE sql VOLATILE
m4_ifdef(`__HAS_FUNCTION_PROPERTIES__', `MODIFIES SQL DATA');
-
-
CREATE OR REPLACE FUNCTION MADLIB_SCHEMA.svm_classification(
source_table text,
model_table text,
@@ -528,13 +582,11 @@ CREATE OR REPLACE FUNCTION MADLIB_SCHEMA.svm_classification(
kernel_func text,
kernel_params text,
grouping_col text)
- RETURNS void AS $$
+RETURNS void AS $$
SELECT MADLIB_SCHEMA.svm_classification($1, $2, $3, $4, $5, $6, $7, NULL);
$$ LANGUAGE sql VOLATILE
m4_ifdef(`__HAS_FUNCTION_PROPERTIES__', `MODIFIES SQL DATA');
-
-
CREATE OR REPLACE FUNCTION MADLIB_SCHEMA.svm_classification(
source_table text,
model_table text,
@@ -547,7 +599,6 @@ CREATE OR REPLACE FUNCTION MADLIB_SCHEMA.svm_classification(
$$ LANGUAGE sql VOLATILE
m4_ifdef(`__HAS_FUNCTION_PROPERTIES__', `MODIFIES SQL DATA');
-
CREATE OR REPLACE FUNCTION MADLIB_SCHEMA.svm_classification(
source_table text,
model_table text,
@@ -570,18 +621,15 @@ CREATE OR REPLACE FUNCTION MADLIB_SCHEMA.svm_classification(
$$ LANGUAGE sql VOLATILE
m4_ifdef(`__HAS_FUNCTION_PROPERTIES__', `MODIFIES SQL DATA');
-
-
-------Prediction
-
+------ Prediction -------------------------------------------------------------
/**
* @brief Scores the data points stored in a table using a learned linear support-vector model
* @param model_table Name of table where the learned model to be used is stored
* @param new_data_table Name of table/view containing the data points to be scored
* @param id_col Name of column in new_data_table containing the integer identifier of data points
- *
*
- *
+ *
+ *
* @param output_table Name of table to store the results
*
* @return Textual summary of the algorithm run
@@ -599,5 +647,6 @@ PythonFunction(svm, svm, svm_predict)
$$ LANGUAGE plpythonu VOLATILE
m4_ifdef(`__HAS_FUNCTION_PROPERTIES__', `MODIFIES SQL DATA');
+-- Online Help -----------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/incubator-madlib/blob/f62ecdba/src/ports/postgres/modules/svm/test/linear_svm.sql_in
----------------------------------------------------------------------
diff --git a/src/ports/postgres/modules/svm/test/linear_svm.sql_in b/src/ports/postgres/modules/svm/test/linear_svm.sql_in
index 5e8a4cc..0253c77 100644
--- a/src/ports/postgres/modules/svm/test/linear_svm.sql_in
+++ b/src/ports/postgres/modules/svm/test/linear_svm.sql_in
@@ -10,6 +10,13 @@ BEGIN
END
$$ LANGUAGE plpgsql;
+CREATE OR REPLACE FUNCTION __svr_target_cl_func(ind float8[])
+RETURNS float8 AS $$
+BEGIN
+ RETURN 1*ind[1] + 2*ind[2];
+END
+$$ LANGUAGE plpgsql;
+
CREATE OR REPLACE FUNCTION __svm_random_ind(d INT)
RETURNS float8[] AS $$
DECLARE
@@ -48,8 +55,93 @@ BEGIN
END
$$ LANGUAGE plpgsql;
+CREATE OR REPLACE FUNCTION svr_generate_cls_data(
+ output_table text, num int, dim int)
+RETURNS VOID AS $$
+DECLARE
+ temp_table text;
+BEGIN
+ temp_table := 'madlib_temp_' || output_table;
+ EXECUTE '
+ CREATE TABLE ' || temp_table || ' AS
+ SELECT
+ subq.val AS id,
+ __svm_random_ind(' || dim || ') AS ind
+ FROM
+ (SELECT generate_series(1, ' || num || ') AS val) subq';
+ EXECUTE '
+ CREATE TABLE ' || output_table || ' AS
+ SELECT id, ind, __svr_target_cl_func(ind) AS label
+ FROM ' || temp_table;
+END
+$$ LANGUAGE plpgsql;
+
SELECT svm_generate_cls_data('svm_train_data', 1000, 4);
SELECT svm_generate_cls_data('svm_test_data', 1000, 4);
+SELECT svr_generate_cls_data('svr_train_data', 1000, 4);
+SELECT svr_generate_cls_data('svr_test_data', 1000, 4);
+
+-- check the default values
+DROP TABLE IF EXISTS svr_model, svr_model_summary;
+SELECT svm_regression(
+ 'svr_train_data',
+ 'svr_model',
+ 'label',
+ 'ind');
+\x on
+SELECT * FROM svr_model;
+SELECT * FROM svr_model_summary;
+\x off
+SELECT
+ assert(
+ norm1(coef) < 4,
+ 'optimal coef should be close to [1, 2, 0, 0]!')
+FROM svr_model;
+
+-- check the use of l1 norm
+DROP TABLE IF EXISTS svr_model, svr_model_summary;
+SELECT svm_regression(
+ 'svr_train_data',
+ 'svr_model',
+ 'label',
+ 'ind',
+ NULL,
+ NULL,
+ NULL,
+ 'init_stepsize=0.01, max_iter=50, lambda=2, norm=l1, epsilon=0.01',
+ false);
+DROP TABLE IF EXISTS svr_test_result;
+SELECT svm_predict('svr_model', 'svr_train_data', 'id', 'svr_test_result');
+\x on
+SELECT * FROM svr_model;
+\x off
+SELECT
+ assert(
+ avg(subq.err) < 0.1,
+ 'prediction error is too large!')
+FROM
+ (
+ SELECT
+ train.id,
+ abs(train.label - test.prediction) AS err
+ FROM svr_train_data AS train, svr_test_result AS test
+ WHERE train.id = test.id
+ ) AS subq;
+
+-- by default using epsilon == 0.1
+DROP TABLE IF EXISTS svr_model, svr_model_summary;
+SELECT svm_regression(
+ 'svr_train_data',
+ 'svr_model',
+ 'label',
+ 'ind',
+ NULL,
+ NULL,
+ NULL,
+ 'init_stepsize=1, max_iter=10, lambda=2');
+SELECT
+ assert(epsilon > 0,'default epsilon is positive!')
+FROM svr_model_summary;
-- Example usage for LINEAR classification, replace the above by
SELECT svm_classification(
@@ -118,9 +210,8 @@ SELECT svm_classification(
'ind',
NULL, -- kernel_func
NULL, -- kernel_pararms
- NULL, --grouping_col
- 'init_stepsize=0.03, decay_factor=1, max_iter=5, tolerance=0',
- 'lambda=0',
+ NULL, -- grouping_col
+ 'init_stepsize=0.03, decay_factor=1, max_iter=5, tolerance=0, lambda=0',
true -- verbose
);
\x on
@@ -139,8 +230,7 @@ SELECT svm_classification(
NULL, -- kernel_func
NULL, -- kernel_pararms
NULL, --grouping_col
- 'init_stepsize=0.03, decay_factor=1, max_iter=5, tolerance=0',
- 'lambda=1'
+ 'init_stepsize=0.03, decay_factor=1, max_iter=5, tolerance=0, lambda=1'
);
\x on
SELECT * FROM svm_model_small_norm2;
@@ -164,8 +254,7 @@ SELECT svm_classification(
NULL, -- kernel_func
NULL, -- kernel_pararms
NULL, --grouping_col
- 'init_stepsize=0.03, decay_factor=1, max_iter=5, tolerance=0',
- 'lambda=1, norm=L1'
+ 'init_stepsize=0.03, decay_factor=1, max_iter=5, tolerance=0, lambda=1, norm=L1'
);
\x on
SELECT * FROM svm_model_very_sparse;
@@ -205,8 +294,7 @@ SELECT svm_classification(
NULL, -- kernel_func
NULL, -- kernel_pararms
NULL, --grouping_col
- 'init_stepsize=0.03, decay_factor=0.9, max_iter=5, tolerance=0',
- 'lambda={0.001}',
+ 'init_stepsize=0.03, decay_factor=0.9, max_iter=5, tolerance=0, lambda={0.001}',
true -- verbose
);
SELECT norm_of_gradient FROM svm_model;
@@ -288,8 +376,7 @@ SELECT svm_classification(
NULL, -- kernel_func
NULL, -- kernel_pararms
'gid', --grouping_col
- 'init_stepsize=0.03, decay_factor=0.9, max_iter=5, tolerance=0',
- 'lambda=0.001',
+ 'init_stepsize=0.03, decay_factor=0.9, max_iter=5, tolerance=0, lambda=0.001',
TRUE -- verbose
);
\x on
@@ -323,8 +410,7 @@ SELECT svm_classification(
NULL, -- kernel_func
NULL, -- kernel_pararms
NULL, --grouping_col
- 'init_stepsize=0.03, decay_factor=0.9, max_iter=5, tolerance=0',
- 'lambda=0.001',
+ 'init_stepsize=0.03, decay_factor=0.9, max_iter=5, tolerance=0, lambda=0.001',
true -- verbose
);
\x on
@@ -336,3 +422,212 @@ DROP TABLE IF EXISTS svm_test_predict CASCADE;
SELECT svm_predict('svm_model_expression', 'svm_test_normalized', 'id', 'svm_test_predict');
SELECT * FROM svm_test_predict;
+DROP TABLE IF EXISTS abalone_train_small_tmp;
+CREATE TABLE abalone_train_small_tmp (
+ sex TEXT,
+ id SERIAL NOT NULL,
+ length DOUBLE PRECISION,
+ diameter DOUBLE PRECISION,
+ height DOUBLE PRECISION,
+ whole DOUBLE PRECISION,
+ shucked DOUBLE PRECISION,
+ viscera DOUBLE PRECISION,
+ shell DOUBLE PRECISION,
+ rings INTEGER);
+
+INSERT INTO abalone_train_small_tmp(id,sex,length,diameter,height,whole,shucked,viscera,shell,rings) VALUES
+(1040,'F',0.66,0.475,0.18,1.3695,0.641,0.294,0.335,6),
+(3160,'F',0.34,0.255,0.085,0.204,0.097,0.021,0.05,6),
+(3984,'F',0.585,0.45,0.125,0.874,0.3545,0.2075,0.225,6),
+(861,'F',0.595,0.475,0.16,1.1405,0.547,0.231,0.271,6),
+(932,'F',0.445,0.335,0.11,0.4355,0.2025,0.1095,0.1195,6),
+(1585,'F',0.515,0.375,0.11,0.6065,0.3005,0.131,0.15,6),
+(3187,'F',0.47,0.36,0.11,0.4965,0.237,0.127,0.13,6),
+(3202,'F',0.385,0.3,0.1,0.2725,0.1115,0.057,0.08,6),
+(949,'F',0.475,0.36,0.12,0.5915,0.3245,0.11,0.127,6),
+(2582,'F',0.53,0.42,0.17,0.828,0.41,0.208,0.1505,6),
+(2551,'I',0.28,0.22,0.08,0.1315,0.066,0.024,0.03,5),
+(1246,'I',0.385,0.28,0.09,0.228,0.1025,0.042,0.0655,5),
+(819,'I',0.35,0.25,0.07,0.18,0.0655,0.048,0.054,6),
+(297,'I',0.275,0.205,0.075,0.1105,0.045,0.0285,0.035,6),
+(3630,'I',0.27,0.205,0.05,0.084,0.03,0.0185,0.029,6),
+(2196,'I',0.26,0.215,0.08,0.099,0.037,0.0255,0.045,5),
+(2343,'I',0.255,0.185,0.07,0.075,0.028,0.018,0.025,6),
+(49,'I',0.325,0.245,0.07,0.161,0.0755,0.0255,0.045,6),
+(2185,'I',0.32,0.235,0.08,0.1485,0.064,0.031,0.045,6),
+(2154,'I',0.28,0.2,0.075,0.1225,0.0545,0.0115,0.035,5),
+(1996,'I',0.32,0.24,0.07,0.133,0.0585,0.0255,0.041,6),
+(126,'I',0.27,0.195,0.06,0.073,0.0285,0.0235,0.03,5),
+(1227,'I',0.35,0.27,0.075,0.215,0.1,0.036,0.065,6),
+(3969,'I',0.375,0.29,0.095,0.2875,0.123,0.0605,0.08,6),
+(2505,'I',0.31,0.24,0.105,0.2885,0.118,0.065,0.083,6),
+(2039,'I',0.28,0.215,0.08,0.132,0.072,0.022,0.033,5),
+(829,'I',0.41,0.325,0.1,0.394,0.208,0.0655,0.106,6),
+(3197,'I',0.325,0.245,0.075,0.1495,0.0605,0.033,0.045,5),
+(1447,'I',0.44,0.34,0.105,0.369,0.164,0.08,0.1015,5),
+(2821,'I',0.375,0.285,0.09,0.2545,0.119,0.0595,0.0675,6),
+(1828,'I',0.34,0.26,0.085,0.1885,0.0815,0.0335,0.06,6),
+(2002,'I',0.36,0.27,0.085,0.2185,0.1065,0.038,0.062,6),
+(785,'I',0.215,0.155,0.06,0.0525,0.021,0.0165,0.015,5),
+(2199,'I',0.27,0.19,0.08,0.081,0.0265,0.0195,0.03,6),
+(3527,'I',0.335,0.26,0.085,0.192,0.097,0.03,0.054,6),
+(466,'I',0.175,0.125,0.05,0.0235,0.008,0.0035,0.008,5),
+(425,'I',0.26,0.2,0.07,0.092,0.037,0.02,0.03,6),
+(1825,'I',0.185,0.135,0.04,0.027,0.0105,0.0055,0.009,5),
+(3815,'I',0.38,0.275,0.095,0.2425,0.106,0.0485,0.21,6),
+(2503,'I',0.285,0.21,0.07,0.109,0.044,0.0265,0.033,5),
+(3998,'I',0.36,0.27,0.09,0.2075,0.098,0.039,0.062,6),
+(333,'I',0.3,0.22,0.08,0.121,0.0475,0.042,0.035,5),
+(1837,'I',0.415,0.31,0.09,0.2815,0.1245,0.0615,0.085,6),
+(2813,'I',0.24,0.17,0.05,0.0545,0.0205,0.016,0.0155,5),
+(930,'I',0.44,0.345,0.13,0.4495,0.209,0.0835,0.134,6),
+(1436,'I',0.385,0.3,0.09,0.247,0.1225,0.044,0.0675,5),
+(3972,'I',0.4,0.295,0.095,0.252,0.1105,0.0575,0.066,6),
+(1433,'I',0.365,0.255,0.08,0.1985,0.0785,0.0345,0.053,5),
+(1252,'I',0.405,0.285,0.09,0.2645,0.1265,0.0505,0.075,6),
+(3439,'I',0.43,0.335,0.105,0.378,0.188,0.0785,0.09,6),
+(1250,'I',0.395,0.27,0.1,0.2985,0.1445,0.061,0.082,5),
+(2865,'I',0.31,0.23,0.07,0.1245,0.0505,0.0265,0.038,6),
+(3411,'I',0.415,0.31,0.105,0.3595,0.167,0.083,0.0915,6),
+(1539,'I',0.355,0.27,0.075,0.1775,0.079,0.0315,0.054,6),
+(1990,'I',0.28,0.21,0.075,0.1195,0.053,0.0265,0.03,6),
+(1771,'I',0.455,0.335,0.105,0.422,0.229,0.0865,0.1,6),
+(2291,'I',0.325,0.27,0.1,0.185,0.08,0.0435,0.065,6),
+(3381,'I',0.19,0.13,0.045,0.0265,0.009,0.005,0.009,5),
+(1545,'I',0.37,0.27,0.095,0.2175,0.097,0.046,0.065,6),
+(652,'I',0.335,0.245,0.09,0.1665,0.0595,0.04,0.06,6),
+(3434,'I',0.365,0.27,0.105,0.2155,0.0915,0.0475,0.063,6),
+(2004,'I',0.375,0.28,0.08,0.226,0.105,0.047,0.065,6),
+(2000,'I',0.35,0.25,0.07,0.1605,0.0715,0.0335,0.046,6),
+(3946,'I',0.235,0.175,0.065,0.0615,0.0205,0.02,0.019,6),
+(177,'I',0.315,0.21,0.06,0.125,0.06,0.0375,0.035,5),
+(920,'I',0.41,0.31,0.09,0.3335,0.1635,0.061,0.091,6),
+(3437,'I',0.38,0.275,0.095,0.2505,0.0945,0.0655,0.075,6),
+(2630,'I',0.33,0.24,0.075,0.163,0.0745,0.033,0.048,6),
+(1092,'I',0.45,0.33,0.11,0.3685,0.16,0.0885,0.102,6),
+(3476,'I',0.4,0.315,0.085,0.2675,0.116,0.0585,0.0765,6),
+(3526,'I',0.33,0.23,0.085,0.1695,0.079,0.026,0.0505,6),
+(1534,'I',0.295,0.215,0.07,0.121,0.047,0.0155,0.0405,6),
+(921,'I',0.415,0.33,0.09,0.3595,0.17,0.081,0.09,6),
+(2206,'I',0.275,0.22,0.08,0.1365,0.0565,0.0285,0.042,6),
+(1218,'I',0.315,0.23,0.08,0.1375,0.0545,0.031,0.0445,5),
+(1998,'I',0.335,0.25,0.08,0.1695,0.0695,0.044,0.0495,6),
+(2455,'I',0.275,0.2,0.065,0.092,0.0385,0.0235,0.027,5),
+(2548,'I',0.23,0.18,0.05,0.064,0.0215,0.0135,0.02,5),
+(3996,'I',0.245,0.175,0.055,0.0785,0.04,0.018,0.02,5),
+(3408,'I',0.35,0.265,0.08,0.192,0.081,0.0465,0.053,6),
+(3907,'M',0.245,0.18,0.065,0.0635,0.0245,0.0135,0.02,4),
+(3850,'M',0.385,0.3,0.115,0.3435,0.1645,0.085,0.1025,6),
+(124,'M',0.37,0.265,0.075,0.214,0.09,0.051,0.07,6),
+(2583,'M',0.53,0.41,0.14,0.681,0.3095,0.1415,0.1835,6),
+(526,'M',0.175,0.125,0.04,0.024,0.0095,0.006,0.005,4),
+(2184,'M',0.495,0.4,0.155,0.8085,0.2345,0.1155,0.35,6),
+(2132,'M',0.32,0.24,0.08,0.18,0.08,0.0385,0.055,6),
+(651,'M',0.255,0.18,0.065,0.079,0.034,0.014,0.025,5),
+(612,'M',0.195,0.145,0.05,0.032,0.01,0.008,0.012,4),
+(958,'M',0.5,0.39,0.135,0.6595,0.3145,0.1535,0.1565,6),
+(3174,'M',0.35,0.265,0.09,0.2265,0.0995,0.0575,0.065,6),
+(265,'M',0.27,0.2,0.08,0.1205,0.0465,0.028,0.04,6),
+(519,'M',0.325,0.23,0.09,0.147,0.06,0.034,0.045,4),
+(2382,'M',0.155,0.115,0.025,0.024,0.009,0.005,0.0075,5),
+(698,'M',0.28,0.205,0.1,0.1165,0.0545,0.0285,0.03,5),
+(2381,'M',0.175,0.135,0.04,0.0305,0.011,0.0075,0.01,5),
+(516,'M',0.27,0.195,0.08,0.1,0.0385,0.0195,0.03,6),
+(831,'M',0.415,0.305,0.1,0.325,0.156,0.0505,0.091,6),
+(3359,'M',0.285,0.215,0.075,0.106,0.0415,0.023,0.035,5);
+
+DROP TABLE IF EXISTS abalone_train_small;
+CREATE TABLE abalone_train_small AS (
+ SELECT * FROM abalone_train_small_tmp
+);
+
+-- create epsilon input table
+
+DROP TABLE IF EXISTS abalone_eps;
+CREATE TABLE abalone_eps (
+ sex TEXT,
+ epsilon DOUBLE PRECISION);
+
+INSERT INTO abalone_eps(sex, epsilon) VALUES
+('I', 0.2),
+('M', 0.05);
+
+-- solve it with grouping and table of epsilon as inputs
+
+DROP TABLE IF EXISTS svr_mdl, svr_mdl_summary;
+SELECT madlib.svm_regression(
+ 'abalone_train_small',
+ 'svr_mdl',
+ 'rings',
+ 'ARRAY[1,diameter,shell,shucked,length]',
+ NULL,NULL,'sex',
+ 'max_iter=50, init_stepsize=1, decay_factor=0.9, tolerance=1e-16, epsilon = 50, eps_table=abalone_eps',
+ false);
+SELECT * FROM svr_mdl;
+
+
+DROP TABLE IF EXISTS svr_mdl_i, svr_mdl_i_summary;
+SELECT madlib.svm_regression(
+ 'abalone_train_small',
+ 'svr_mdl_i',
+ 'rings',
+ 'ARRAY[1,diameter,shell,shucked,length]',
+ NULL,NULL,'sex',
+ 'max_iter=50, init_stepsize=1, decay_factor=0.9, tolerance=1e-16, epsilon = 0.2',
+ false);
+SELECT * FROM svr_mdl_i where sex = 'I';
+
+DROP TABLE IF EXISTS svr_mdl_m, svr_mdl_m_summary;
+SELECT madlib.svm_regression(
+ 'abalone_train_small',
+ 'svr_mdl_m',
+ 'rings',
+ 'ARRAY[1,diameter,shell,shucked,length]',
+ NULL,NULL,'sex',
+ 'max_iter=50, init_stepsize=1, decay_factor=0.9, tolerance=1e-16, epsilon = 0.05',
+ false);
+SELECT * FROM svr_mdl_m where sex = 'M';
+
+DROP TABLE IF EXISTS svr_mdl_f, svr_mdl_f_summary;
+SELECT madlib.svm_regression(
+ 'abalone_train_small',
+ 'svr_mdl_f',
+ 'rings',
+ 'ARRAY[1,diameter,shell,shucked,length]',
+ NULL,NULL,'sex',
+ 'max_iter=50, init_stepsize=1, decay_factor=0.9, tolerance=1e-16, epsilon = 50',
+ false);
+SELECT * FROM svr_mdl_f where sex = 'F';
+
+-- verify that the results are the same
+
+SELECT assert(
+ abs_err < 1e-5,
+ 'SVR with epsilon table input: Wrong results!')
+FROM (
+ SELECT
+ abs(t1.norm_of_gradient - t2.norm_of_gradient) AS abs_err
+ FROM svr_mdl_f AS t1 JOIN svr_mdl AS t2 USING (sex)
+ where sex = 'F'
+) AS q1;
+
+SELECT assert(
+ rel_err < 1e-1,
+ 'SVR with epsilon table input: Wrong results!')
+FROM (
+ SELECT
+ relative_error(t1.norm_of_gradient, t2.norm_of_gradient) AS rel_err
+ FROM svr_mdl_i AS t1 JOIN svr_mdl AS t2 USING (sex)
+ where sex = 'I'
+) AS q1;
+
+SELECT assert(
+ rel_err < 1e-1,
+ 'SVR with epsilon table input: Wrong results!')
+FROM (
+ SELECT
+ relative_error(t1.norm_of_gradient, t2.norm_of_gradient) AS rel_err
+ FROM svr_mdl_m AS t1 JOIN svr_mdl AS t2 USING (sex)
+ where sex = 'M'
+) AS q1;
+
http://git-wip-us.apache.org/repos/asf/incubator-madlib/blob/f62ecdba/src/ports/postgres/modules/utilities/control_composite.py_in
----------------------------------------------------------------------
diff --git a/src/ports/postgres/modules/utilities/control_composite.py_in b/src/ports/postgres/modules/utilities/control_composite.py_in
index 63d8aef..2852c63 100644
--- a/src/ports/postgres/modules/utilities/control_composite.py_in
+++ b/src/ports/postgres/modules/utilities/control_composite.py_in
@@ -19,29 +19,6 @@ from utilities import unique_string
_unique_string = unique_string
-class MinWarning:
- """
- @brief A wrapper for setting the level of logs going into client
- """
-
- def __init__(self, warningLevel='error'):
- self.warningLevel = warningLevel
-
- def __enter__(self):
- self.oldMsgLevel = plpy.execute("""
- SELECT setting FROM pg_settings WHERE name='client_min_messages'
- """)[0]['setting']
- plpy.execute("""
- SET client_min_messages = {warningLevel}
- """.format(warningLevel=self.warningLevel))
- return self
-
- def __exit__(self, *args):
- plpy.execute("""
- SET client_min_messages = {oldMsgLevel};
- """.format(oldMsgLevel=self.oldMsgLevel))
-
-
class IterationControllerComposite:
"""
@brief Abstraction for implementing driver functions in PL/Python
http://git-wip-us.apache.org/repos/asf/incubator-madlib/blob/f62ecdba/src/ports/postgres/modules/utilities/in_mem_group_control.py_in
----------------------------------------------------------------------
diff --git a/src/ports/postgres/modules/utilities/in_mem_group_control.py_in b/src/ports/postgres/modules/utilities/in_mem_group_control.py_in
index 79a26c4..d89212b 100644
--- a/src/ports/postgres/modules/utilities/in_mem_group_control.py_in
+++ b/src/ports/postgres/modules/utilities/in_mem_group_control.py_in
@@ -7,6 +7,141 @@
import plpy
from control import MinWarning
from utilities import unique_string
+from collections import namedtuple
+from collections import Iterable
+
+
+class BaseState(object):
+ """@brief Abstraction for intermediate iteration state"""
+ def __init__(self, **kwargs):
+ self._state = {}
+ self._is_none = None
+ self.initialize(**kwargs)
+
+ def __len__(self):
+ return len(self._state)
+
+ def __del__(self):
+ del self._state
+
+ def __getitem__(self, k):
+ return self._state[k]
+
+ def __setitem__(self, k, v):
+ self._state[k] = v
+
+ @property
+ def keys(self):
+ return self._state.keys()
+
+ @property
+ def values(self):
+ if self.is_none():
+ return []
+ return [s for x in self._state.values() for s in x]
+
+ def delete(self, keys_to_remove):
+ for k in keys_to_remove:
+ try:
+ del self._state[k]
+ except KeyError:
+ pass
+ self._is_none = None
+
+ def initialize(self,
+ col_grp_key='',
+ col_grp_state='',
+ ret_states=None, **kwargs):
+ self.update(col_grp_key, col_grp_state, ret_states)
+
+ def update(self, col_grp_key, col_grp_state, ret_states):
+ failed_grp_keys = []
+ if ret_states is None:
+ return failed_grp_keys
+ t0 = ret_states[0]
+ # no key column in table ret_states
+ if col_grp_key not in t0:
+ return failed_grp_keys
+ # initialize state to None
+ if col_grp_state == '':
+ self._is_none = True
+ for s in ret_states:
+ self._state[s[col_grp_key]] = None
+ return failed_grp_keys
+ for t in ret_states:
+ _grp_key, _grp_state = t[col_grp_key], t[col_grp_state]
+ if _grp_state is None:
+ failed_grp_keys.append(_grp_key)
+ else:
+ self._state[_grp_key] = _grp_state
+ # no need to update if all failed
+ if len(failed_grp_keys) < len(self):
+ self._is_none = False
+ return failed_grp_keys
+
+ # entries in self not in other are kept
+ def update_from_state(self, other, keys=None):
+ if not isinstance(other, BaseState):
+ return
+ if keys is None:
+ self._state.update(other._state)
+ else:
+ for k in keys:
+ self[k] = other[k]
+ # reset cache
+ self._is_none = None
+
+ def sync_from(self, other):
+ self._state = {}
+ self.update_from_state(other)
+ self._is_none = other.is_none()
+
+ def is_none(self):
+ if self._is_none is None:
+ self._is_none = True
+ for k, v in self._state.iteritems():
+ if v is not None:
+ self._is_none = False
+ break
+ return self._is_none
+
+ def interpret(self, schema_madlib, state_type, keys=None):
+ if keys is None:
+ keys = self.keys
+ elif isinstance(keys, str) or not isinstance(keys, Iterable):
+ keys = [keys]
+ s = dict.fromkeys(keys)
+ plan = plpy.prepare(
+ """
+ SELECT
+ (result).loss AS loss,
+ (result).norm_of_gradient AS norm_of_gradient
+ FROM (
+ SELECT
+ {schema_madlib}.internal_linear_svm_igd_result($1)
+ AS result
+ ) subq
+ """.format(schema_madlib=schema_madlib), [state_type])
+ for k in keys:
+ s[k] = plpy.execute(plan, [self._state[k]])[0]
+ return s
+
+
+class Bytea8State(BaseState):
+ """@brief bytea8 type state"""
+ def __init__(self, **kwargs):
+ super(Bytea8State, self).__init__(**kwargs)
+
+ @property
+ def values(self):
+ return self._state.values()
+
+
+def state_factory(is_bytea8, **kwargs):
+ if is_bytea8:
+ return Bytea8State(**kwargs)
+ else:
+ return BaseState(**kwargs)
class GroupIterationController:
@@ -34,17 +169,18 @@ class GroupIterationController:
self.is_group_null = True if arg_dict["grouping_col"] is None else False
self.kwargs = dict(arg_dict)
self.kwargs.update(
+ as_rel_source=arg_dict.get('as_rel_source', '_src'),
state_type=arg_dict.get('state_type', 'double precision[]').format(**arg_dict),
- col_grp_null=unique_string(),
- col_n_tuples=self.kwargs.get('col_n_tuples', unique_string()),
- col_grp_key=self.kwargs.get('col_grp_key', unique_string()),
- grouping_col=("NULL" if arg_dict["grouping_col"] is None
+ col_grp_null=unique_string(desp='col_grp_null'),
+ col_n_tuples=self.kwargs.get('col_n_tuples',
+ unique_string(desp='col_n_tuples')),
+ col_grp_key=self.kwargs.get('col_grp_key',
+ unique_string(desp='col_grp_key')),
+ grouping_col=("NULL"
+ if arg_dict["grouping_col"] is None
else arg_dict["grouping_col"]),
)
self.grp_to_n_tuples = {}
- self.new_states = {}
- self.old_states = {}
- self.finished_states = {}
self.failed_grp_keys = []
self.is_state_type_bytea8 = False
@@ -56,8 +192,52 @@ class GroupIterationController:
else:
plpy.error("Internal error: unexpected state type!")
+ self.new_states = state_factory(self.is_state_type_bytea8)
+ self.old_states = state_factory(self.is_state_type_bytea8)
+ self.finished_states = state_factory(self.is_state_type_bytea8)
+
+ self.group_param = self._init_group_param()
+
+ def _init_group_param(self):
+ _grp_key = ("array_to_string(ARRAY[{grouping_str}], ',')"
+ .format(grouping_str=self.kwargs['grouping_str']))
+ _select_rel_state = ("SELECT "
+ "grp_key AS {col_grp_key},"
+ "state AS {col_grp_state} "
+ "FROM {schema_madlib}._gen_state($1, NULL, $2)"
+ .format(**self.kwargs))
+ _select_n_tuples = ("SELECT "
+ "unnest($3) AS {col_grp_key}, "
+ "unnest($4) AS {col_n_tuples}"
+ .format(**self.kwargs))
+ _using_str="ON TRUE"
+ _grouped_state_type="float8[]"
+ _groupby_str=""
+ if not self.is_group_null:
+ _groupby_str = "GROUP BY {grouping_col}, {col_grp_key}".format(
+ **self.kwargs)
+ _using_str = "USING ({col_grp_key})".format(**self.kwargs)
+ _grp_key = self.kwargs['col_grp_key']
+ if self.is_state_type_bytea8:
+ _select_rel_state = ("SELECT "
+ "unnest($1) AS {col_grp_key}, "
+ "unnest($2) AS {col_grp_state}"
+ "".format(**self.kwargs))
+ _grouped_state_type = "{schema_madlib}.bytea8[]".format(**self.kwargs)
+ GroupParam = namedtuple('GroupParam',
+ 'groupby_str, using_str,'
+ 'select_rel_state,grouped_state_type,'
+ 'grp_key, select_n_tuples')
+ return GroupParam(groupby_str=_groupby_str,
+ using_str=_using_str,
+ select_rel_state=_select_rel_state,
+ grp_key=_grp_key,
+ select_n_tuples=_select_n_tuples,
+ grouped_state_type=_grouped_state_type)
+
def __enter__(self):
- with MinWarning('warning'):
+ verbosity_level = self.kwargs.get('verbosity_level', 'warning')
+ with MinWarning(verbosity_level):
############################
# create state table
# currently assuming that groups is passed as a valid array
@@ -100,26 +280,44 @@ class GroupIterationController:
############################
# initialize states
- ret_states = plpy.execute("SELECT * FROM " + self.kwargs['rel_state'])
- for state in ret_states:
- self.new_states[state[self.kwargs['col_grp_key']]] = None
- self.grp_to_n_tuples[state[self.kwargs['col_grp_key']]] = \
- long(state[self.kwargs['col_n_tuples']])
+ rel_state_str = self.kwargs['rel_state']
+ col_grp_key = self.kwargs['col_grp_key']
+ col_n_tuples = self.kwargs['col_n_tuples']
+ ret_states = plpy.execute("SELECT * FROM " + rel_state_str)
+ self.new_states.initialize(col_grp_key=col_grp_key,
+ col_grp_state='',
+ ret_states=ret_states)
+ for s in ret_states:
+ self.grp_to_n_tuples[s[col_grp_key]] = long(s[col_n_tuples])
self.in_with = True
return self
+ def info(self):
+ """ Logging intermediate state information """
+ if not self.kwargs['verbose']:
+ return
+ group_param = self.group_param
+ schema_madlib = self.kwargs['schema_madlib']
+ res = self.new_states.interpret(schema_madlib,
+ group_param.grouped_state_type)
+ for grp, t in res.iteritems():
+ loss, normg = t['loss'], t['norm_of_gradient']
+ iteration = self.iteration
+ output_str = "DEBUG: \
+ grp = {grp:10s}, \
+ iter = {iteration:5d}, \
+ loss = {loss:.5e}, \
+ |gradient| = {normg:.5e}, \
+ stepsize = {stepsize:.5e}"
+ plpy.notice(output_str.format(
+ grp=grp, iteration=iteration,
+ loss=loss, normg=normg,
+ **self.kwargs))
+
def final(self):
""" Store the final converged state to a table for output """
- if self.is_state_type_bytea8:
- unnest_str = "unnest($1) AS {col_grp_key}, unnest($2) AS {col_grp_state}".format(**self.kwargs)
- grouped_state_type = "{0}.bytea8[]".format(self.kwargs['schema_madlib'])
- else:
- unnest_str = ("grp_key AS {col_grp_key}, state AS {col_grp_state} "
- "FROM {schema_madlib}._gen_state($1, NULL, $2)".
- format(**self.kwargs))
- grouped_state_type = "float8[]"
-
+ group_param = self.group_param
insert_sql = """
INSERT INTO {rel_state}
SELECT
@@ -132,31 +330,21 @@ class GroupIterationController:
SELECT {grouping_col}, {col_grp_key}
FROM {rel_state}
) AS _src
- JOIN (
- SELECT {unnest_str}
- ) AS _rel_state
+ JOIN ( {select_rel_state} ) AS _rel_state
USING ({col_grp_key})
- JOIN (
- SELECT unnest($3) AS {col_grp_key},
- unnest($4) AS {col_n_tuples}
- ) AS _rel_n_tuples
+ JOIN ( {select_n_tuples} ) AS _rel_n_tuples
USING ({col_grp_key})
""".format(
iteration=self.iteration,
- unnest_str=unnest_str,
+ select_rel_state=group_param.select_rel_state,
+ select_n_tuples=group_param.select_n_tuples,
**self.kwargs)
insert_plan = plpy.prepare(insert_sql,
- ["text[]", grouped_state_type,
+ ["text[]", group_param.grouped_state_type,
"text[]", "bigint[]"])
- if self.is_state_type_bytea8:
- insert_values = self.finished_states.values()
-
- else:
- insert_values = [c for state in self.finished_states.values()
- for c in state]
- plpy.execute(insert_plan, [self.finished_states.keys(),
- insert_values,
+ plpy.execute(insert_plan, [self.finished_states.keys,
+ self.finished_states.values,
self.grp_to_n_tuples.keys(),
self.grp_to_n_tuples.values()])
plpy.execute(insert_plan, [self.failed_grp_keys,
@@ -184,19 +372,11 @@ class GroupIterationController:
@return True if \c expression in all non-failed groups is True,
otherwise False
"""
- if not self.new_states:
+ if len(self.new_states) == 0:
# self.new_states can become empty if the last of the groups failed
# in the previous update
return True
- self.is_state_type_bytea8 = False
- if self.kwargs['state_type'] == "{0}.bytea8".format(self.kwargs['schema_madlib']):
- self.is_state_type_bytea8 = True
- elif (self.kwargs['state_type'].lower() == "double precision[]" or
- self.kwargs['state_type'].lower() == "float8[]"):
- self.is_state_type_bytea8 = False
- else:
- plpy.error("Internal error: unexpected state type!")
if self.is_state_type_bytea8:
unnest_str_previous = "unnest($1) AS {col_grp_key}, unnest($2) AS _state_previous".format(**self.kwargs)
unnest_str_current = "unnest($3) AS {col_grp_key}, unnest($4) AS _state_current".format(**self.kwargs)
@@ -227,30 +407,16 @@ class GroupIterationController:
unnest_str_previous=unnest_str_previous, **self.kwargs),
["text[]", grouped_state_type] * 2)
- if self.is_state_type_bytea8:
- ret_tuples = plpy.execute(eval_plan,
- [self.old_states.keys(),
- self.old_states.values(),
- self.new_states.keys(),
- self.new_states.values()])
- else:
- if self.iteration == 1:
- flatten_agg_states_old = []
- else:
- flatten_agg_states_old = [c for state in self.old_states.values() for c in state]
- ret_tuples = plpy.execute(eval_plan,
- [self.old_states.keys(),
- flatten_agg_states_old,
- self.new_states.keys(),
- [c for state in self.new_states.values() for c in state]])
-
- self.old_states = {}
- for t in ret_tuples:
- if t['_expression']:
- k = t[self.kwargs['col_grp_key']]
- self.finished_states[k] = self.new_states[k]
- del self.new_states[k]
+ res = plpy.execute(eval_plan,
+ [self.old_states.keys,
+ self.old_states.values,
+ self.new_states.keys,
+ self.new_states.values])
+ col_grp_key = self.kwargs['col_grp_key']
+ finished_keys = [t[col_grp_key] for t in res if t['_expression']]
+ self.finished_states.update_from_state(self.new_states, finished_keys)
+ self.new_states.delete(finished_keys)
return len(self.new_states) == 0
def update(self, newState, **updateKwargs):
@@ -276,76 +442,45 @@ class GroupIterationController:
newState = newState.format(**self.kwargs)
self.iteration = self.iteration + 1
- groupby_str = "GROUP BY {grouping_col}, {col_grp_key}".format(
- **self.kwargs) if not self.is_group_null else ""
- using_str = "USING ({col_grp_key})".format(
- **self.kwargs) if not self.is_group_null else "ON TRUE"
- if self.is_state_type_bytea8:
- unnest_str = "unnest($1) AS {col_grp_key}, unnest($2) AS {col_grp_state}".format(**self.kwargs)
- grouped_state_type = "{schema_madlib}.bytea8[]".format(**self.kwargs)
- else:
- unnest_str = "grp_key AS {col_grp_key}, state AS {col_grp_state} FROM {schema_madlib}._gen_state($1, NULL, $2)".format(**self.kwargs)
- grouped_state_type = "float8[]"
-
- n_tuples_unnest_str = "unnest($3) AS {col_grp_key}, unnest($4) AS {col_n_tuples}".format(**self.kwargs)
-
- update_plan = plpy.prepare(
- """
+ group_param = self.group_param
+ update_sql = """
SELECT
{_grp_key} AS {col_grp_key},
- {grouping_col} {as_string},
+ {grouping_col},
{iteration} AS {col_grp_iteration},
({newState}) AS {col_grp_state}
FROM (
- SELECT
- *,
+ SELECT *,
array_to_string(ARRAY[{grouping_str}], ',') AS {col_grp_key}
FROM {rel_source}
- ) AS _src
- JOIN (
- SELECT {unnest_str}
- ) AS {rel_state}
+ ) AS {as_rel_source}
+ JOIN ( {select_rel_state} ) AS {rel_state}
{using_str}
- JOIN (
- SELECT
- {n_tuples_unnest_str}
- ) AS _rel_n_tuples
+ JOIN ( {select_n_tuples} ) AS _rel_n_tuples
{using_str}
{groupby_str}
""".format(
- iteration=self.iteration,
- groupby_str=groupby_str,
- using_str=using_str,
- as_string='AS _grp' if self.is_group_null else '',
- _grp_key=("array_to_string(ARRAY[{grouping_str}], "
- "',')".format(**self.kwargs) if self.is_group_null
- else self.kwargs['col_grp_key']),
newState=newState,
- unnest_str=unnest_str,
- n_tuples_unnest_str=n_tuples_unnest_str,
- **self.kwargs),
- ["text[]", grouped_state_type, "text[]", "integer[]"])
-
- if self.is_state_type_bytea8:
- res_tuples = plpy.execute(update_plan, [self.new_states.keys(),
- self.new_states.values(),
- self.grp_to_n_tuples.keys(),
- self.grp_to_n_tuples.values()])
- else:
- if self.iteration == 1:
- flatten_agg_states = []
- else:
- flatten_agg_states = [c for state in self.new_states.values() for c in state]
- res_tuples = plpy.execute(update_plan, [self.new_states.keys(),
- flatten_agg_states,
- self.grp_to_n_tuples.keys(),
- self.grp_to_n_tuples.values()])
-
- self.old_states = self.new_states
- self.new_states = {}
- for t in res_tuples:
- if t[self.kwargs['col_grp_state']] is None:
- self.failed_grp_keys.append(t[self.kwargs['col_grp_key']])
- else:
- self.new_states[t[self.kwargs['col_grp_key']]] = \
- t[self.kwargs['col_grp_state']]
+ iteration=self.iteration,
+ using_str=group_param.using_str,
+ groupby_str=group_param.groupby_str,
+ _grp_key=group_param.grp_key,
+ select_rel_state=group_param.select_rel_state,
+ select_n_tuples=group_param.select_n_tuples,
+ **self.kwargs)
+ plpy.info(update_sql)
+ update_plan = plpy.prepare(
+ update_sql,
+ ["text[]", group_param.grouped_state_type, "text[]", "integer[]"])
+ res_tuples = plpy.execute(update_plan, [self.new_states.keys,
+ self.new_states.values,
+ self.grp_to_n_tuples.keys(),
+ self.grp_to_n_tuples.values()])
+
+ col_grp_state = self.kwargs['col_grp_state']
+ col_grp_key = self.kwargs['col_grp_key']
+ self.old_states.sync_from(self.new_states)
+ self.failed_grp_keys.extend(self.new_states.update(
+ col_grp_key,
+ col_grp_state,
+ res_tuples))