R/gam.R

Defines functions .h2o.fill_gam h2o.get_gam_knot_column_names h2o.get_knot_locations .h2o.train_segments_gam h2o.gam

Documented in h2o.gam h2o.get_gam_knot_column_names h2o.get_knot_locations

# This file is auto-generated by h2o-3/h2o-bindings/bin/gen_R.py
# Copyright 2016 H2O.ai;  Apache License Version 2.0 (see LICENSE for details) 
#'
# -------------------------- Generalized Additive Model -------------------------- #
#'
#' Fit a General Additive Model
#' 
#' Creates a generalized additive model, specified by a response variable, a set of predictors, and a
#' description of the error distribution.
#' 
#'
#' @param x (Optional) A vector containing the names or indices of the predictor variables to use in building the model.
#'        If x is missing, then all columns except y are used.
#' @param y The name or column index of the response variable in the data. 
#'        The response must be either a numeric or a categorical/factor variable. 
#'        If the response is numeric, then a regression model will be trained, otherwise it will train a classification model.
#' @param training_frame Id of the training data frame.
#' @param gam_columns Arrays of predictor column names for gam for smoothers using single or multiple predictors like
#'        {{'c1'},{'c2','c3'},{'c4'},...}
#' @param model_id Destination id for this model; auto-generated if not specified.
#' @param validation_frame Id of the validation data frame.
#' @param nfolds Number of folds for K-fold cross-validation (0 to disable or >= 2). Defaults to 0.
#' @param seed Seed for random numbers (affects certain parts of the algo that are stochastic and those might or might not be enabled by default).
#'        Defaults to -1 (time-based random number).
#' @param keep_cross_validation_models \code{Logical}. Whether to keep the cross-validation models. Defaults to TRUE.
#' @param keep_cross_validation_predictions \code{Logical}. Whether to keep the predictions of the cross-validation models. Defaults to FALSE.
#' @param keep_cross_validation_fold_assignment \code{Logical}. Whether to keep the cross-validation fold assignment. Defaults to FALSE.
#' @param fold_assignment Cross-validation fold assignment scheme, if fold_column is not specified. The 'Stratified' option will
#'        stratify the folds based on the response variable, for classification problems. Must be one of: "AUTO",
#'        "Random", "Modulo", "Stratified". Defaults to AUTO.
#' @param fold_column Column with cross-validation fold index assignment per observation.
#' @param ignore_const_cols \code{Logical}. Ignore constant columns. Defaults to TRUE.
#' @param score_each_iteration \code{Logical}. Whether to score during each iteration of model training. Defaults to FALSE.
#' @param offset_column Offset column. This will be added to the combination of columns before applying the link function.
#' @param weights_column Column with observation weights. Giving some observation a weight of zero is equivalent to excluding it from
#'        the dataset; giving an observation a relative weight of 2 is equivalent to repeating that row twice. Negative
#'        weights are not allowed. Note: Weights are per-row observation weights and do not increase the size of the
#'        data frame. This is typically the number of times a row is repeated, but non-integer values are supported as
#'        well. During training, rows with higher weights matter more, due to the larger loss function pre-factor. If
#'        you set weight = 0 for a row, the returned prediction frame at that row is zero and this is incorrect. To get
#'        an accurate prediction, remove all rows with weight == 0.
#' @param family Family. Use binomial for classification with logistic regression, others are for regression problems. Must be
#'        one of: "AUTO", "gaussian", "binomial", "quasibinomial", "ordinal", "multinomial", "poisson", "gamma",
#'        "tweedie", "negativebinomial", "fractionalbinomial". Defaults to AUTO.
#' @param tweedie_variance_power Tweedie variance power Defaults to 0.
#' @param tweedie_link_power Tweedie link power Defaults to 0.
#' @param theta Theta Defaults to 0.
#' @param solver AUTO will set the solver based on given data and the other parameters. IRLSM is fast on on problems with small
#'        number of predictors and for lambda-search with L1 penalty, L_BFGS scales better for datasets with many
#'        columns. Must be one of: "AUTO", "IRLSM", "L_BFGS", "COORDINATE_DESCENT_NAIVE", "COORDINATE_DESCENT",
#'        "GRADIENT_DESCENT_LH", "GRADIENT_DESCENT_SQERR". Defaults to AUTO.
#' @param alpha Distribution of regularization between the L1 (Lasso) and L2 (Ridge) penalties. A value of 1 for alpha
#'        represents Lasso regression, a value of 0 produces Ridge regression, and anything in between specifies the
#'        amount of mixing between the two. Default value of alpha is 0 when SOLVER = 'L-BFGS'; 0.5 otherwise.
#' @param lambda Regularization strength
#' @param lambda_search \code{Logical}. Use lambda search starting at lambda max, given lambda is then interpreted as lambda min
#'        Defaults to FALSE.
#' @param early_stopping \code{Logical}. Stop early when there is no more relative improvement on train or validation (if provided)
#'        Defaults to TRUE.
#' @param nlambdas Number of lambdas to be used in a search. Default indicates: If alpha is zero, with lambda search set to True,
#'        the value of nlamdas is set to 30 (fewer lambdas are needed for ridge regression) otherwise it is set to 100.
#'        Defaults to -1.
#' @param standardize \code{Logical}. Standardize numeric columns to have zero mean and unit variance Defaults to FALSE.
#' @param missing_values_handling Handling of missing values. Either MeanImputation, Skip or PlugValues. Must be one of: "MeanImputation",
#'        "Skip", "PlugValues". Defaults to MeanImputation.
#' @param plug_values Plug Values (a single row frame containing values that will be used to impute missing values of the
#'        training/validation frame, use with conjunction missing_values_handling = PlugValues)
#' @param compute_p_values \code{Logical}. Request p-values computation, p-values work only with IRLSM solver and no regularization
#'        Defaults to FALSE.
#' @param remove_collinear_columns \code{Logical}. In case of linearly dependent columns, remove some of the dependent columns Defaults to FALSE.
#' @param splines_non_negative Valid for I-spline (bs=2) only.  True if the I-splines are monotonically increasing (and monotonically non-
#'        decreasing) and False if the I-splines are monotonically decreasing (and monotonically non-increasing).  If
#'        specified, must be the same size as gam_columns.  Values for other spline types will be ignored.  Default to
#'        true.
#' @param intercept \code{Logical}. Include constant term in the model Defaults to TRUE.
#' @param non_negative \code{Logical}. Restrict coefficients (not intercept) to be non-negative Defaults to FALSE.
#' @param max_iterations Maximum number of iterations Defaults to -1.
#' @param objective_epsilon Converge if  objective value changes less than this. Default indicates: If lambda_search is set to True the
#'        value of objective_epsilon is set to .0001. If the lambda_search is set to False and lambda is equal to zero,
#'        the value of objective_epsilon is set to .000001, for any other value of lambda the default value of
#'        objective_epsilon is set to .0001. Defaults to -1.
#' @param beta_epsilon Converge if  beta changes less (using L-infinity norm) than beta esilon, ONLY applies to IRLSM solver
#'        Defaults to 0.0001.
#' @param gradient_epsilon Converge if  objective changes less (using L-infinity norm) than this, ONLY applies to L-BFGS solver. Default
#'        indicates: If lambda_search is set to False and lambda is equal to zero, the default value of gradient_epsilon
#'        is equal to .000001, otherwise the default value is .0001. If lambda_search is set to True, the conditional
#'        values above are 1E-8 and 1E-6 respectively. Defaults to -1.
#' @param link Link function. Must be one of: "family_default", "identity", "logit", "log", "inverse", "tweedie", "ologit".
#'        Defaults to family_default.
#' @param startval double array to initialize coefficients for GAM.
#' @param prior Prior probability for y==1. To be used only for logistic regression iff the data has been sampled and the mean
#'        of response does not reflect reality. Defaults to -1.
#' @param cold_start \code{Logical}. Only applicable to multiple alpha/lambda values when calling GLM from GAM.  If false, build
#'        the next model for next set of alpha/lambda values starting from the values provided by current model.  If
#'        true will start GLM model from scratch. Defaults to FALSE.
#' @param lambda_min_ratio Minimum lambda used in lambda search, specified as a ratio of lambda_max (the smallest lambda that drives all
#'        coefficients to zero). Default indicates: if the number of observations is greater than the number of
#'        variables, then lambda_min_ratio is set to 0.0001; if the number of observations is less than the number of
#'        variables, then lambda_min_ratio is set to 0.01. Defaults to -1.
#' @param beta_constraints Beta constraints
#' @param max_active_predictors Maximum number of active predictors during computation. Use as a stopping criterion to prevent expensive model
#'        building with many predictors. Default indicates: If the IRLSM solver is used, the value of
#'        max_active_predictors is set to 5000 otherwise it is set to 100000000. Defaults to -1.
#' @param interactions A list of predictor column indices to interact. All pairwise combinations will be computed for the list.
#' @param interaction_pairs A list of pairwise (first order) column interactions.
#' @param obj_reg Likelihood divider in objective value computation, default is 1/nobs Defaults to -1.
#' @param export_checkpoints_dir Automatically export generated models to this directory.
#' @param stopping_rounds Early stopping based on convergence of stopping_metric. Stop if simple moving average of length k of the
#'        stopping_metric does not improve for k:=stopping_rounds scoring events (0 to disable) Defaults to 0.
#' @param stopping_metric Metric to use for early stopping (AUTO: logloss for classification, deviance for regression and anomaly_score
#'        for Isolation Forest). Note that custom and custom_increasing can only be used in GBM and DRF with the Python
#'        client. Must be one of: "AUTO", "deviance", "logloss", "MSE", "RMSE", "MAE", "RMSLE", "AUC", "AUCPR",
#'        "lift_top_group", "misclassification", "mean_per_class_error", "custom", "custom_increasing". Defaults to
#'        AUTO.
#' @param stopping_tolerance Relative tolerance for metric-based stopping criterion (stop if relative improvement is not at least this
#'        much) Defaults to 0.001.
#' @param balance_classes \code{Logical}. Balance training data class counts via over/under-sampling (for imbalanced data). Defaults to
#'        FALSE.
#' @param class_sampling_factors Desired over/under-sampling ratios per class (in lexicographic order). If not specified, sampling factors will
#'        be automatically computed to obtain class balance during training. Requires balance_classes.
#' @param max_after_balance_size Maximum relative size of the training data after balancing class counts (can be less than 1.0). Requires
#'        balance_classes. Defaults to 5.0.
#' @param max_runtime_secs Maximum allowed runtime in seconds for model training. Use 0 to disable. Defaults to 0.
#' @param custom_metric_func Reference to custom evaluation function, format: `language:keyName=funcName`
#' @param num_knots Number of knots for gam predictors.  If specified, must specify one for each gam predictor.  For monotone
#'        I-splines, mininum = 2, for cs spline, minimum = 3.  For thin plate, minimum is size of polynomial basis + 2.
#' @param spline_orders Order of I-splines or NBSplineTypeI M-splines used for gam predictors. If specified, must be the same size as
#'        gam_columns.  For I-splines, the spline_orders will be the same as the polynomials used to generate the
#'        splines.  For M-splines, the polynomials used to generate the splines will be spline_order-1.  Values for bs=0
#'        or 1 will be ignored.
#' @param knot_ids Array storing frame keys of knots.  One for each gam column set specified in gam_columns
#' @param standardize_tp_gam_cols \code{Logical}. standardize tp (thin plate) predictor columns Defaults to FALSE.
#' @param scale_tp_penalty_mat \code{Logical}. Scale penalty matrix for tp (thin plate) smoothers as in R Defaults to FALSE.
#' @param bs Basis function type for each gam predictors, 0 for cr, 1 for thin plate regression with knots, 2 for monotone
#'        I-splines, 3 for NBSplineTypeI M-splines (refer to doc here: https://github.com/h2oai/h2o-3/issues/6926).  If
#'        specified, must be the same size as gam_columns
#' @param scale Smoothing parameter for gam predictors.  If specified, must be of the same length as gam_columns
#' @param keep_gam_cols \code{Logical}. Save keys of model matrix Defaults to FALSE.
#' @param store_knot_locations \code{Logical}. If set to true, will return knot locations as double[][] array for gam column names found
#'        knots_for_gam.  Default to false. Defaults to FALSE.
#' @param auc_type Set default multinomial AUC type. Must be one of: "AUTO", "NONE", "MACRO_OVR", "WEIGHTED_OVR", "MACRO_OVO",
#'        "WEIGHTED_OVO". Defaults to AUTO.
#' @examples
#' \dontrun{
#' h2o.init()
#' 
#' # Run GAM of CAPSULE ~ AGE + RACE + PSA + DCAPS
#' prostate_path <- system.file("extdata", "prostate.csv", package = "h2o")
#' prostate <- h2o.uploadFile(path = prostate_path)
#' prostate$CAPSULE <- as.factor(prostate$CAPSULE)
#' h2o.gam(y = "CAPSULE", x = c("RACE"), gam_columns = c("PSA"),
#'      training_frame = prostate, family = "binomial")
#' 
#' }
#' @export
h2o.gam <- function(x,
                    y,
                    training_frame,
                    gam_columns,
                    model_id = NULL,
                    validation_frame = NULL,
                    nfolds = 0,
                    seed = -1,
                    keep_cross_validation_models = TRUE,
                    keep_cross_validation_predictions = FALSE,
                    keep_cross_validation_fold_assignment = FALSE,
                    fold_assignment = c("AUTO", "Random", "Modulo", "Stratified"),
                    fold_column = NULL,
                    ignore_const_cols = TRUE,
                    score_each_iteration = FALSE,
                    offset_column = NULL,
                    weights_column = NULL,
                    family = c("AUTO", "gaussian", "binomial", "quasibinomial", "ordinal", "multinomial", "poisson", "gamma", "tweedie", "negativebinomial", "fractionalbinomial"),
                    tweedie_variance_power = 0,
                    tweedie_link_power = 0,
                    theta = 0,
                    solver = c("AUTO", "IRLSM", "L_BFGS", "COORDINATE_DESCENT_NAIVE", "COORDINATE_DESCENT", "GRADIENT_DESCENT_LH", "GRADIENT_DESCENT_SQERR"),
                    alpha = NULL,
                    lambda = NULL,
                    lambda_search = FALSE,
                    early_stopping = TRUE,
                    nlambdas = -1,
                    standardize = FALSE,
                    missing_values_handling = c("MeanImputation", "Skip", "PlugValues"),
                    plug_values = NULL,
                    compute_p_values = FALSE,
                    remove_collinear_columns = FALSE,
                    splines_non_negative = NULL,
                    intercept = TRUE,
                    non_negative = FALSE,
                    max_iterations = -1,
                    objective_epsilon = -1,
                    beta_epsilon = 0.0001,
                    gradient_epsilon = -1,
                    link = c("family_default", "identity", "logit", "log", "inverse", "tweedie", "ologit"),
                    startval = NULL,
                    prior = -1,
                    cold_start = FALSE,
                    lambda_min_ratio = -1,
                    beta_constraints = NULL,
                    max_active_predictors = -1,
                    interactions = NULL,
                    interaction_pairs = NULL,
                    obj_reg = -1,
                    export_checkpoints_dir = NULL,
                    stopping_rounds = 0,
                    stopping_metric = c("AUTO", "deviance", "logloss", "MSE", "RMSE", "MAE", "RMSLE", "AUC", "AUCPR", "lift_top_group", "misclassification", "mean_per_class_error", "custom", "custom_increasing"),
                    stopping_tolerance = 0.001,
                    balance_classes = FALSE,
                    class_sampling_factors = NULL,
                    max_after_balance_size = 5.0,
                    max_runtime_secs = 0,
                    custom_metric_func = NULL,
                    num_knots = NULL,
                    spline_orders = NULL,
                    knot_ids = NULL,
                    standardize_tp_gam_cols = FALSE,
                    scale_tp_penalty_mat = FALSE,
                    bs = NULL,
                    scale = NULL,
                    keep_gam_cols = FALSE,
                    store_knot_locations = FALSE,
                    auc_type = c("AUTO", "NONE", "MACRO_OVR", "WEIGHTED_OVR", "MACRO_OVO", "WEIGHTED_OVO"))
{
  # Validate required training_frame first and other frame args: should be a valid key or an H2OFrame object
  training_frame <- .validate.H2OFrame(training_frame, required=TRUE)
  validation_frame <- .validate.H2OFrame(validation_frame, required=FALSE)

  # Validate other required args
  # If x is missing, no predictors will be used.  Only the gam columns are present as predictors
  if (missing(x)) {
      x = NULL
  }
  # If gam_columns is missing, then assume user wants to use all columns as features for GAM.
  if (missing(gam_columns)) {
      stop("Columns indices to apply to GAM must be specified. If there are none, please use GLM.")
  }
  gam_columns <- lapply(gam_columns, function(x) if(is.character(x) & length(x) == 1) list(x) else x)

  # Validate other args
  # if (!is.null(beta_constraints)) {
  #     if (!inherits(beta_constraints, 'data.frame') && !is.H2OFrame(beta_constraints))
  #       stop(paste('`beta_constraints` must be an H2OH2OFrame or R data.frame. Got: ', class(beta_constraints)))
  #     if (inherits(beta_constraints, 'data.frame')) {
  #       beta_constraints <- as.h2o(beta_constraints)
  #     }
  # }
  if (inherits(beta_constraints, 'data.frame')) {
    beta_constraints <- as.h2o(beta_constraints)
  }

  # Build parameter list to send to model builder
  parms <- list()
  parms$training_frame <- training_frame
  args <- .verify_dataxy(training_frame, x, y)
  if( !missing(offset_column) && !is.null(offset_column))  args$x_ignore <- args$x_ignore[!( offset_column == args$x_ignore )]
  if( !missing(weights_column) && !is.null(weights_column)) args$x_ignore <- args$x_ignore[!( weights_column == args$x_ignore )]
  if( !missing(fold_column) && !is.null(fold_column)) args$x_ignore <- args$x_ignore[!( fold_column == args$x_ignore )]
  parms$ignored_columns <- args$x_ignore
  parms$response_column <- args$y
  parms$gam_columns <- gam_columns

  if (!missing(model_id))
    parms$model_id <- model_id
  if (!missing(validation_frame))
    parms$validation_frame <- validation_frame
  if (!missing(seed))
    parms$seed <- seed
  if (!missing(keep_cross_validation_models))
    parms$keep_cross_validation_models <- keep_cross_validation_models
  if (!missing(keep_cross_validation_predictions))
    parms$keep_cross_validation_predictions <- keep_cross_validation_predictions
  if (!missing(keep_cross_validation_fold_assignment))
    parms$keep_cross_validation_fold_assignment <- keep_cross_validation_fold_assignment
  if (!missing(fold_assignment))
    parms$fold_assignment <- fold_assignment
  if (!missing(fold_column))
    parms$fold_column <- fold_column
  if (!missing(ignore_const_cols))
    parms$ignore_const_cols <- ignore_const_cols
  if (!missing(score_each_iteration))
    parms$score_each_iteration <- score_each_iteration
  if (!missing(offset_column))
    parms$offset_column <- offset_column
  if (!missing(weights_column))
    parms$weights_column <- weights_column
  if (!missing(family))
    parms$family <- family
  if (!missing(tweedie_variance_power))
    parms$tweedie_variance_power <- tweedie_variance_power
  if (!missing(tweedie_link_power))
    parms$tweedie_link_power <- tweedie_link_power
  if (!missing(theta))
    parms$theta <- theta
  if (!missing(solver))
    parms$solver <- solver
  if (!missing(alpha))
    parms$alpha <- alpha
  if (!missing(lambda))
    parms$lambda <- lambda
  if (!missing(lambda_search))
    parms$lambda_search <- lambda_search
  if (!missing(early_stopping))
    parms$early_stopping <- early_stopping
  if (!missing(nlambdas))
    parms$nlambdas <- nlambdas
  if (!missing(standardize))
    parms$standardize <- standardize
  if (!missing(plug_values))
    parms$plug_values <- plug_values
  if (!missing(compute_p_values))
    parms$compute_p_values <- compute_p_values
  if (!missing(remove_collinear_columns))
    parms$remove_collinear_columns <- remove_collinear_columns
  if (!missing(splines_non_negative))
    parms$splines_non_negative <- splines_non_negative
  if (!missing(intercept))
    parms$intercept <- intercept
  if (!missing(non_negative))
    parms$non_negative <- non_negative
  if (!missing(max_iterations))
    parms$max_iterations <- max_iterations
  if (!missing(objective_epsilon))
    parms$objective_epsilon <- objective_epsilon
  if (!missing(beta_epsilon))
    parms$beta_epsilon <- beta_epsilon
  if (!missing(gradient_epsilon))
    parms$gradient_epsilon <- gradient_epsilon
  if (!missing(link))
    parms$link <- link
  if (!missing(startval))
    parms$startval <- startval
  if (!missing(prior))
    parms$prior <- prior
  if (!missing(cold_start))
    parms$cold_start <- cold_start
  if (!missing(lambda_min_ratio))
    parms$lambda_min_ratio <- lambda_min_ratio
  if (!missing(max_active_predictors))
    parms$max_active_predictors <- max_active_predictors
  if (!missing(interaction_pairs))
    parms$interaction_pairs <- interaction_pairs
  if (!missing(obj_reg))
    parms$obj_reg <- obj_reg
  if (!missing(export_checkpoints_dir))
    parms$export_checkpoints_dir <- export_checkpoints_dir
  if (!missing(stopping_rounds))
    parms$stopping_rounds <- stopping_rounds
  if (!missing(stopping_metric))
    parms$stopping_metric <- stopping_metric
  if (!missing(stopping_tolerance))
    parms$stopping_tolerance <- stopping_tolerance
  if (!missing(balance_classes))
    parms$balance_classes <- balance_classes
  if (!missing(class_sampling_factors))
    parms$class_sampling_factors <- class_sampling_factors
  if (!missing(max_after_balance_size))
    parms$max_after_balance_size <- max_after_balance_size
  if (!missing(max_runtime_secs))
    parms$max_runtime_secs <- max_runtime_secs
  if (!missing(custom_metric_func))
    parms$custom_metric_func <- custom_metric_func
  if (!missing(num_knots))
    parms$num_knots <- num_knots
  if (!missing(spline_orders))
    parms$spline_orders <- spline_orders
  if (!missing(knot_ids))
    parms$knot_ids <- knot_ids
  if (!missing(gam_columns))
    parms$gam_columns <- gam_columns
  if (!missing(standardize_tp_gam_cols))
    parms$standardize_tp_gam_cols <- standardize_tp_gam_cols
  if (!missing(scale_tp_penalty_mat))
    parms$scale_tp_penalty_mat <- scale_tp_penalty_mat
  if (!missing(bs))
    parms$bs <- bs
  if (!missing(scale))
    parms$scale <- scale
  if (!missing(keep_gam_cols))
    parms$keep_gam_cols <- keep_gam_cols
  if (!missing(store_knot_locations))
    parms$store_knot_locations <- store_knot_locations
  if (!missing(auc_type))
    parms$auc_type <- auc_type

  if( !missing(interactions) ) {
    # interactions are column names => as-is
    if( is.character(interactions) )       parms$interactions <- interactions
    else if( is.numeric(interactions) )    parms$interactions <- names(training_frame)[interactions]
    else stop("Don't know what to do with interactions. Supply vector of indices or names")
  }
  # For now, accept nfolds in the R interface if it is 0 or 1, since those values really mean do nothing.
  # For any other value, error out.
  # Expunge nfolds from the message sent to H2O, since H2O doesn't understand it.
  if (!missing(nfolds) && nfolds > 1)
    parms$nfolds <- nfolds
  if(!missing(beta_constraints))
    parms$beta_constraints <- beta_constraints
    if(!missing(missing_values_handling))
      parms$missing_values_handling <- missing_values_handling

  # Error check and build model
  model <- .h2o.modelJob('gam', parms, h2oRestApiVersion=3, verbose=FALSE)

  model@model$coefficients <- model@model$coefficients_table[,2]
  names(model@model$coefficients) <- model@model$coefficients_table[,1]
  if (!(is.null(model@model$random_coefficients_table))) {
      model@model$random_coefficients <- model@model$random_coefficients_table[,2]
      names(model@model$random_coefficients) <- model@model$random_coefficients_table[,1]
  }
  return(model)
}
.h2o.train_segments_gam <- function(x,
                                    y,
                                    training_frame,
                                    gam_columns,
                                    validation_frame = NULL,
                                    nfolds = 0,
                                    seed = -1,
                                    keep_cross_validation_models = TRUE,
                                    keep_cross_validation_predictions = FALSE,
                                    keep_cross_validation_fold_assignment = FALSE,
                                    fold_assignment = c("AUTO", "Random", "Modulo", "Stratified"),
                                    fold_column = NULL,
                                    ignore_const_cols = TRUE,
                                    score_each_iteration = FALSE,
                                    offset_column = NULL,
                                    weights_column = NULL,
                                    family = c("AUTO", "gaussian", "binomial", "quasibinomial", "ordinal", "multinomial", "poisson", "gamma", "tweedie", "negativebinomial", "fractionalbinomial"),
                                    tweedie_variance_power = 0,
                                    tweedie_link_power = 0,
                                    theta = 0,
                                    solver = c("AUTO", "IRLSM", "L_BFGS", "COORDINATE_DESCENT_NAIVE", "COORDINATE_DESCENT", "GRADIENT_DESCENT_LH", "GRADIENT_DESCENT_SQERR"),
                                    alpha = NULL,
                                    lambda = NULL,
                                    lambda_search = FALSE,
                                    early_stopping = TRUE,
                                    nlambdas = -1,
                                    standardize = FALSE,
                                    missing_values_handling = c("MeanImputation", "Skip", "PlugValues"),
                                    plug_values = NULL,
                                    compute_p_values = FALSE,
                                    remove_collinear_columns = FALSE,
                                    splines_non_negative = NULL,
                                    intercept = TRUE,
                                    non_negative = FALSE,
                                    max_iterations = -1,
                                    objective_epsilon = -1,
                                    beta_epsilon = 0.0001,
                                    gradient_epsilon = -1,
                                    link = c("family_default", "identity", "logit", "log", "inverse", "tweedie", "ologit"),
                                    startval = NULL,
                                    prior = -1,
                                    cold_start = FALSE,
                                    lambda_min_ratio = -1,
                                    beta_constraints = NULL,
                                    max_active_predictors = -1,
                                    interactions = NULL,
                                    interaction_pairs = NULL,
                                    obj_reg = -1,
                                    export_checkpoints_dir = NULL,
                                    stopping_rounds = 0,
                                    stopping_metric = c("AUTO", "deviance", "logloss", "MSE", "RMSE", "MAE", "RMSLE", "AUC", "AUCPR", "lift_top_group", "misclassification", "mean_per_class_error", "custom", "custom_increasing"),
                                    stopping_tolerance = 0.001,
                                    balance_classes = FALSE,
                                    class_sampling_factors = NULL,
                                    max_after_balance_size = 5.0,
                                    max_runtime_secs = 0,
                                    custom_metric_func = NULL,
                                    num_knots = NULL,
                                    spline_orders = NULL,
                                    knot_ids = NULL,
                                    standardize_tp_gam_cols = FALSE,
                                    scale_tp_penalty_mat = FALSE,
                                    bs = NULL,
                                    scale = NULL,
                                    keep_gam_cols = FALSE,
                                    store_knot_locations = FALSE,
                                    auc_type = c("AUTO", "NONE", "MACRO_OVR", "WEIGHTED_OVR", "MACRO_OVO", "WEIGHTED_OVO"),
                                    segment_columns = NULL,
                                    segment_models_id = NULL,
                                    parallelism = 1)
{
  # formally define variables that were excluded from function parameters
  model_id <- NULL
  verbose <- NULL
  destination_key <- NULL
  # Validate required training_frame first and other frame args: should be a valid key or an H2OFrame object
  training_frame <- .validate.H2OFrame(training_frame, required=TRUE)
  validation_frame <- .validate.H2OFrame(validation_frame, required=FALSE)

  # Validate other required args
  # If x is missing, no predictors will be used.  Only the gam columns are present as predictors
  if (missing(x)) {
      x = NULL
  }
  # If gam_columns is missing, then assume user wants to use all columns as features for GAM.
  if (missing(gam_columns)) {
      stop("Columns indices to apply to GAM must be specified. If there are none, please use GLM.")
  }
  gam_columns <- lapply(gam_columns, function(x) if(is.character(x) & length(x) == 1) list(x) else x)

  # Validate other args
  # if (!is.null(beta_constraints)) {
  #     if (!inherits(beta_constraints, 'data.frame') && !is.H2OFrame(beta_constraints))
  #       stop(paste('`beta_constraints` must be an H2OH2OFrame or R data.frame. Got: ', class(beta_constraints)))
  #     if (inherits(beta_constraints, 'data.frame')) {
  #       beta_constraints <- as.h2o(beta_constraints)
  #     }
  # }
  if (inherits(beta_constraints, 'data.frame')) {
    beta_constraints <- as.h2o(beta_constraints)
  }

  # Build parameter list to send to model builder
  parms <- list()
  parms$training_frame <- training_frame
  args <- .verify_dataxy(training_frame, x, y)
  if( !missing(offset_column) && !is.null(offset_column))  args$x_ignore <- args$x_ignore[!( offset_column == args$x_ignore )]
  if( !missing(weights_column) && !is.null(weights_column)) args$x_ignore <- args$x_ignore[!( weights_column == args$x_ignore )]
  if( !missing(fold_column) && !is.null(fold_column)) args$x_ignore <- args$x_ignore[!( fold_column == args$x_ignore )]
  parms$ignored_columns <- args$x_ignore
  parms$response_column <- args$y
  parms$gam_columns <- gam_columns

  if (!missing(validation_frame))
    parms$validation_frame <- validation_frame
  if (!missing(seed))
    parms$seed <- seed
  if (!missing(keep_cross_validation_models))
    parms$keep_cross_validation_models <- keep_cross_validation_models
  if (!missing(keep_cross_validation_predictions))
    parms$keep_cross_validation_predictions <- keep_cross_validation_predictions
  if (!missing(keep_cross_validation_fold_assignment))
    parms$keep_cross_validation_fold_assignment <- keep_cross_validation_fold_assignment
  if (!missing(fold_assignment))
    parms$fold_assignment <- fold_assignment
  if (!missing(fold_column))
    parms$fold_column <- fold_column
  if (!missing(ignore_const_cols))
    parms$ignore_const_cols <- ignore_const_cols
  if (!missing(score_each_iteration))
    parms$score_each_iteration <- score_each_iteration
  if (!missing(offset_column))
    parms$offset_column <- offset_column
  if (!missing(weights_column))
    parms$weights_column <- weights_column
  if (!missing(family))
    parms$family <- family
  if (!missing(tweedie_variance_power))
    parms$tweedie_variance_power <- tweedie_variance_power
  if (!missing(tweedie_link_power))
    parms$tweedie_link_power <- tweedie_link_power
  if (!missing(theta))
    parms$theta <- theta
  if (!missing(solver))
    parms$solver <- solver
  if (!missing(alpha))
    parms$alpha <- alpha
  if (!missing(lambda))
    parms$lambda <- lambda
  if (!missing(lambda_search))
    parms$lambda_search <- lambda_search
  if (!missing(early_stopping))
    parms$early_stopping <- early_stopping
  if (!missing(nlambdas))
    parms$nlambdas <- nlambdas
  if (!missing(standardize))
    parms$standardize <- standardize
  if (!missing(plug_values))
    parms$plug_values <- plug_values
  if (!missing(compute_p_values))
    parms$compute_p_values <- compute_p_values
  if (!missing(remove_collinear_columns))
    parms$remove_collinear_columns <- remove_collinear_columns
  if (!missing(splines_non_negative))
    parms$splines_non_negative <- splines_non_negative
  if (!missing(intercept))
    parms$intercept <- intercept
  if (!missing(non_negative))
    parms$non_negative <- non_negative
  if (!missing(max_iterations))
    parms$max_iterations <- max_iterations
  if (!missing(objective_epsilon))
    parms$objective_epsilon <- objective_epsilon
  if (!missing(beta_epsilon))
    parms$beta_epsilon <- beta_epsilon
  if (!missing(gradient_epsilon))
    parms$gradient_epsilon <- gradient_epsilon
  if (!missing(link))
    parms$link <- link
  if (!missing(startval))
    parms$startval <- startval
  if (!missing(prior))
    parms$prior <- prior
  if (!missing(cold_start))
    parms$cold_start <- cold_start
  if (!missing(lambda_min_ratio))
    parms$lambda_min_ratio <- lambda_min_ratio
  if (!missing(max_active_predictors))
    parms$max_active_predictors <- max_active_predictors
  if (!missing(interaction_pairs))
    parms$interaction_pairs <- interaction_pairs
  if (!missing(obj_reg))
    parms$obj_reg <- obj_reg
  if (!missing(export_checkpoints_dir))
    parms$export_checkpoints_dir <- export_checkpoints_dir
  if (!missing(stopping_rounds))
    parms$stopping_rounds <- stopping_rounds
  if (!missing(stopping_metric))
    parms$stopping_metric <- stopping_metric
  if (!missing(stopping_tolerance))
    parms$stopping_tolerance <- stopping_tolerance
  if (!missing(balance_classes))
    parms$balance_classes <- balance_classes
  if (!missing(class_sampling_factors))
    parms$class_sampling_factors <- class_sampling_factors
  if (!missing(max_after_balance_size))
    parms$max_after_balance_size <- max_after_balance_size
  if (!missing(max_runtime_secs))
    parms$max_runtime_secs <- max_runtime_secs
  if (!missing(custom_metric_func))
    parms$custom_metric_func <- custom_metric_func
  if (!missing(num_knots))
    parms$num_knots <- num_knots
  if (!missing(spline_orders))
    parms$spline_orders <- spline_orders
  if (!missing(knot_ids))
    parms$knot_ids <- knot_ids
  if (!missing(gam_columns))
    parms$gam_columns <- gam_columns
  if (!missing(standardize_tp_gam_cols))
    parms$standardize_tp_gam_cols <- standardize_tp_gam_cols
  if (!missing(scale_tp_penalty_mat))
    parms$scale_tp_penalty_mat <- scale_tp_penalty_mat
  if (!missing(bs))
    parms$bs <- bs
  if (!missing(scale))
    parms$scale <- scale
  if (!missing(keep_gam_cols))
    parms$keep_gam_cols <- keep_gam_cols
  if (!missing(store_knot_locations))
    parms$store_knot_locations <- store_knot_locations
  if (!missing(auc_type))
    parms$auc_type <- auc_type

  if( !missing(interactions) ) {
    # interactions are column names => as-is
    if( is.character(interactions) )       parms$interactions <- interactions
    else if( is.numeric(interactions) )    parms$interactions <- names(training_frame)[interactions]
    else stop("Don't know what to do with interactions. Supply vector of indices or names")
  }
  # For now, accept nfolds in the R interface if it is 0 or 1, since those values really mean do nothing.
  # For any other value, error out.
  # Expunge nfolds from the message sent to H2O, since H2O doesn't understand it.
  if (!missing(nfolds) && nfolds > 1)
    parms$nfolds <- nfolds
  if(!missing(beta_constraints))
    parms$beta_constraints <- beta_constraints
    if(!missing(missing_values_handling))
      parms$missing_values_handling <- missing_values_handling

  # Build segment-models specific parameters
  segment_parms <- list()
  if (!missing(segment_columns))
    segment_parms$segment_columns <- segment_columns
  if (!missing(segment_models_id))
    segment_parms$segment_models_id <- segment_models_id
  segment_parms$parallelism <- parallelism

  # Error check and build segment models
  segment_models <- .h2o.segmentModelsJob('gam', segment_parms, parms, h2oRestApiVersion=3)
  return(segment_models)
}


#' Extracts the knot locations from model output if it is enabled.
#'
#' @param model is a H2OModel with algorithm name of gam
#' @param gam_column will only extract the knot locations for the specific gam_columns.  Else, return all.
#' @export 
h2o.get_knot_locations <- function(model, gam_column=NULL) {
    if (!model@allparameters$store_knot_locations) {
        stop("knot locations are not available, please set store_knot_locations to TRUE")
    }
    if (is.null(gam_column)) {
        return(model@model$knot_locations)
    }
    gam_columns <- model@model$gam_knot_column_names
    if (gam_column %in% gam_columns) {
        return(model@model$knot_locations[which(gam_columns==gam_column)])
    } else {
        stop(paste(gam_column, "is not a valid gam column", sep=" "))
    }
}

#' Extracts the gam column names corresponding to the knot locations from model output if it is enabled.
#'
#' @param model is a H2OModel with algorithm name of gam
#' @export 
h2o.get_gam_knot_column_names <- function(model) {
    if (!model@allparameters$store_knot_locations) {
        stop("knot locations are not available, please set store_knot_locations to TRUE")
    }
    return(model@model$gam_knot_column_names)

}
    
    .h2o.fill_gam <- function(model, parameters, allparams) {
        if (is.null(model$scoring_history))
            model$scoring_history <- model$glm_scoring_history
        if (is.null(model$model_summary))
            model$model_summary <- model$glm_model_summary
        return(model)
    }

Try the h2o package in your browser

Any scripts or data that you put into this service are public.

h2o documentation built on Aug. 9, 2023, 9:06 a.m.