1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359
|
#' PCA Signal Extraction
#'
#' `step_pca` creates a *specification* of a recipe step that will convert
#' numeric data into one or more principal components.
#'
#' @inheritParams step_center
#' @param role For model terms created by this step, what analysis role should
#' they be assigned? By default, the new columns created by this step from
#' the original variables will be used as _predictors_ in a model.
#' @param num_comp The number of components to retain as new predictors.
#' If `num_comp` is greater than the number of columns or the number of
#' possible components, a smaller value will be used. If `num_comp = 0`
#' is set then no transformation is done and selected variables will
#' stay unchanged.
#' @param threshold A fraction of the total variance that should be covered by
#' the components. For example, `threshold = .75` means that `step_pca` should
#' generate enough components to capture 75 percent of the variability in the
#' variables. Note: using this argument will override and reset any value given
#' to `num_comp`.
#' @param options A list of options to the default method for
#' [stats::prcomp()]. Argument defaults are set to `retx = FALSE`, `center =
#' FALSE`, `scale. = FALSE`, and `tol = NULL`. **Note** that the argument `x`
#' should not be passed here (or at all).
#' @param res The [stats::prcomp.default()] object is stored here once this
#' preprocessing step has be trained by [prep()].
#' @param columns A character string of variable names that will
#' be populated elsewhere.
#' @param prefix A character string for the prefix of the resulting new
#' variables. See notes below.
#' @param keep_original_cols A logical to keep the original variables in the
#' output. Defaults to `FALSE`.
#' @template step-return
#' @family multivariate transformation steps
#' @export
#' @details
#' Principal component analysis (PCA) is a transformation of a
#' group of variables that produces a new set of artificial
#' features or components. These components are designed to capture
#' the maximum amount of information (i.e. variance) in the
#' original variables. Also, the components are statistically
#' independent from one another. This means that they can be used
#' to combat large inter-variables correlations in a data set.
#'
#' It is advisable to standardize the variables prior to running
#' PCA. Here, each variable will be centered and scaled prior to
#' the PCA calculation. This can be changed using the
#' `options` argument or by using [step_center()]
#' and [step_scale()].
#'
#' The argument `num_comp` controls the number of components that
#' will be retained (the original variables that are used to derive
#' the components are removed from the data). The new components
#' will have names that begin with `prefix` and a sequence of
#' numbers. The variable names are padded with zeros. For example,
#' if `num_comp < 10`, their names will be `PC1` - `PC9`.
#' If `num_comp = 101`, the names would be `PC001` -
#' `PC101`.
#'
#' Alternatively, `threshold` can be used to determine the
#' number of components that are required to capture a specified
#' fraction of the total variance in the variables.
#'
#' # Tidying
#'
#' When you [`tidy()`][tidy.recipe()] this step, use either `type = "coef"`
#' for the variable loadings per component or `type = "variance"` for how
#' much variance each component accounts for.
#'
#' @template case-weights-unsupervised
#'
#' @references Jolliffe, I. T. (2010). *Principal Component
#' Analysis*. Springer.
#'
#' @examples
#' rec <- recipe(~., data = USArrests)
#' pca_trans <- rec %>%
#' step_normalize(all_numeric()) %>%
#' step_pca(all_numeric(), num_comp = 3)
#' pca_estimates <- prep(pca_trans, training = USArrests)
#' pca_data <- bake(pca_estimates, USArrests)
#'
#' rng <- extendrange(c(pca_data$PC1, pca_data$PC2))
#' plot(pca_data$PC1, pca_data$PC2,
#' xlim = rng, ylim = rng
#' )
#'
#' with_thresh <- rec %>%
#' step_normalize(all_numeric()) %>%
#' step_pca(all_numeric(), threshold = .99)
#' with_thresh <- prep(with_thresh, training = USArrests)
#' bake(with_thresh, USArrests)
#'
#' tidy(pca_trans, number = 2)
#' tidy(pca_estimates, number = 2)
step_pca <- function(recipe,
...,
role = "predictor",
trained = FALSE,
num_comp = 5,
threshold = NA,
options = list(),
res = NULL,
columns = NULL,
prefix = "PC",
keep_original_cols = FALSE,
skip = FALSE,
id = rand_id("pca")) {
if (!is_tune(threshold) & !is_varying(threshold)) {
if (!is.na(threshold) && (threshold > 1 | threshold <= 0)) {
rlang::abort("`threshold` should be on (0, 1].")
}
}
add_step(
recipe,
step_pca_new(
terms = enquos(...),
role = role,
trained = trained,
num_comp = num_comp,
threshold = threshold,
options = options,
res = res,
columns = columns,
prefix = prefix,
keep_original_cols = keep_original_cols,
skip = skip,
id = id,
case_weights = NULL
)
)
}
step_pca_new <-
function(terms, role, trained, num_comp, threshold, options, res, columns,
prefix, keep_original_cols, skip, id, case_weights) {
step(
subclass = "pca",
terms = terms,
role = role,
trained = trained,
num_comp = num_comp,
threshold = threshold,
options = options,
res = res,
columns = columns,
prefix = prefix,
keep_original_cols = keep_original_cols,
skip = skip,
id = id,
case_weights = case_weights
)
}
#' @export
prep.step_pca <- function(x, training, info = NULL, ...) {
col_names <- recipes_eval_select(x$terms, training, info)
check_type(training[, col_names], types = c("double", "integer"))
wts <- get_case_weights(info, training)
were_weights_used <- are_weights_used(wts, unsupervised = TRUE)
if (isFALSE(were_weights_used)) {
wts <- NULL
}
if (x$num_comp > 0 && length(col_names) > 0) {
if (is.null(wts)) {
prc_call <-
expr(prcomp(
retx = FALSE,
center = FALSE,
scale. = FALSE,
tol = NULL
))
if (length(x$options) > 0) {
prc_call <- rlang::call_modify(prc_call, !!!x$options)
}
prc_call$x <- expr(training[, col_names, drop = FALSE])
prc_obj <- eval(prc_call)
## decide on removing prc elements that aren't used in new projections
## e.g. `sdev` etc.
} else {
prc_obj <- pca_wts(training[, col_names, drop = FALSE], wts = wts)
}
x$num_comp <- min(x$num_comp, length(col_names))
if (!is.na(x$threshold)) {
total_var <- sum(prc_obj$sdev^2)
num_comp <-
which.max(cumsum(prc_obj$sdev^2 / total_var) >= x$threshold)
if (length(num_comp) == 0) {
num_comp <- length(prc_obj$sdev)
}
x$num_comp <- num_comp
}
} else {
prc_obj <- NULL
}
step_pca_new(
terms = x$terms,
role = x$role,
trained = TRUE,
num_comp = x$num_comp,
threshold = x$threshold,
options = x$options,
res = prc_obj,
columns = col_names,
prefix = x$prefix,
keep_original_cols = get_keep_original_cols(x),
skip = x$skip,
id = x$id,
case_weights = were_weights_used
)
}
#' @export
bake.step_pca <- function(object, new_data, ...) {
if (is.null(object$columns)) {
object$columns <- stats::setNames(nm = rownames(object$res$rotation))
}
if (length(object$columns) > 0 && !all(is.na(object$res$rotation))) {
check_new_data(object$columns, object, new_data)
pca_vars <- rownames(object$res$rotation)
comps <- scale(new_data[, pca_vars], object$res$center, object$res$scale) %*%
object$res$rotation
comps <- comps[, 1:object$num_comp, drop = FALSE]
comps <- check_name(comps, new_data, object)
new_data <- bind_cols(new_data, as_tibble(comps))
keep_original_cols <- get_keep_original_cols(object)
if (!keep_original_cols) {
new_data <- new_data[, !(colnames(new_data) %in% pca_vars), drop = FALSE]
}
}
new_data
}
print.step_pca <-
function(x, width = max(20, options()$width - 29), ...) {
if (x$trained) {
if (is.null(x$columns)) {
x$columns <- stats::setNames(nm = rownames(x$res$rotation))
}
if (length(x$columns) == 0 || all(is.na(x$res$rotation))) {
title <- "No PCA components were extracted from "
columns <- names(x$columns)
} else {
title <- glue::glue("PCA extraction with ")
columns <- rownames(x$res$rotation)
}
} else {
title <- "PCA extraction with "
}
print_step(columns, x$terms, x$trained, title, width,
case_weights = x$case_weights)
invisible(x)
}
pca_coefs <- function(x) {
if (x$num_comp > 0 && length(x$columns) > 0) {
rot <- as.data.frame(x$res$rotation)
npc <- ncol(rot)
res <- utils::stack(rot)
colnames(res) <- c("value", "component")
res$component <- as.character(res$component)
res$terms <- rep(unname(x$columns), npc)
res <- as_tibble(res)[, c("terms", "value", "component")]
} else {
res <- tibble::tibble(
terms = unname(x$columns), value = rlang::na_dbl,
component = rlang::na_chr
)
}
res
}
pca_variances <- function(x) {
if (x$num_comp > 0 && length(x$columns) > 0) {
variances <- x$res$sdev^2
p <- length(variances)
tot <- sum(variances)
y <- c(
variances,
cumsum(variances),
variances / tot * 100,
cumsum(variances) / tot * 100
)
x <-
rep(
c(
"variance",
"cumulative variance",
"percent variance",
"cumulative percent variance"
),
each = p
)
res <- tibble::tibble(
terms = x,
value = y,
component = rep(1:p, 4)
)
} else {
res <- tibble::tibble(
terms = unname(x$columns),
value = rep(rlang::na_dbl, length(x$columns)),
component = rep(rlang::na_chr, length(x$columns))
)
}
res
}
#' @rdname tidy.recipe
#' @param type For `step_pca`, either `"coef"` (for the variable loadings per
#' component) or `"variance"` (how much variance does each component
#' account for).
#' @export
tidy.step_pca <- function(x, type = "coef", ...) {
if (!is_trained(x)) {
term_names <- sel2char(x$terms)
res <- tibble(
terms = term_names,
value = na_dbl,
component = na_chr
)
} else {
type <- match.arg(type, c("coef", "variance"))
if (type == "coef") {
res <- pca_coefs(x)
} else {
res <- pca_variances(x)
}
}
res$id <- x$id
res
}
#' @export
tunable.step_pca <- function(x, ...) {
tibble::tibble(
name = c("num_comp", "threshold"),
call_info = list(
list(pkg = "dials", fun = "num_comp", range = c(1L, 4L)),
list(pkg = "dials", fun = "threshold")
),
source = "recipe",
component = "step_pca",
component_id = x$id
)
}
|