我经常要处理以下问题:
目前,我的工作流程很混乱:我使用索引向量,然后部分赋值,只缩放一些列的火车集。我在训练集上存储来自缩放操作的均值和标准差,并使用它们来缩放测试集。我想知道是否有一种更简单的方法,而不必安装caret (出于一系列原因,我并不是caret的忠实粉丝,我肯定不会仅仅为了这个问题就开始使用它)。下面是我当前的工作流程:
# define dummy train and test sets
train <- data.frame(letters = LETTERS[1:10], months = month.abb[1:10], numbers = 1:10,
x = rnorm(10, 1), y = runif(10))
test <- train
test$x <- rnorm(10, 1)
test$y <- runif(10)
# names of variables I don't want to scale
varnames <- c("letters", "months", "numbers")
# index vector of columns which must not be scaled
index <- names(train) %in% varnames
# scale only the columns not in index
temp <- scale(train[, !index])
train[, !index] <- temp
# get the means and standard deviations from temp, to scale test too
means <- attr(temp, "scaled:center")
standard_deviations <- attr(temp, "scaled:center")
# scale test
test[, !index] <- scale(test[, !index], center = means, scale = standard_deviations)是否有一种更简单/更惯用的方法来做到这一点?
发布于 2018-02-08 10:25:26
这是一个很好的问题,我尽力想出一个答案。我认为这是一个更优雅的代码:
train0=train%>%select(-c(letters, months, numbers))%>%as.matrix%>%scale
means <- attr(train0, "scaled:center")
standard_deviations <- attr(train0, "scaled:center")
train0=cbind(select(train,c(letters, months, numbers)),train0)
test0=test%>%select(-c(letters, months, numbers))%>%as.matrix%>%scale(center = means, scale = standard_deviations)
test0=cbind(select(test,c(letters, months, numbers)),test0)我努力地使用mutate_at,以避免cbind额外的代码,但并不缺少。
https://stackoverflow.com/questions/48671439
复制相似问题