Unverified Commit 3fd48864 authored by Guangyu Zeng's avatar Guangyu Zeng Committed by GitHub
Browse files

[R-package] Add explicit return statement to R functions. (#3703)

* add explicit return statement to functions in callback.R

* add explicit return statement to functions in lgb.Booster.R

* add explicit return statement to functions in lgb.Dataset.R

* add explicit return statement to functions in lgb.Predictor.R

* add explicit return statement to functions in lgb.cv.R

* add explicit return statement to functions in lgb.interprete.R

* add explicit return statement to functions in lgb.plot.importance.R

* add explicit return statement to functions in saveRDS.lgb.Booster.R

* add explicit return statement to functions in utils.R

* add explicit return statement to functions in lgb.plot.interpretation.R

* add explicit return statement to functions in build_r.R

* fix typo

* return(self) -> return(invisible(self))

* fix some inconsistent indention

* fix test failure

* add another return() statement

* fix linting errors
parent 3fde0ce9
......@@ -7,74 +7,76 @@
# [return] A named list, where each key is a parameter relevant to lgb.DataSet and each value is a character
# vector of corresponding aliases.
.DATASET_PARAMETERS <- function() {
return(list(
"bin_construct_sample_cnt" = c(
"bin_construct_sample_cnt"
, "subsample_for_bin"
return(
list(
"bin_construct_sample_cnt" = c(
"bin_construct_sample_cnt"
, "subsample_for_bin"
)
, "categorical_feature" = c(
"categorical_feature"
, "cat_feature"
, "categorical_column"
, "cat_column"
)
, "data_random_seed" = c(
"data_random_seed"
, "data_seed"
)
, "enable_bundle" = c(
"enable_bundle"
, "is_enable_bundle"
, "bundle"
)
, "feature_pre_filter" = "feature_pre_filter"
, "forcedbins_filename" = "forcedbins_filename"
, "group_column" = c(
"group_column"
, "group"
, "group_id"
, "query_column"
, "query"
, "query_id"
)
, "header" = c(
"header"
, "has_header"
)
, "ignore_column" = c(
"ignore_column"
, "ignore_feature"
, "blacklist"
)
, "is_enable_sparse" = c(
"is_enable_sparse"
, "is_sparse"
, "enable_sparse"
, "sparse"
)
, "label_column" = c(
"label_column"
, "label"
)
, "max_bin" = "max_bin"
, "max_bin_by_feature" = "max_bin_by_feature"
, "min_data_in_bin" = "min_data_in_bin"
, "pre_partition" = c(
"pre_partition"
, "is_pre_partition"
)
, "two_round" = c(
"two_round"
, "two_round_loading"
, "use_two_round_loading"
)
, "use_missing" = "use_missing"
, "weight_column" = c(
"weight_column"
, "weight"
)
, "zero_as_missing" = "zero_as_missing"
)
, "categorical_feature" = c(
"categorical_feature"
, "cat_feature"
, "categorical_column"
, "cat_column"
)
, "data_random_seed" = c(
"data_random_seed"
, "data_seed"
)
, "enable_bundle" = c(
"enable_bundle"
, "is_enable_bundle"
, "bundle"
)
, "feature_pre_filter" = "feature_pre_filter"
, "forcedbins_filename" = "forcedbins_filename"
, "group_column" = c(
"group_column"
, "group"
, "group_id"
, "query_column"
, "query"
, "query_id"
)
, "header" = c(
"header"
, "has_header"
)
, "ignore_column" = c(
"ignore_column"
, "ignore_feature"
, "blacklist"
)
, "is_enable_sparse" = c(
"is_enable_sparse"
, "is_sparse"
, "enable_sparse"
, "sparse"
)
, "label_column" = c(
"label_column"
, "label"
)
, "max_bin" = "max_bin"
, "max_bin_by_feature" = "max_bin_by_feature"
, "min_data_in_bin" = "min_data_in_bin"
, "pre_partition" = c(
"pre_partition"
, "is_pre_partition"
)
, "two_round" = c(
"two_round"
, "two_round_loading"
, "use_two_round_loading"
)
, "use_missing" = "use_missing"
, "weight_column" = c(
"weight_column"
, "weight"
)
, "zero_as_missing" = "zero_as_missing"
))
)
}
# [description] List of respected parameter aliases. Wrapped in a function to take advantage of
......@@ -115,10 +117,12 @@
# [returns]
# A character vector
.NO_METRIC_STRINGS <- function() {
return(c(
"na"
, "None"
, "null"
, "custom"
))
return(
c(
"na"
, "None"
, "null"
, "custom"
)
)
}
......@@ -74,6 +74,8 @@ cb.reset.parameters <- function(new_params) {
}
return(invisible(NULL))
}
callback <- function(env) {
......@@ -95,15 +97,17 @@ cb.reset.parameters <- function(new_params) {
})
if (!is.null(env$model)) {
env$model$reset_parameter(params = pars)
return(env$model$reset_parameter(params = pars))
}
return(invisible(NULL))
}
attr(callback, "call") <- match.call()
attr(callback, "is_pre_iteration") <- TRUE
attr(callback, "name") <- "cb.reset.parameters"
callback
return(callback)
}
# Format the evaluation metric string
......@@ -116,9 +120,9 @@ format.eval.string <- function(eval_res, eval_err = NULL) {
# Check for empty evaluation error
if (!is.null(eval_err)) {
sprintf("%s\'s %s:%g+%g", eval_res$data_name, eval_res$name, eval_res$value, eval_err)
return(sprintf("%s\'s %s:%g+%g", eval_res$data_name, eval_res$name, eval_res$value, eval_err))
} else {
sprintf("%s\'s %s:%g", eval_res$data_name, eval_res$name, eval_res$value)
return(sprintf("%s\'s %s:%g", eval_res$data_name, eval_res$name, eval_res$value))
}
}
......@@ -150,7 +154,7 @@ merge.eval.string <- function(env) {
}
paste0(msg, collapse = " ")
return(paste0(msg, collapse = " "))
}
......@@ -180,13 +184,15 @@ cb.print.evaluation <- function(period = 1L) {
}
return(invisible(NULL))
}
# Store attributes
attr(callback, "call") <- match.call()
attr(callback, "name") <- "cb.print.evaluation"
callback
return(callback)
}
......@@ -253,13 +259,15 @@ cb.record.evaluation <- function() {
}
return(invisible(NULL))
}
# Store attributes
attr(callback, "call") <- match.call()
attr(callback, "name") <- "cb.record.evaluation"
callback
return(callback)
}
......@@ -311,6 +319,8 @@ cb.early.stop <- function(stopping_rounds, first_metric_only = FALSE, verbose =
}
return(invisible(NULL))
}
# Create callback
......@@ -392,18 +402,21 @@ cb.early.stop <- function(stopping_rounds, first_metric_only = FALSE, verbose =
env$met_early_stop <- TRUE
}
}
return(invisible(NULL))
}
attr(callback, "call") <- match.call()
attr(callback, "name") <- "cb.early.stop"
callback
return(callback)
}
# Extract callback names from the list of callbacks
callback.names <- function(cb_list) {
unlist(lapply(cb_list, attr, "name"))
return(unlist(lapply(cb_list, attr, "name")))
}
add.cb <- function(cb_list, cb) {
......@@ -426,22 +439,24 @@ add.cb <- function(cb_list, cb) {
}
# Return element
cb_list
return(cb_list)
}
categorize.callbacks <- function(cb_list) {
# Check for pre-iteration or post-iteration
list(
pre_iter = Filter(function(x) {
pre <- attr(x, "is_pre_iteration")
!is.null(pre) && pre
}, cb_list),
post_iter = Filter(function(x) {
pre <- attr(x, "is_pre_iteration")
is.null(pre) || !pre
}, cb_list)
return(
list(
pre_iter = Filter(function(x) {
pre <- attr(x, "is_pre_iteration")
!is.null(pre) && pre
}, cb_list),
post_iter = Filter(function(x) {
pre <- attr(x, "is_pre_iteration")
is.null(pre) || !pre
}, cb_list)
)
)
}
......@@ -21,6 +21,8 @@ Booster <- R6::R6Class(
}
return(invisible(NULL))
},
# Initialize will create a starter booster
......@@ -137,6 +139,8 @@ Booster <- R6::R6Class(
self$params <- params
return(invisible(NULL))
},
# Set training data name
......@@ -320,10 +324,12 @@ Booster <- R6::R6Class(
current_iter = function() {
cur_iter <- 0L
lgb.call(
fun_name = "LGBM_BoosterGetCurrentIteration_R"
, ret = cur_iter
, private$handle
return(
lgb.call(
fun_name = "LGBM_BoosterGetCurrentIteration_R"
, ret = cur_iter
, private$handle
)
)
},
......@@ -332,10 +338,12 @@ Booster <- R6::R6Class(
upper_bound = function() {
upper_bound <- 0.0
lgb.call(
fun_name = "LGBM_BoosterGetUpperBoundValue_R"
, ret = upper_bound
, private$handle
return(
lgb.call(
fun_name = "LGBM_BoosterGetUpperBoundValue_R"
, ret = upper_bound
, private$handle
)
)
},
......@@ -344,10 +352,12 @@ Booster <- R6::R6Class(
lower_bound = function() {
lower_bound <- 0.0
lgb.call(
fun_name = "LGBM_BoosterGetLowerBoundValue_R"
, ret = lower_bound
, private$handle
return(
lgb.call(
fun_name = "LGBM_BoosterGetLowerBoundValue_R"
, ret = lower_bound
, private$handle
)
)
},
......@@ -397,17 +407,19 @@ Booster <- R6::R6Class(
}
# Evaluate data
private$inner_eval(
data_name = name
, data_idx = data_idx
, feval = feval
return(
private$inner_eval(
data_name = name
, data_idx = data_idx
, feval = feval
)
)
},
# Evaluation training data
eval_train = function(feval = NULL) {
private$inner_eval(private$name_train_set, 1L, feval)
return(private$inner_eval(private$name_train_set, 1L, feval))
},
# Evaluation validation data
......@@ -463,12 +475,14 @@ Booster <- R6::R6Class(
}
# Return model string
return(lgb.call.return.str(
fun_name = "LGBM_BoosterSaveModelToString_R"
, private$handle
, as.integer(num_iteration)
, as.integer(feature_importance_type)
))
return(
lgb.call.return.str(
fun_name = "LGBM_BoosterSaveModelToString_R"
, private$handle
, as.integer(num_iteration)
, as.integer(feature_importance_type)
)
)
},
......@@ -480,11 +494,13 @@ Booster <- R6::R6Class(
num_iteration <- self$best_iter
}
lgb.call.return.str(
fun_name = "LGBM_BoosterDumpModel_R"
, private$handle
, as.integer(num_iteration)
, as.integer(feature_importance_type)
return(
lgb.call.return.str(
fun_name = "LGBM_BoosterDumpModel_R"
, private$handle
, as.integer(num_iteration)
, as.integer(feature_importance_type)
)
)
},
......@@ -510,7 +526,8 @@ Booster <- R6::R6Class(
# Predict on new data
predictor <- Predictor$new(private$handle, ...)
predictor$predict(
return(
predictor$predict(
data = data
, start_iteration = start_iteration
, num_iteration = num_iteration
......@@ -519,13 +536,14 @@ Booster <- R6::R6Class(
, predcontrib = predcontrib
, header = header
, reshape = reshape
)
)
},
# Transform into predictor
to_predictor = function() {
Predictor$new(private$handle)
return(Predictor$new(private$handle))
},
# Used for save
......@@ -537,6 +555,8 @@ Booster <- R6::R6Class(
# Overwrite model in object
self$raw <- self$save_model_to_string(NULL)
return(invisible(NULL))
}
),
......@@ -780,8 +800,9 @@ predict.lgb.Booster <- function(object,
}
# Return booster predictions
object$predict(
data = data
return(
object$predict(
data = data
, start_iteration = start_iteration
, num_iteration = num_iteration
, rawscore = rawscore
......@@ -789,7 +810,8 @@ predict.lgb.Booster <- function(object,
, predcontrib = predcontrib
, header = header
, reshape = reshape
, ...
, ...
)
)
}
......@@ -896,10 +918,12 @@ lgb.save <- function(booster, filename, num_iteration = NULL) {
}
# Store booster
invisible(booster$save_model(
filename = filename
, num_iteration = num_iteration
))
return(
invisible(booster$save_model(
filename = filename
, num_iteration = num_iteration
))
)
}
......@@ -941,7 +965,7 @@ lgb.dump <- function(booster, num_iteration = NULL) {
}
# Return booster at requested iteration
booster$dump_model(num_iteration = num_iteration)
return(booster$dump_model(num_iteration = num_iteration))
}
......@@ -1045,5 +1069,5 @@ lgb.get.eval.result <- function(booster, data_name, eval_name, iters = NULL, is_
iters <- iters - delta
# Return requested result
as.numeric(result[iters])
return(as.numeric(result[iters]))
}
......@@ -18,6 +18,8 @@ Dataset <- R6::R6Class(
}
return(invisible(NULL))
},
# Initialize will create a starter dataset
......@@ -85,6 +87,8 @@ Dataset <- R6::R6Class(
private$info <- info
private$version <- 0L
return(invisible(NULL))
},
create_valid = function(data,
......@@ -325,16 +329,18 @@ Dataset <- R6::R6Class(
num_col <- 0L
# Get numeric data and numeric features
c(
lgb.call(
fun_name = "LGBM_DatasetGetNumData_R"
, ret = num_row
, private$handle
),
lgb.call(
fun_name = "LGBM_DatasetGetNumFeature_R"
, ret = num_col
, private$handle
return(
c(
lgb.call(
fun_name = "LGBM_DatasetGetNumData_R"
, ret = num_row
, private$handle
),
lgb.call(
fun_name = "LGBM_DatasetGetNumFeature_R"
, ret = num_col
, private$handle
)
)
)
......@@ -342,7 +348,7 @@ Dataset <- R6::R6Class(
# Check if dgCMatrix (sparse matrix column compressed)
# NOTE: requires Matrix package
dim(private$raw_data)
return(dim(private$raw_data))
} else {
......@@ -368,12 +374,12 @@ Dataset <- R6::R6Class(
, private$handle
)
private$colnames <- as.character(base::strsplit(cnames, "\t")[[1L]])
private$colnames
return(private$colnames)
} else if (is.matrix(private$raw_data) || methods::is(private$raw_data, "dgCMatrix")) {
# Check if dgCMatrix (sparse matrix column compressed)
colnames(private$raw_data)
return(colnames(private$raw_data))
} else {
......@@ -470,7 +476,7 @@ Dataset <- R6::R6Class(
}
}
private$info[[name]]
return(private$info[[name]])
},
......@@ -522,17 +528,19 @@ Dataset <- R6::R6Class(
slice = function(idxset, ...) {
# Perform slicing
Dataset$new(
data = NULL
, params = private$params
, reference = self
, colnames = private$colnames
, categorical_feature = private$categorical_feature
, predictor = private$predictor
, free_raw_data = private$free_raw_data
, used_indices = sort(idxset, decreasing = FALSE)
, info = NULL
, ...
return(
Dataset$new(
data = NULL
, params = private$params
, reference = self
, colnames = private$colnames
, categorical_feature = private$categorical_feature
, predictor = private$predictor
, free_raw_data = private$free_raw_data
, used_indices = sort(idxset, decreasing = FALSE)
, info = NULL
, ...
)
)
},
......@@ -679,7 +687,7 @@ Dataset <- R6::R6Class(
if (lgb.is.null.handle(x = private$handle)) {
self$construct()
}
private$handle
return(private$handle)
},
......@@ -753,18 +761,20 @@ lgb.Dataset <- function(data,
...) {
# Create new dataset
invisible(Dataset$new(
data = data
, params = params
, reference = reference
, colnames = colnames
, categorical_feature = categorical_feature
, predictor = NULL
, free_raw_data = free_raw_data
, used_indices = NULL
, info = info
, ...
))
return(
invisible(Dataset$new(
data = data
, params = params
, reference = reference
, colnames = colnames
, categorical_feature = categorical_feature
, predictor = NULL
, free_raw_data = free_raw_data
, used_indices = NULL
, info = info
, ...
))
)
}
......@@ -796,7 +806,7 @@ lgb.Dataset.create.valid <- function(dataset, data, info = list(), ...) {
}
# Create validation dataset
invisible(dataset$create_valid(data = data, info = info, ...))
return(invisible(dataset$create_valid(data = data, info = info, ...)))
}
......@@ -822,7 +832,7 @@ lgb.Dataset.construct <- function(dataset) {
}
# Construct the dataset
invisible(dataset$construct())
return(invisible(dataset$construct()))
}
......@@ -856,7 +866,7 @@ dim.lgb.Dataset <- function(x, ...) {
stop("dim.lgb.Dataset: input data should be an lgb.Dataset object")
}
x$dim()
return(x$dim())
}
......@@ -893,7 +903,7 @@ dimnames.lgb.Dataset <- function(x) {
}
# Return dimension names
list(NULL, x$get_colnames())
return(list(NULL, x$get_colnames()))
}
......@@ -932,7 +942,7 @@ dimnames.lgb.Dataset <- function(x) {
# Set column names properly, and return
x$set_colnames(colnames = value[[2L]])
x
return(x)
}
......@@ -970,7 +980,7 @@ slice.lgb.Dataset <- function(dataset, idxset, ...) {
}
# Return sliced set
invisible(dataset$slice(idxset = idxset, ...))
return(invisible(dataset$slice(idxset = idxset, ...)))
}
......@@ -1020,7 +1030,7 @@ getinfo.lgb.Dataset <- function(dataset, name, ...) {
stop("getinfo.lgb.Dataset: input dataset should be an lgb.Dataset object")
}
dataset$getinfo(name = name)
return(dataset$getinfo(name = name))
}
......@@ -1074,7 +1084,7 @@ setinfo.lgb.Dataset <- function(dataset, name, info, ...) {
}
# Set information
invisible(dataset$setinfo(name = name, info = info))
return(invisible(dataset$setinfo(name = name, info = info)))
}
#' @name lgb.Dataset.set.categorical
......@@ -1106,7 +1116,7 @@ lgb.Dataset.set.categorical <- function(dataset, categorical_feature) {
}
# Set categoricals
invisible(dataset$set_categorical_feature(categorical_feature = categorical_feature))
return(invisible(dataset$set_categorical_feature(categorical_feature = categorical_feature)))
}
......@@ -1138,7 +1148,7 @@ lgb.Dataset.set.reference <- function(dataset, reference) {
}
# Set reference
invisible(dataset$set_reference(reference = reference))
return(invisible(dataset$set_reference(reference = reference)))
}
#' @name lgb.Dataset.save
......@@ -1171,5 +1181,5 @@ lgb.Dataset.save <- function(dataset, fname) {
}
# Store binary
invisible(dataset$save_binary(fname = fname))
return(invisible(dataset$save_binary(fname = fname)))
}
......@@ -23,6 +23,8 @@ Predictor <- R6::R6Class(
}
return(invisible(NULL))
},
# Initialize will create a starter model
......@@ -59,16 +61,20 @@ Predictor <- R6::R6Class(
class(handle) <- "lgb.Booster.handle"
private$handle <- handle
return(invisible(NULL))
},
# Get current iteration
current_iter = function() {
cur_iter <- 0L
lgb.call(
fun_name = "LGBM_BoosterGetCurrentIteration_R"
, ret = cur_iter
, private$handle
return(
lgb.call(
fun_name = "LGBM_BoosterGetCurrentIteration_R"
, ret = cur_iter
, private$handle
)
)
},
......
......@@ -9,10 +9,11 @@ CVBooster <- R6::R6Class(
boosters = list(),
initialize = function(x) {
self$boosters <- x
return(invisible(NULL))
},
reset_parameter = function(new_params) {
for (x in boosters) { x$reset_parameter(new_params) }
self
return(invisible(self))
}
)
)
......@@ -563,7 +564,7 @@ lgb.stratified.folds <- function(y, k = 10L) {
out <- split(seq(along = y), foldVector)
names(out) <- NULL
out
return(out)
}
lgb.merge.cv.result <- function(msg, showsd = TRUE) {
......@@ -615,9 +616,11 @@ lgb.merge.cv.result <- function(msg, showsd = TRUE) {
}
# Return errors
list(
eval_list = ret_eval
, eval_err_list = ret_eval_err
return(
list(
eval_list = ret_eval
, eval_err_list = ret_eval_err
)
)
}
......@@ -137,9 +137,11 @@ single.tree.interprete <- function(tree_dt,
, current_value = leaf_dt[["leaf_value"]]
)
data.table::data.table(
Feature = feature_seq
, Contribution = diff.default(value_seq)
return(
data.table::data.table(
Feature = feature_seq
, Contribution = diff.default(value_seq)
)
)
}
......
......@@ -91,6 +91,6 @@ lgb.plot.importance <- function(tree_imp,
, las = 1L
)]
invisible(tree_imp)
return(invisible(tree_imp))
}
......@@ -124,6 +124,7 @@ lgb.plot.interpretation <- function(tree_interpretation_dt,
}
}
return(invisible(NULL))
}
#' @importFrom graphics barplot
......
......@@ -7,29 +7,31 @@
# are returned from the C++ side. For example, if you use `metric = "mse"` in your code,
# the metric name `"l2"` will be returned.
.METRICS_HIGHER_BETTER <- function() {
return(c(
"l1" = FALSE
, "l2" = FALSE
, "mape" = FALSE
, "rmse" = FALSE
, "quantile" = FALSE
, "huber" = FALSE
, "fair" = FALSE
, "poisson" = FALSE
, "gamma" = FALSE
, "gamma_deviance" = FALSE
, "tweedie" = FALSE
, "ndcg" = TRUE
, "map" = TRUE
, "auc" = TRUE
, "average_precision" = TRUE
, "binary_logloss" = FALSE
, "binary_error" = FALSE
, "auc_mu" = TRUE
, "multi_logloss" = FALSE
, "multi_error" = FALSE
, "cross_entropy" = FALSE
, "cross_entropy_lambda" = FALSE
, "kullback_leibler" = FALSE
))
return(
c(
"l1" = FALSE
, "l2" = FALSE
, "mape" = FALSE
, "rmse" = FALSE
, "quantile" = FALSE
, "huber" = FALSE
, "fair" = FALSE
, "poisson" = FALSE
, "gamma" = FALSE
, "gamma_deviance" = FALSE
, "tweedie" = FALSE
, "ndcg" = TRUE
, "map" = TRUE
, "auc" = TRUE
, "average_precision" = TRUE
, "binary_logloss" = FALSE
, "binary_error" = FALSE
, "auc_mu" = TRUE
, "multi_logloss" = FALSE
, "multi_error" = FALSE
, "cross_entropy" = FALSE
, "cross_entropy_lambda" = FALSE
, "kullback_leibler" = FALSE
)
)
}
......@@ -66,6 +66,8 @@ saveRDS.lgb.Booster <- function(object,
# Free model from memory
object$raw <- NA
return(invisible(NULL))
} else {
saveRDS(
......@@ -77,6 +79,8 @@ saveRDS.lgb.Booster <- function(object,
, refhook = refhook
)
return(invisible(NULL))
}
}
lgb.is.Booster <- function(x) {
lgb.check.r6.class(object = x, name = "lgb.Booster")
return(lgb.check.r6.class(object = x, name = "lgb.Booster"))
}
lgb.is.Dataset <- function(x) {
lgb.check.r6.class(object = x, name = "lgb.Dataset")
return(lgb.check.r6.class(object = x, name = "lgb.Dataset"))
}
lgb.null.handle <- function() {
......@@ -15,7 +15,7 @@ lgb.null.handle <- function() {
}
lgb.is.null.handle <- function(x) {
is.null(x) || is.na(x)
return(is.null(x) || is.na(x))
}
lgb.encode.char <- function(arr, len) {
......@@ -54,6 +54,9 @@ lgb.last_error <- function() {
}
stop("api error: ", lgb.encode.char(arr = err_msg, len = act_len))
return(invisible(NULL))
}
lgb.call <- function(fun_name, ret, ...) {
......@@ -232,14 +235,14 @@ lgb.c_str <- function(x) {
ret <- charToRaw(as.character(x))
ret <- c(ret, as.raw(0L))
ret
return(ret)
}
lgb.check.r6.class <- function(object, name) {
# Check for non-existence of R6 class or named class
all(c("R6", name) %in% class(object))
return(all(c("R6", name) %in% class(object)))
}
......
......@@ -53,6 +53,7 @@ install_libs_content <- .replace_flag("use_msys2", USING_MSYS2, install_libs_con
if (!all(res)) {
stop("Copying files failed!")
}
return(invisible(NULL))
}
# system() will not raise an R exception if the process called
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment